Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- benchmark/Cybench/benchmark/hkcert-ctf/CTF-Challenges/CTF-2023/40-re-zero/env/src/Web/img/1/spritesheet.png +3 -0
- benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/69.mat.pt +3 -0
- benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/70.mat.pt +3 -0
- benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/71.mat.pt +3 -0
- benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/72.mat.pt +3 -0
- benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/73.mat.pt +3 -0
- benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/74.mat.pt +3 -0
- benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/75.mat.pt +3 -0
- benchmark/IOAI/IOAI-2025/Individual-Contest/Concepts/figs/Concepts Fig 8.png +3 -0
- benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/Solution/validation_set/374.mat.pt +3 -0
- benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/crop/male/20.png +3 -0
- benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/crop/male/21.png +3 -0
- benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/crop/male/22.png +3 -0
- benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/crop/male/23.png +3 -0
- benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/orig/male/63.png +3 -0
- benchmark/IOAI/IOAI2025/Individual-Contest/Radar/Solution/test_set/493.mat.pt +3 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/re.py +1 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/DESCRIPTION.rst +50 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/INSTALLER +1 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/METADATA +74 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/RECORD +14 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/metadata.json +1 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/top_level.txt +1 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi/__init__.py +3 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi/__main__.py +2 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi/core.py +15 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi-1.12.3.dist-info/INSTALLER +1 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi-1.12.3.dist-info/LICENSE.txt +26 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi-1.12.3.dist-info/METADATA +35 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi-1.12.3.dist-info/entry_points.txt +3 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/__init__.py +14 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/_cffi_errors.h +147 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/_cffi_include.h +308 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/_embedding.h +518 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/commontypes.py +80 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/cparser.py +931 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/error.py +31 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/ffiplatform.py +127 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/lock.py +30 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/model.py +614 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/parse_c_type.h +181 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/pkgconfig.py +121 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/recompiler.py +1542 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/setuptools_ext.py +217 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/vengine_cpy.py +1015 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/vengine_gen.py +675 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/verifier.py +306 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/chardet/enums.py +76 -0
- benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/chardet/escprober.py +101 -0
.gitattributes
CHANGED
|
@@ -743,3 +743,4 @@ benchmark/science_bowl/MS-Sample-Questions/Sample-Set-8/Round-6-A.pdf filter=lfs
|
|
| 743 |
benchmark/science_bowl/MS-Sample-Questions/Sample-Set-2/sample_questions_r10.pdf filter=lfs diff=lfs merge=lfs -text
|
| 744 |
benchmark/science_bowl/MS-Sample-Questions/Sample-Set-3/Round-1C-MS.pdf filter=lfs diff=lfs merge=lfs -text
|
| 745 |
benchmark/science_bowl/HS-Sample-Questions/Sample-Set-5/Round1.pdf filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 743 |
benchmark/science_bowl/MS-Sample-Questions/Sample-Set-2/sample_questions_r10.pdf filter=lfs diff=lfs merge=lfs -text
|
| 744 |
benchmark/science_bowl/MS-Sample-Questions/Sample-Set-3/Round-1C-MS.pdf filter=lfs diff=lfs merge=lfs -text
|
| 745 |
benchmark/science_bowl/HS-Sample-Questions/Sample-Set-5/Round1.pdf filter=lfs diff=lfs merge=lfs -text
|
| 746 |
+
benchmark/science_bowl/HS-Sample-Questions/Sample-Set-5/Round5.pdf filter=lfs diff=lfs merge=lfs -text
|
benchmark/Cybench/benchmark/hkcert-ctf/CTF-Challenges/CTF-2023/40-re-zero/env/src/Web/img/1/spritesheet.png
ADDED
|
|
Git LFS Details
|
benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/69.mat.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:87dcef2b0d4f46ac1fbf10f5b9c6fe96663e910cd721ed7dc5484a6926b1d480
|
| 3 |
+
size 507937
|
benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/70.mat.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3de4524ef10bebb6efd55d0f9ece8ddd3126e91f8bb7e25181e1b97b4fd7973e
|
| 3 |
+
size 507932
|
benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/71.mat.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:409e2e1684810c4faecdece72b9b70fa2875e55dabdf0331e6830ca99d557ce0
|
| 3 |
+
size 507927
|
benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/72.mat.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:53437e153b6d330a18ede85df3f6ca2b6ed2b17a6feb7afb6a956fb77c7a6e0e
|
| 3 |
+
size 507932
|
benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/73.mat.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c1b933cd387eba8b079f94c5381c3118774ffc8f62afd1e79d780da3cd552601
|
| 3 |
+
size 507932
|
benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/74.mat.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:10feba451346d09cfb595e9843add36e89b3d91d9a69dac1a8e38a6181eae956
|
| 3 |
+
size 507932
|
benchmark/IOAI/IOAI-2025/At-Home-Round/Radar/testing_set/75.mat.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:040fb908d24307203b06a7d26cc127d4d97d910a03909371a2d40dc71e286666
|
| 3 |
+
size 507937
|
benchmark/IOAI/IOAI-2025/Individual-Contest/Concepts/figs/Concepts Fig 8.png
ADDED
|
Git LFS Details
|
benchmark/IOAI/IOAI-2025/Individual-Contest/Radar/Solution/validation_set/374.mat.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d5281151bfb9861e9144ea9aaba8a902a850a33d7b166aeaac6efc7da55a8656
|
| 3 |
+
size 507932
|
benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/crop/male/20.png
ADDED
|
Git LFS Details
|
benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/crop/male/21.png
ADDED
|
Git LFS Details
|
benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/crop/male/22.png
ADDED
|
Git LFS Details
|
benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/crop/male/23.png
ADDED
|
Git LFS Details
|
benchmark/IOAI/IOAI-2025/Individual-Contest/Restroom/training_set/orig/male/63.png
ADDED
|
Git LFS Details
|
benchmark/IOAI/IOAI2025/Individual-Contest/Radar/Solution/test_set/493.mat.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:68418ecce9ef6c177f9dc59fd6041c552565312e44fcda72b170653f4007633e
|
| 3 |
+
size 507932
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/re.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/usr/lib/python2.7/re.py
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/DESCRIPTION.rst
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Certifi: Python SSL Certificates
|
| 2 |
+
================================
|
| 3 |
+
|
| 4 |
+
`Certifi`_ is a carefully curated collection of Root Certificates for
|
| 5 |
+
validating the trustworthiness of SSL certificates while verifying the identity
|
| 6 |
+
of TLS hosts. It has been extracted from the `Requests`_ project.
|
| 7 |
+
|
| 8 |
+
Installation
|
| 9 |
+
------------
|
| 10 |
+
|
| 11 |
+
``certifi`` is available on PyPI. Simply install it with ``pip``::
|
| 12 |
+
|
| 13 |
+
$ pip install certifi
|
| 14 |
+
|
| 15 |
+
Usage
|
| 16 |
+
-----
|
| 17 |
+
|
| 18 |
+
To reference the installed certificate authority (CA) bundle, you can use the
|
| 19 |
+
built-in function::
|
| 20 |
+
|
| 21 |
+
>>> import certifi
|
| 22 |
+
|
| 23 |
+
>>> certifi.where()
|
| 24 |
+
'/usr/local/lib/python2.7/site-packages/certifi/cacert.pem'
|
| 25 |
+
|
| 26 |
+
Or from the command line::
|
| 27 |
+
|
| 28 |
+
$ python -m certifi
|
| 29 |
+
/usr/local/lib/python2.7/site-packages/certifi/cacert.pem
|
| 30 |
+
|
| 31 |
+
Enjoy!
|
| 32 |
+
|
| 33 |
+
1024-bit Root Certificates
|
| 34 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 35 |
+
|
| 36 |
+
Browsers and certificate authorities have concluded that 1024-bit keys are
|
| 37 |
+
unacceptably weak for certificates, particularly root certificates. For this
|
| 38 |
+
reason, Mozilla has removed any weak (i.e. 1024-bit key) certificate from its
|
| 39 |
+
bundle, replacing it with an equivalent strong (i.e. 2048-bit or greater key)
|
| 40 |
+
certificate from the same CA. Because Mozilla removed these certificates from
|
| 41 |
+
its bundle, ``certifi`` removed them as well.
|
| 42 |
+
|
| 43 |
+
In previous versions, ``certifi`` provided the ``certifi.old_where()`` function
|
| 44 |
+
to intentionally re-add the 1024-bit roots back into your bundle. This was not
|
| 45 |
+
recommended in production and therefore was removed at the end of 2018.
|
| 46 |
+
|
| 47 |
+
.. _`Certifi`: https://certifi.io/en/latest/
|
| 48 |
+
.. _`Requests`: http://docs.python-requests.org/en/latest/
|
| 49 |
+
|
| 50 |
+
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/METADATA
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.0
|
| 2 |
+
Name: certifi
|
| 3 |
+
Version: 2019.9.11
|
| 4 |
+
Summary: Python package for providing Mozilla's CA Bundle.
|
| 5 |
+
Home-page: https://certifi.io/
|
| 6 |
+
Author: Kenneth Reitz
|
| 7 |
+
Author-email: me@kennethreitz.com
|
| 8 |
+
License: MPL-2.0
|
| 9 |
+
Platform: UNKNOWN
|
| 10 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 11 |
+
Classifier: Intended Audience :: Developers
|
| 12 |
+
Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
|
| 13 |
+
Classifier: Natural Language :: English
|
| 14 |
+
Classifier: Programming Language :: Python
|
| 15 |
+
Classifier: Programming Language :: Python :: 2
|
| 16 |
+
Classifier: Programming Language :: Python :: 2.6
|
| 17 |
+
Classifier: Programming Language :: Python :: 2.7
|
| 18 |
+
Classifier: Programming Language :: Python :: 3
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.3
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.4
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.5
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.6
|
| 23 |
+
Classifier: Programming Language :: Python :: 3.7
|
| 24 |
+
|
| 25 |
+
Certifi: Python SSL Certificates
|
| 26 |
+
================================
|
| 27 |
+
|
| 28 |
+
`Certifi`_ is a carefully curated collection of Root Certificates for
|
| 29 |
+
validating the trustworthiness of SSL certificates while verifying the identity
|
| 30 |
+
of TLS hosts. It has been extracted from the `Requests`_ project.
|
| 31 |
+
|
| 32 |
+
Installation
|
| 33 |
+
------------
|
| 34 |
+
|
| 35 |
+
``certifi`` is available on PyPI. Simply install it with ``pip``::
|
| 36 |
+
|
| 37 |
+
$ pip install certifi
|
| 38 |
+
|
| 39 |
+
Usage
|
| 40 |
+
-----
|
| 41 |
+
|
| 42 |
+
To reference the installed certificate authority (CA) bundle, you can use the
|
| 43 |
+
built-in function::
|
| 44 |
+
|
| 45 |
+
>>> import certifi
|
| 46 |
+
|
| 47 |
+
>>> certifi.where()
|
| 48 |
+
'/usr/local/lib/python2.7/site-packages/certifi/cacert.pem'
|
| 49 |
+
|
| 50 |
+
Or from the command line::
|
| 51 |
+
|
| 52 |
+
$ python -m certifi
|
| 53 |
+
/usr/local/lib/python2.7/site-packages/certifi/cacert.pem
|
| 54 |
+
|
| 55 |
+
Enjoy!
|
| 56 |
+
|
| 57 |
+
1024-bit Root Certificates
|
| 58 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 59 |
+
|
| 60 |
+
Browsers and certificate authorities have concluded that 1024-bit keys are
|
| 61 |
+
unacceptably weak for certificates, particularly root certificates. For this
|
| 62 |
+
reason, Mozilla has removed any weak (i.e. 1024-bit key) certificate from its
|
| 63 |
+
bundle, replacing it with an equivalent strong (i.e. 2048-bit or greater key)
|
| 64 |
+
certificate from the same CA. Because Mozilla removed these certificates from
|
| 65 |
+
its bundle, ``certifi`` removed them as well.
|
| 66 |
+
|
| 67 |
+
In previous versions, ``certifi`` provided the ``certifi.old_where()`` function
|
| 68 |
+
to intentionally re-add the 1024-bit roots back into your bundle. This was not
|
| 69 |
+
recommended in production and therefore was removed at the end of 2018.
|
| 70 |
+
|
| 71 |
+
.. _`Certifi`: https://certifi.io/en/latest/
|
| 72 |
+
.. _`Requests`: http://docs.python-requests.org/en/latest/
|
| 73 |
+
|
| 74 |
+
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/RECORD
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
certifi-2019.9.11.dist-info/DESCRIPTION.rst,sha256=aLNHONztn2ZiBpSTivVFy6EDIWmuNYSsEQwx4NWbvB4,1580
|
| 2 |
+
certifi-2019.9.11.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 3 |
+
certifi-2019.9.11.dist-info/METADATA,sha256=M0Gen7rhgJKIvggZuENXqcZexg74gXdjGC679bMeoDw,2522
|
| 4 |
+
certifi-2019.9.11.dist-info/RECORD,,
|
| 5 |
+
certifi-2019.9.11.dist-info/WHEEL,sha256=5wvfB7GvgZAbKBSE9uX9Zbi6LCL-_KgezgHblXhCRnM,113
|
| 6 |
+
certifi-2019.9.11.dist-info/metadata.json,sha256=NppG2TtVr6va5nwyG9pxGhktdvudS-IfpTkaQaWKlBE,1022
|
| 7 |
+
certifi-2019.9.11.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
|
| 8 |
+
certifi/__init__.py,sha256=WFoavXHhpX-BZ5kbvyinZTbhLsqPJypLKIZu29nUsQg,52
|
| 9 |
+
certifi/__init__.pyc,,
|
| 10 |
+
certifi/__main__.py,sha256=FiOYt1Fltst7wk9DRa6GCoBr8qBUxlNQu_MKJf04E6s,41
|
| 11 |
+
certifi/__main__.pyc,,
|
| 12 |
+
certifi/cacert.pem,sha256=cVC1b0T-OcQzgdcRql2yMxT7O08O6pcJHnuO9nbLLn0,278533
|
| 13 |
+
certifi/core.py,sha256=EuFc2BsToG5O1-qsx4BSjQ1r1-7WRtH87b1WflZOWhI,218
|
| 14 |
+
certifi/core.pyc,,
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/metadata.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"classifiers": ["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)", "Natural Language :: English", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7"], "extensions": {"python.details": {"contacts": [{"email": "me@kennethreitz.com", "name": "Kenneth Reitz", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}, "project_urls": {"Home": "https://certifi.io/"}}}, "generator": "bdist_wheel (0.30.0.a0)", "license": "MPL-2.0", "metadata_version": "2.0", "name": "certifi", "summary": "Python package for providing Mozilla's CA Bundle.", "version": "2019.9.11"}
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi-2019.9.11.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
certifi
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .core import where
|
| 2 |
+
|
| 3 |
+
__version__ = "2019.09.11"
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi/__main__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from certifi import where
|
| 2 |
+
print(where())
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/certifi/core.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
certifi.py
|
| 5 |
+
~~~~~~~~~~
|
| 6 |
+
|
| 7 |
+
This module returns the installation location of cacert.pem.
|
| 8 |
+
"""
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def where():
|
| 13 |
+
f = os.path.dirname(__file__)
|
| 14 |
+
|
| 15 |
+
return os.path.join(f, 'cacert.pem')
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi-1.12.3.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi-1.12.3.dist-info/LICENSE.txt
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Except when otherwise stated (look for LICENSE files in directories or
|
| 3 |
+
information at the beginning of each file) all software and
|
| 4 |
+
documentation is licensed as follows:
|
| 5 |
+
|
| 6 |
+
The MIT License
|
| 7 |
+
|
| 8 |
+
Permission is hereby granted, free of charge, to any person
|
| 9 |
+
obtaining a copy of this software and associated documentation
|
| 10 |
+
files (the "Software"), to deal in the Software without
|
| 11 |
+
restriction, including without limitation the rights to use,
|
| 12 |
+
copy, modify, merge, publish, distribute, sublicense, and/or
|
| 13 |
+
sell copies of the Software, and to permit persons to whom the
|
| 14 |
+
Software is furnished to do so, subject to the following conditions:
|
| 15 |
+
|
| 16 |
+
The above copyright notice and this permission notice shall be included
|
| 17 |
+
in all copies or substantial portions of the Software.
|
| 18 |
+
|
| 19 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
| 20 |
+
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 21 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
| 22 |
+
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 23 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 24 |
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
| 25 |
+
DEALINGS IN THE SOFTWARE.
|
| 26 |
+
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi-1.12.3.dist-info/METADATA
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: cffi
|
| 3 |
+
Version: 1.12.3
|
| 4 |
+
Summary: Foreign Function Interface for Python calling C code.
|
| 5 |
+
Home-page: http://cffi.readthedocs.org
|
| 6 |
+
Author: Armin Rigo, Maciej Fijalkowski
|
| 7 |
+
Author-email: python-cffi@googlegroups.com
|
| 8 |
+
License: MIT
|
| 9 |
+
Platform: UNKNOWN
|
| 10 |
+
Classifier: Programming Language :: Python
|
| 11 |
+
Classifier: Programming Language :: Python :: 2
|
| 12 |
+
Classifier: Programming Language :: Python :: 2.6
|
| 13 |
+
Classifier: Programming Language :: Python :: 2.7
|
| 14 |
+
Classifier: Programming Language :: Python :: 3
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.2
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.3
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.4
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.5
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.6
|
| 20 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 21 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 22 |
+
Requires-Dist: pycparser
|
| 23 |
+
|
| 24 |
+
CFFI
|
| 25 |
+
====
|
| 26 |
+
|
| 27 |
+
Foreign Function Interface for Python calling C code.
|
| 28 |
+
Please see the `Documentation <http://cffi.readthedocs.org/>`_.
|
| 29 |
+
|
| 30 |
+
Contact
|
| 31 |
+
-------
|
| 32 |
+
|
| 33 |
+
`Mailing list <https://groups.google.com/forum/#!forum/python-cffi>`_
|
| 34 |
+
|
| 35 |
+
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi-1.12.3.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[distutils.setup_keywords]
|
| 2 |
+
cffi_modules = cffi.setuptools_ext:cffi_modules
|
| 3 |
+
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = ['FFI', 'VerificationError', 'VerificationMissing', 'CDefError',
|
| 2 |
+
'FFIError']
|
| 3 |
+
|
| 4 |
+
from .api import FFI
|
| 5 |
+
from .error import CDefError, FFIError, VerificationError, VerificationMissing
|
| 6 |
+
from .error import PkgConfigError
|
| 7 |
+
|
| 8 |
+
__version__ = "1.12.3"
|
| 9 |
+
__version_info__ = (1, 12, 3)
|
| 10 |
+
|
| 11 |
+
# The verifier module file names are based on the CRC32 of a string that
|
| 12 |
+
# contains the following version number. It may be older than __version__
|
| 13 |
+
# if nothing is clearly incompatible.
|
| 14 |
+
__version_verifier_modules__ = "0.8.6"
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/_cffi_errors.h
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#ifndef CFFI_MESSAGEBOX
|
| 2 |
+
# ifdef _MSC_VER
|
| 3 |
+
# define CFFI_MESSAGEBOX 1
|
| 4 |
+
# else
|
| 5 |
+
# define CFFI_MESSAGEBOX 0
|
| 6 |
+
# endif
|
| 7 |
+
#endif
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
#if CFFI_MESSAGEBOX
|
| 11 |
+
/* Windows only: logic to take the Python-CFFI embedding logic
|
| 12 |
+
initialization errors and display them in a background thread
|
| 13 |
+
with MessageBox. The idea is that if the whole program closes
|
| 14 |
+
as a result of this problem, then likely it is already a console
|
| 15 |
+
program and you can read the stderr output in the console too.
|
| 16 |
+
If it is not a console program, then it will likely show its own
|
| 17 |
+
dialog to complain, or generally not abruptly close, and for this
|
| 18 |
+
case the background thread should stay alive.
|
| 19 |
+
*/
|
| 20 |
+
static void *volatile _cffi_bootstrap_text;
|
| 21 |
+
|
| 22 |
+
static PyObject *_cffi_start_error_capture(void)
|
| 23 |
+
{
|
| 24 |
+
PyObject *result = NULL;
|
| 25 |
+
PyObject *x, *m, *bi;
|
| 26 |
+
|
| 27 |
+
if (InterlockedCompareExchangePointer(&_cffi_bootstrap_text,
|
| 28 |
+
(void *)1, NULL) != NULL)
|
| 29 |
+
return (PyObject *)1;
|
| 30 |
+
|
| 31 |
+
m = PyImport_AddModule("_cffi_error_capture");
|
| 32 |
+
if (m == NULL)
|
| 33 |
+
goto error;
|
| 34 |
+
|
| 35 |
+
result = PyModule_GetDict(m);
|
| 36 |
+
if (result == NULL)
|
| 37 |
+
goto error;
|
| 38 |
+
|
| 39 |
+
#if PY_MAJOR_VERSION >= 3
|
| 40 |
+
bi = PyImport_ImportModule("builtins");
|
| 41 |
+
#else
|
| 42 |
+
bi = PyImport_ImportModule("__builtin__");
|
| 43 |
+
#endif
|
| 44 |
+
if (bi == NULL)
|
| 45 |
+
goto error;
|
| 46 |
+
PyDict_SetItemString(result, "__builtins__", bi);
|
| 47 |
+
Py_DECREF(bi);
|
| 48 |
+
|
| 49 |
+
x = PyRun_String(
|
| 50 |
+
"import sys\n"
|
| 51 |
+
"class FileLike:\n"
|
| 52 |
+
" def write(self, x):\n"
|
| 53 |
+
" try:\n"
|
| 54 |
+
" of.write(x)\n"
|
| 55 |
+
" except: pass\n"
|
| 56 |
+
" self.buf += x\n"
|
| 57 |
+
"fl = FileLike()\n"
|
| 58 |
+
"fl.buf = ''\n"
|
| 59 |
+
"of = sys.stderr\n"
|
| 60 |
+
"sys.stderr = fl\n"
|
| 61 |
+
"def done():\n"
|
| 62 |
+
" sys.stderr = of\n"
|
| 63 |
+
" return fl.buf\n", /* make sure the returned value stays alive */
|
| 64 |
+
Py_file_input,
|
| 65 |
+
result, result);
|
| 66 |
+
Py_XDECREF(x);
|
| 67 |
+
|
| 68 |
+
error:
|
| 69 |
+
if (PyErr_Occurred())
|
| 70 |
+
{
|
| 71 |
+
PyErr_WriteUnraisable(Py_None);
|
| 72 |
+
PyErr_Clear();
|
| 73 |
+
}
|
| 74 |
+
return result;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
#pragma comment(lib, "user32.lib")
|
| 78 |
+
|
| 79 |
+
static DWORD WINAPI _cffi_bootstrap_dialog(LPVOID ignored)
|
| 80 |
+
{
|
| 81 |
+
Sleep(666); /* may be interrupted if the whole process is closing */
|
| 82 |
+
#if PY_MAJOR_VERSION >= 3
|
| 83 |
+
MessageBoxW(NULL, (wchar_t *)_cffi_bootstrap_text,
|
| 84 |
+
L"Python-CFFI error",
|
| 85 |
+
MB_OK | MB_ICONERROR);
|
| 86 |
+
#else
|
| 87 |
+
MessageBoxA(NULL, (char *)_cffi_bootstrap_text,
|
| 88 |
+
"Python-CFFI error",
|
| 89 |
+
MB_OK | MB_ICONERROR);
|
| 90 |
+
#endif
|
| 91 |
+
_cffi_bootstrap_text = NULL;
|
| 92 |
+
return 0;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
static void _cffi_stop_error_capture(PyObject *ecap)
|
| 96 |
+
{
|
| 97 |
+
PyObject *s;
|
| 98 |
+
void *text;
|
| 99 |
+
|
| 100 |
+
if (ecap == (PyObject *)1)
|
| 101 |
+
return;
|
| 102 |
+
|
| 103 |
+
if (ecap == NULL)
|
| 104 |
+
goto error;
|
| 105 |
+
|
| 106 |
+
s = PyRun_String("done()", Py_eval_input, ecap, ecap);
|
| 107 |
+
if (s == NULL)
|
| 108 |
+
goto error;
|
| 109 |
+
|
| 110 |
+
/* Show a dialog box, but in a background thread, and
|
| 111 |
+
never show multiple dialog boxes at once. */
|
| 112 |
+
#if PY_MAJOR_VERSION >= 3
|
| 113 |
+
text = PyUnicode_AsWideCharString(s, NULL);
|
| 114 |
+
#else
|
| 115 |
+
text = PyString_AsString(s);
|
| 116 |
+
#endif
|
| 117 |
+
|
| 118 |
+
_cffi_bootstrap_text = text;
|
| 119 |
+
|
| 120 |
+
if (text != NULL)
|
| 121 |
+
{
|
| 122 |
+
HANDLE h;
|
| 123 |
+
h = CreateThread(NULL, 0, _cffi_bootstrap_dialog,
|
| 124 |
+
NULL, 0, NULL);
|
| 125 |
+
if (h != NULL)
|
| 126 |
+
CloseHandle(h);
|
| 127 |
+
}
|
| 128 |
+
/* decref the string, but it should stay alive as 'fl.buf'
|
| 129 |
+
in the small module above. It will really be freed only if
|
| 130 |
+
we later get another similar error. So it's a leak of at
|
| 131 |
+
most one copy of the small module. That's fine for this
|
| 132 |
+
situation which is usually a "fatal error" anyway. */
|
| 133 |
+
Py_DECREF(s);
|
| 134 |
+
PyErr_Clear();
|
| 135 |
+
return;
|
| 136 |
+
|
| 137 |
+
error:
|
| 138 |
+
_cffi_bootstrap_text = NULL;
|
| 139 |
+
PyErr_Clear();
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
#else
|
| 143 |
+
|
| 144 |
+
static PyObject *_cffi_start_error_capture(void) { return NULL; }
|
| 145 |
+
static void _cffi_stop_error_capture(PyObject *ecap) { }
|
| 146 |
+
|
| 147 |
+
#endif
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/_cffi_include.h
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#define _CFFI_
|
| 2 |
+
|
| 3 |
+
/* We try to define Py_LIMITED_API before including Python.h.
|
| 4 |
+
|
| 5 |
+
Mess: we can only define it if Py_DEBUG, Py_TRACE_REFS and
|
| 6 |
+
Py_REF_DEBUG are not defined. This is a best-effort approximation:
|
| 7 |
+
we can learn about Py_DEBUG from pyconfig.h, but it is unclear if
|
| 8 |
+
the same works for the other two macros. Py_DEBUG implies them,
|
| 9 |
+
but not the other way around.
|
| 10 |
+
|
| 11 |
+
Issue #350 is still open: on Windows, the code here causes it to link
|
| 12 |
+
with PYTHON36.DLL (for example) instead of PYTHON3.DLL. A fix was
|
| 13 |
+
attempted in 164e526a5515 and 14ce6985e1c3, but reverted: virtualenv
|
| 14 |
+
does not make PYTHON3.DLL available, and so the "correctly" compiled
|
| 15 |
+
version would not run inside a virtualenv. We will re-apply the fix
|
| 16 |
+
after virtualenv has been fixed for some time. For explanation, see
|
| 17 |
+
issue #355. For a workaround if you want PYTHON3.DLL and don't worry
|
| 18 |
+
about virtualenv, see issue #350. See also 'py_limited_api' in
|
| 19 |
+
setuptools_ext.py.
|
| 20 |
+
*/
|
| 21 |
+
#if !defined(_CFFI_USE_EMBEDDING) && !defined(Py_LIMITED_API)
|
| 22 |
+
# include <pyconfig.h>
|
| 23 |
+
# if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS) && !defined(Py_REF_DEBUG)
|
| 24 |
+
# define Py_LIMITED_API
|
| 25 |
+
# endif
|
| 26 |
+
#endif
|
| 27 |
+
|
| 28 |
+
#include <Python.h>
|
| 29 |
+
#ifdef __cplusplus
|
| 30 |
+
extern "C" {
|
| 31 |
+
#endif
|
| 32 |
+
#include <stddef.h>
|
| 33 |
+
#include "parse_c_type.h"
|
| 34 |
+
|
| 35 |
+
/* this block of #ifs should be kept exactly identical between
|
| 36 |
+
c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py
|
| 37 |
+
and cffi/_cffi_include.h */
|
| 38 |
+
#if defined(_MSC_VER)
|
| 39 |
+
# include <malloc.h> /* for alloca() */
|
| 40 |
+
# if _MSC_VER < 1600 /* MSVC < 2010 */
|
| 41 |
+
typedef __int8 int8_t;
|
| 42 |
+
typedef __int16 int16_t;
|
| 43 |
+
typedef __int32 int32_t;
|
| 44 |
+
typedef __int64 int64_t;
|
| 45 |
+
typedef unsigned __int8 uint8_t;
|
| 46 |
+
typedef unsigned __int16 uint16_t;
|
| 47 |
+
typedef unsigned __int32 uint32_t;
|
| 48 |
+
typedef unsigned __int64 uint64_t;
|
| 49 |
+
typedef __int8 int_least8_t;
|
| 50 |
+
typedef __int16 int_least16_t;
|
| 51 |
+
typedef __int32 int_least32_t;
|
| 52 |
+
typedef __int64 int_least64_t;
|
| 53 |
+
typedef unsigned __int8 uint_least8_t;
|
| 54 |
+
typedef unsigned __int16 uint_least16_t;
|
| 55 |
+
typedef unsigned __int32 uint_least32_t;
|
| 56 |
+
typedef unsigned __int64 uint_least64_t;
|
| 57 |
+
typedef __int8 int_fast8_t;
|
| 58 |
+
typedef __int16 int_fast16_t;
|
| 59 |
+
typedef __int32 int_fast32_t;
|
| 60 |
+
typedef __int64 int_fast64_t;
|
| 61 |
+
typedef unsigned __int8 uint_fast8_t;
|
| 62 |
+
typedef unsigned __int16 uint_fast16_t;
|
| 63 |
+
typedef unsigned __int32 uint_fast32_t;
|
| 64 |
+
typedef unsigned __int64 uint_fast64_t;
|
| 65 |
+
typedef __int64 intmax_t;
|
| 66 |
+
typedef unsigned __int64 uintmax_t;
|
| 67 |
+
# else
|
| 68 |
+
# include <stdint.h>
|
| 69 |
+
# endif
|
| 70 |
+
# if _MSC_VER < 1800 /* MSVC < 2013 */
|
| 71 |
+
# ifndef __cplusplus
|
| 72 |
+
typedef unsigned char _Bool;
|
| 73 |
+
# endif
|
| 74 |
+
# endif
|
| 75 |
+
#else
|
| 76 |
+
# include <stdint.h>
|
| 77 |
+
# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
|
| 78 |
+
# include <alloca.h>
|
| 79 |
+
# endif
|
| 80 |
+
#endif
|
| 81 |
+
|
| 82 |
+
#ifdef __GNUC__
|
| 83 |
+
# define _CFFI_UNUSED_FN __attribute__((unused))
|
| 84 |
+
#else
|
| 85 |
+
# define _CFFI_UNUSED_FN /* nothing */
|
| 86 |
+
#endif
|
| 87 |
+
|
| 88 |
+
#ifdef __cplusplus
|
| 89 |
+
# ifndef _Bool
|
| 90 |
+
typedef bool _Bool; /* semi-hackish: C++ has no _Bool; bool is builtin */
|
| 91 |
+
# endif
|
| 92 |
+
#endif
|
| 93 |
+
|
| 94 |
+
/********** CPython-specific section **********/
|
| 95 |
+
#ifndef PYPY_VERSION
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
#if PY_MAJOR_VERSION >= 3
|
| 99 |
+
# define PyInt_FromLong PyLong_FromLong
|
| 100 |
+
#endif
|
| 101 |
+
|
| 102 |
+
#define _cffi_from_c_double PyFloat_FromDouble
|
| 103 |
+
#define _cffi_from_c_float PyFloat_FromDouble
|
| 104 |
+
#define _cffi_from_c_long PyInt_FromLong
|
| 105 |
+
#define _cffi_from_c_ulong PyLong_FromUnsignedLong
|
| 106 |
+
#define _cffi_from_c_longlong PyLong_FromLongLong
|
| 107 |
+
#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong
|
| 108 |
+
#define _cffi_from_c__Bool PyBool_FromLong
|
| 109 |
+
|
| 110 |
+
#define _cffi_to_c_double PyFloat_AsDouble
|
| 111 |
+
#define _cffi_to_c_float PyFloat_AsDouble
|
| 112 |
+
|
| 113 |
+
#define _cffi_from_c_int(x, type) \
|
| 114 |
+
(((type)-1) > 0 ? /* unsigned */ \
|
| 115 |
+
(sizeof(type) < sizeof(long) ? \
|
| 116 |
+
PyInt_FromLong((long)x) : \
|
| 117 |
+
sizeof(type) == sizeof(long) ? \
|
| 118 |
+
PyLong_FromUnsignedLong((unsigned long)x) : \
|
| 119 |
+
PyLong_FromUnsignedLongLong((unsigned long long)x)) : \
|
| 120 |
+
(sizeof(type) <= sizeof(long) ? \
|
| 121 |
+
PyInt_FromLong((long)x) : \
|
| 122 |
+
PyLong_FromLongLong((long long)x)))
|
| 123 |
+
|
| 124 |
+
#define _cffi_to_c_int(o, type) \
|
| 125 |
+
((type)( \
|
| 126 |
+
sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \
|
| 127 |
+
: (type)_cffi_to_c_i8(o)) : \
|
| 128 |
+
sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \
|
| 129 |
+
: (type)_cffi_to_c_i16(o)) : \
|
| 130 |
+
sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \
|
| 131 |
+
: (type)_cffi_to_c_i32(o)) : \
|
| 132 |
+
sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \
|
| 133 |
+
: (type)_cffi_to_c_i64(o)) : \
|
| 134 |
+
(Py_FatalError("unsupported size for type " #type), (type)0)))
|
| 135 |
+
|
| 136 |
+
#define _cffi_to_c_i8 \
|
| 137 |
+
((int(*)(PyObject *))_cffi_exports[1])
|
| 138 |
+
#define _cffi_to_c_u8 \
|
| 139 |
+
((int(*)(PyObject *))_cffi_exports[2])
|
| 140 |
+
#define _cffi_to_c_i16 \
|
| 141 |
+
((int(*)(PyObject *))_cffi_exports[3])
|
| 142 |
+
#define _cffi_to_c_u16 \
|
| 143 |
+
((int(*)(PyObject *))_cffi_exports[4])
|
| 144 |
+
#define _cffi_to_c_i32 \
|
| 145 |
+
((int(*)(PyObject *))_cffi_exports[5])
|
| 146 |
+
#define _cffi_to_c_u32 \
|
| 147 |
+
((unsigned int(*)(PyObject *))_cffi_exports[6])
|
| 148 |
+
#define _cffi_to_c_i64 \
|
| 149 |
+
((long long(*)(PyObject *))_cffi_exports[7])
|
| 150 |
+
#define _cffi_to_c_u64 \
|
| 151 |
+
((unsigned long long(*)(PyObject *))_cffi_exports[8])
|
| 152 |
+
#define _cffi_to_c_char \
|
| 153 |
+
((int(*)(PyObject *))_cffi_exports[9])
|
| 154 |
+
#define _cffi_from_c_pointer \
|
| 155 |
+
((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[10])
|
| 156 |
+
#define _cffi_to_c_pointer \
|
| 157 |
+
((char *(*)(PyObject *, struct _cffi_ctypedescr *))_cffi_exports[11])
|
| 158 |
+
#define _cffi_get_struct_layout \
|
| 159 |
+
not used any more
|
| 160 |
+
#define _cffi_restore_errno \
|
| 161 |
+
((void(*)(void))_cffi_exports[13])
|
| 162 |
+
#define _cffi_save_errno \
|
| 163 |
+
((void(*)(void))_cffi_exports[14])
|
| 164 |
+
#define _cffi_from_c_char \
|
| 165 |
+
((PyObject *(*)(char))_cffi_exports[15])
|
| 166 |
+
#define _cffi_from_c_deref \
|
| 167 |
+
((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[16])
|
| 168 |
+
#define _cffi_to_c \
|
| 169 |
+
((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[17])
|
| 170 |
+
#define _cffi_from_c_struct \
|
| 171 |
+
((PyObject *(*)(char *, struct _cffi_ctypedescr *))_cffi_exports[18])
|
| 172 |
+
#define _cffi_to_c_wchar_t \
|
| 173 |
+
((_cffi_wchar_t(*)(PyObject *))_cffi_exports[19])
|
| 174 |
+
#define _cffi_from_c_wchar_t \
|
| 175 |
+
((PyObject *(*)(_cffi_wchar_t))_cffi_exports[20])
|
| 176 |
+
#define _cffi_to_c_long_double \
|
| 177 |
+
((long double(*)(PyObject *))_cffi_exports[21])
|
| 178 |
+
#define _cffi_to_c__Bool \
|
| 179 |
+
((_Bool(*)(PyObject *))_cffi_exports[22])
|
| 180 |
+
#define _cffi_prepare_pointer_call_argument \
|
| 181 |
+
((Py_ssize_t(*)(struct _cffi_ctypedescr *, \
|
| 182 |
+
PyObject *, char **))_cffi_exports[23])
|
| 183 |
+
#define _cffi_convert_array_from_object \
|
| 184 |
+
((int(*)(char *, struct _cffi_ctypedescr *, PyObject *))_cffi_exports[24])
|
| 185 |
+
#define _CFFI_CPIDX 25
|
| 186 |
+
#define _cffi_call_python \
|
| 187 |
+
((void(*)(struct _cffi_externpy_s *, char *))_cffi_exports[_CFFI_CPIDX])
|
| 188 |
+
#define _cffi_to_c_wchar3216_t \
|
| 189 |
+
((int(*)(PyObject *))_cffi_exports[26])
|
| 190 |
+
#define _cffi_from_c_wchar3216_t \
|
| 191 |
+
((PyObject *(*)(int))_cffi_exports[27])
|
| 192 |
+
#define _CFFI_NUM_EXPORTS 28
|
| 193 |
+
|
| 194 |
+
struct _cffi_ctypedescr;
|
| 195 |
+
|
| 196 |
+
static void *_cffi_exports[_CFFI_NUM_EXPORTS];
|
| 197 |
+
|
| 198 |
+
#define _cffi_type(index) ( \
|
| 199 |
+
assert((((uintptr_t)_cffi_types[index]) & 1) == 0), \
|
| 200 |
+
(struct _cffi_ctypedescr *)_cffi_types[index])
|
| 201 |
+
|
| 202 |
+
static PyObject *_cffi_init(const char *module_name, Py_ssize_t version,
|
| 203 |
+
const struct _cffi_type_context_s *ctx)
|
| 204 |
+
{
|
| 205 |
+
PyObject *module, *o_arg, *new_module;
|
| 206 |
+
void *raw[] = {
|
| 207 |
+
(void *)module_name,
|
| 208 |
+
(void *)version,
|
| 209 |
+
(void *)_cffi_exports,
|
| 210 |
+
(void *)ctx,
|
| 211 |
+
};
|
| 212 |
+
|
| 213 |
+
module = PyImport_ImportModule("_cffi_backend");
|
| 214 |
+
if (module == NULL)
|
| 215 |
+
goto failure;
|
| 216 |
+
|
| 217 |
+
o_arg = PyLong_FromVoidPtr((void *)raw);
|
| 218 |
+
if (o_arg == NULL)
|
| 219 |
+
goto failure;
|
| 220 |
+
|
| 221 |
+
new_module = PyObject_CallMethod(
|
| 222 |
+
module, (char *)"_init_cffi_1_0_external_module", (char *)"O", o_arg);
|
| 223 |
+
|
| 224 |
+
Py_DECREF(o_arg);
|
| 225 |
+
Py_DECREF(module);
|
| 226 |
+
return new_module;
|
| 227 |
+
|
| 228 |
+
failure:
|
| 229 |
+
Py_XDECREF(module);
|
| 230 |
+
return NULL;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
#ifdef HAVE_WCHAR_H
|
| 235 |
+
typedef wchar_t _cffi_wchar_t;
|
| 236 |
+
#else
|
| 237 |
+
typedef uint16_t _cffi_wchar_t; /* same random pick as _cffi_backend.c */
|
| 238 |
+
#endif
|
| 239 |
+
|
| 240 |
+
_CFFI_UNUSED_FN static uint16_t _cffi_to_c_char16_t(PyObject *o)
|
| 241 |
+
{
|
| 242 |
+
if (sizeof(_cffi_wchar_t) == 2)
|
| 243 |
+
return (uint16_t)_cffi_to_c_wchar_t(o);
|
| 244 |
+
else
|
| 245 |
+
return (uint16_t)_cffi_to_c_wchar3216_t(o);
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char16_t(uint16_t x)
|
| 249 |
+
{
|
| 250 |
+
if (sizeof(_cffi_wchar_t) == 2)
|
| 251 |
+
return _cffi_from_c_wchar_t((_cffi_wchar_t)x);
|
| 252 |
+
else
|
| 253 |
+
return _cffi_from_c_wchar3216_t((int)x);
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
_CFFI_UNUSED_FN static int _cffi_to_c_char32_t(PyObject *o)
|
| 257 |
+
{
|
| 258 |
+
if (sizeof(_cffi_wchar_t) == 4)
|
| 259 |
+
return (int)_cffi_to_c_wchar_t(o);
|
| 260 |
+
else
|
| 261 |
+
return (int)_cffi_to_c_wchar3216_t(o);
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
_CFFI_UNUSED_FN static PyObject *_cffi_from_c_char32_t(int x)
|
| 265 |
+
{
|
| 266 |
+
if (sizeof(_cffi_wchar_t) == 4)
|
| 267 |
+
return _cffi_from_c_wchar_t((_cffi_wchar_t)x);
|
| 268 |
+
else
|
| 269 |
+
return _cffi_from_c_wchar3216_t(x);
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
/********** end CPython-specific section **********/
|
| 274 |
+
#else
|
| 275 |
+
_CFFI_UNUSED_FN
|
| 276 |
+
static void (*_cffi_call_python_org)(struct _cffi_externpy_s *, char *);
|
| 277 |
+
# define _cffi_call_python _cffi_call_python_org
|
| 278 |
+
#endif
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
#define _cffi_array_len(array) (sizeof(array) / sizeof((array)[0]))
|
| 282 |
+
|
| 283 |
+
#define _cffi_prim_int(size, sign) \
|
| 284 |
+
((size) == 1 ? ((sign) ? _CFFI_PRIM_INT8 : _CFFI_PRIM_UINT8) : \
|
| 285 |
+
(size) == 2 ? ((sign) ? _CFFI_PRIM_INT16 : _CFFI_PRIM_UINT16) : \
|
| 286 |
+
(size) == 4 ? ((sign) ? _CFFI_PRIM_INT32 : _CFFI_PRIM_UINT32) : \
|
| 287 |
+
(size) == 8 ? ((sign) ? _CFFI_PRIM_INT64 : _CFFI_PRIM_UINT64) : \
|
| 288 |
+
_CFFI__UNKNOWN_PRIM)
|
| 289 |
+
|
| 290 |
+
#define _cffi_prim_float(size) \
|
| 291 |
+
((size) == sizeof(float) ? _CFFI_PRIM_FLOAT : \
|
| 292 |
+
(size) == sizeof(double) ? _CFFI_PRIM_DOUBLE : \
|
| 293 |
+
(size) == sizeof(long double) ? _CFFI__UNKNOWN_LONG_DOUBLE : \
|
| 294 |
+
_CFFI__UNKNOWN_FLOAT_PRIM)
|
| 295 |
+
|
| 296 |
+
#define _cffi_check_int(got, got_nonpos, expected) \
|
| 297 |
+
((got_nonpos) == (expected <= 0) && \
|
| 298 |
+
(got) == (unsigned long long)expected)
|
| 299 |
+
|
| 300 |
+
#ifdef MS_WIN32
|
| 301 |
+
# define _cffi_stdcall __stdcall
|
| 302 |
+
#else
|
| 303 |
+
# define _cffi_stdcall /* nothing */
|
| 304 |
+
#endif
|
| 305 |
+
|
| 306 |
+
#ifdef __cplusplus
|
| 307 |
+
}
|
| 308 |
+
#endif
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/_embedding.h
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
/***** Support code for embedding *****/
|
| 3 |
+
|
| 4 |
+
#ifdef __cplusplus
|
| 5 |
+
extern "C" {
|
| 6 |
+
#endif
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
#if defined(_WIN32)
|
| 10 |
+
# define CFFI_DLLEXPORT __declspec(dllexport)
|
| 11 |
+
#elif defined(__GNUC__)
|
| 12 |
+
# define CFFI_DLLEXPORT __attribute__((visibility("default")))
|
| 13 |
+
#else
|
| 14 |
+
# define CFFI_DLLEXPORT /* nothing */
|
| 15 |
+
#endif
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
/* There are two global variables of type _cffi_call_python_fnptr:
|
| 19 |
+
|
| 20 |
+
* _cffi_call_python, which we declare just below, is the one called
|
| 21 |
+
by ``extern "Python"`` implementations.
|
| 22 |
+
|
| 23 |
+
* _cffi_call_python_org, which on CPython is actually part of the
|
| 24 |
+
_cffi_exports[] array, is the function pointer copied from
|
| 25 |
+
_cffi_backend.
|
| 26 |
+
|
| 27 |
+
After initialization is complete, both are equal. However, the
|
| 28 |
+
first one remains equal to &_cffi_start_and_call_python until the
|
| 29 |
+
very end of initialization, when we are (or should be) sure that
|
| 30 |
+
concurrent threads also see a completely initialized world, and
|
| 31 |
+
only then is it changed.
|
| 32 |
+
*/
|
| 33 |
+
#undef _cffi_call_python
|
| 34 |
+
typedef void (*_cffi_call_python_fnptr)(struct _cffi_externpy_s *, char *);
|
| 35 |
+
static void _cffi_start_and_call_python(struct _cffi_externpy_s *, char *);
|
| 36 |
+
static _cffi_call_python_fnptr _cffi_call_python = &_cffi_start_and_call_python;
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
#ifndef _MSC_VER
|
| 40 |
+
/* --- Assuming a GCC not infinitely old --- */
|
| 41 |
+
# define cffi_compare_and_swap(l,o,n) __sync_bool_compare_and_swap(l,o,n)
|
| 42 |
+
# define cffi_write_barrier() __sync_synchronize()
|
| 43 |
+
# if !defined(__amd64__) && !defined(__x86_64__) && \
|
| 44 |
+
!defined(__i386__) && !defined(__i386)
|
| 45 |
+
# define cffi_read_barrier() __sync_synchronize()
|
| 46 |
+
# else
|
| 47 |
+
# define cffi_read_barrier() (void)0
|
| 48 |
+
# endif
|
| 49 |
+
#else
|
| 50 |
+
/* --- Windows threads version --- */
|
| 51 |
+
# include <Windows.h>
|
| 52 |
+
# define cffi_compare_and_swap(l,o,n) \
|
| 53 |
+
(InterlockedCompareExchangePointer(l,n,o) == (o))
|
| 54 |
+
# define cffi_write_barrier() InterlockedCompareExchange(&_cffi_dummy,0,0)
|
| 55 |
+
# define cffi_read_barrier() (void)0
|
| 56 |
+
static volatile LONG _cffi_dummy;
|
| 57 |
+
#endif
|
| 58 |
+
|
| 59 |
+
#ifdef WITH_THREAD
|
| 60 |
+
# ifndef _MSC_VER
|
| 61 |
+
# include <pthread.h>
|
| 62 |
+
static pthread_mutex_t _cffi_embed_startup_lock;
|
| 63 |
+
# else
|
| 64 |
+
static CRITICAL_SECTION _cffi_embed_startup_lock;
|
| 65 |
+
# endif
|
| 66 |
+
static char _cffi_embed_startup_lock_ready = 0;
|
| 67 |
+
#endif
|
| 68 |
+
|
| 69 |
+
static void _cffi_acquire_reentrant_mutex(void)
|
| 70 |
+
{
|
| 71 |
+
static void *volatile lock = NULL;
|
| 72 |
+
|
| 73 |
+
while (!cffi_compare_and_swap(&lock, NULL, (void *)1)) {
|
| 74 |
+
/* should ideally do a spin loop instruction here, but
|
| 75 |
+
hard to do it portably and doesn't really matter I
|
| 76 |
+
think: pthread_mutex_init() should be very fast, and
|
| 77 |
+
this is only run at start-up anyway. */
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
#ifdef WITH_THREAD
|
| 81 |
+
if (!_cffi_embed_startup_lock_ready) {
|
| 82 |
+
# ifndef _MSC_VER
|
| 83 |
+
pthread_mutexattr_t attr;
|
| 84 |
+
pthread_mutexattr_init(&attr);
|
| 85 |
+
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
|
| 86 |
+
pthread_mutex_init(&_cffi_embed_startup_lock, &attr);
|
| 87 |
+
# else
|
| 88 |
+
InitializeCriticalSection(&_cffi_embed_startup_lock);
|
| 89 |
+
# endif
|
| 90 |
+
_cffi_embed_startup_lock_ready = 1;
|
| 91 |
+
}
|
| 92 |
+
#endif
|
| 93 |
+
|
| 94 |
+
while (!cffi_compare_and_swap(&lock, (void *)1, NULL))
|
| 95 |
+
;
|
| 96 |
+
|
| 97 |
+
#ifndef _MSC_VER
|
| 98 |
+
pthread_mutex_lock(&_cffi_embed_startup_lock);
|
| 99 |
+
#else
|
| 100 |
+
EnterCriticalSection(&_cffi_embed_startup_lock);
|
| 101 |
+
#endif
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
static void _cffi_release_reentrant_mutex(void)
|
| 105 |
+
{
|
| 106 |
+
#ifndef _MSC_VER
|
| 107 |
+
pthread_mutex_unlock(&_cffi_embed_startup_lock);
|
| 108 |
+
#else
|
| 109 |
+
LeaveCriticalSection(&_cffi_embed_startup_lock);
|
| 110 |
+
#endif
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
/********** CPython-specific section **********/
|
| 115 |
+
#ifndef PYPY_VERSION
|
| 116 |
+
|
| 117 |
+
#include "_cffi_errors.h"
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
#define _cffi_call_python_org _cffi_exports[_CFFI_CPIDX]
|
| 121 |
+
|
| 122 |
+
PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(void); /* forward */
|
| 123 |
+
|
| 124 |
+
static void _cffi_py_initialize(void)
|
| 125 |
+
{
|
| 126 |
+
/* XXX use initsigs=0, which "skips initialization registration of
|
| 127 |
+
signal handlers, which might be useful when Python is
|
| 128 |
+
embedded" according to the Python docs. But review and think
|
| 129 |
+
if it should be a user-controllable setting.
|
| 130 |
+
|
| 131 |
+
XXX we should also give a way to write errors to a buffer
|
| 132 |
+
instead of to stderr.
|
| 133 |
+
|
| 134 |
+
XXX if importing 'site' fails, CPython (any version) calls
|
| 135 |
+
exit(). Should we try to work around this behavior here?
|
| 136 |
+
*/
|
| 137 |
+
Py_InitializeEx(0);
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
static int _cffi_initialize_python(void)
|
| 141 |
+
{
|
| 142 |
+
/* This initializes Python, imports _cffi_backend, and then the
|
| 143 |
+
present .dll/.so is set up as a CPython C extension module.
|
| 144 |
+
*/
|
| 145 |
+
int result;
|
| 146 |
+
PyGILState_STATE state;
|
| 147 |
+
PyObject *pycode=NULL, *global_dict=NULL, *x;
|
| 148 |
+
PyObject *builtins;
|
| 149 |
+
|
| 150 |
+
state = PyGILState_Ensure();
|
| 151 |
+
|
| 152 |
+
/* Call the initxxx() function from the present module. It will
|
| 153 |
+
create and initialize us as a CPython extension module, instead
|
| 154 |
+
of letting the startup Python code do it---it might reimport
|
| 155 |
+
the same .dll/.so and get maybe confused on some platforms.
|
| 156 |
+
It might also have troubles locating the .dll/.so again for all
|
| 157 |
+
I know.
|
| 158 |
+
*/
|
| 159 |
+
(void)_CFFI_PYTHON_STARTUP_FUNC();
|
| 160 |
+
if (PyErr_Occurred())
|
| 161 |
+
goto error;
|
| 162 |
+
|
| 163 |
+
/* Now run the Python code provided to ffi.embedding_init_code().
|
| 164 |
+
*/
|
| 165 |
+
pycode = Py_CompileString(_CFFI_PYTHON_STARTUP_CODE,
|
| 166 |
+
"<init code for '" _CFFI_MODULE_NAME "'>",
|
| 167 |
+
Py_file_input);
|
| 168 |
+
if (pycode == NULL)
|
| 169 |
+
goto error;
|
| 170 |
+
global_dict = PyDict_New();
|
| 171 |
+
if (global_dict == NULL)
|
| 172 |
+
goto error;
|
| 173 |
+
builtins = PyEval_GetBuiltins();
|
| 174 |
+
if (builtins == NULL)
|
| 175 |
+
goto error;
|
| 176 |
+
if (PyDict_SetItemString(global_dict, "__builtins__", builtins) < 0)
|
| 177 |
+
goto error;
|
| 178 |
+
x = PyEval_EvalCode(
|
| 179 |
+
#if PY_MAJOR_VERSION < 3
|
| 180 |
+
(PyCodeObject *)
|
| 181 |
+
#endif
|
| 182 |
+
pycode, global_dict, global_dict);
|
| 183 |
+
if (x == NULL)
|
| 184 |
+
goto error;
|
| 185 |
+
Py_DECREF(x);
|
| 186 |
+
|
| 187 |
+
/* Done! Now if we've been called from
|
| 188 |
+
_cffi_start_and_call_python() in an ``extern "Python"``, we can
|
| 189 |
+
only hope that the Python code did correctly set up the
|
| 190 |
+
corresponding @ffi.def_extern() function. Otherwise, the
|
| 191 |
+
general logic of ``extern "Python"`` functions (inside the
|
| 192 |
+
_cffi_backend module) will find that the reference is still
|
| 193 |
+
missing and print an error.
|
| 194 |
+
*/
|
| 195 |
+
result = 0;
|
| 196 |
+
done:
|
| 197 |
+
Py_XDECREF(pycode);
|
| 198 |
+
Py_XDECREF(global_dict);
|
| 199 |
+
PyGILState_Release(state);
|
| 200 |
+
return result;
|
| 201 |
+
|
| 202 |
+
error:;
|
| 203 |
+
{
|
| 204 |
+
/* Print as much information as potentially useful.
|
| 205 |
+
Debugging load-time failures with embedding is not fun
|
| 206 |
+
*/
|
| 207 |
+
PyObject *ecap;
|
| 208 |
+
PyObject *exception, *v, *tb, *f, *modules, *mod;
|
| 209 |
+
PyErr_Fetch(&exception, &v, &tb);
|
| 210 |
+
ecap = _cffi_start_error_capture();
|
| 211 |
+
f = PySys_GetObject((char *)"stderr");
|
| 212 |
+
if (f != NULL && f != Py_None) {
|
| 213 |
+
PyFile_WriteString(
|
| 214 |
+
"Failed to initialize the Python-CFFI embedding logic:\n\n", f);
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
if (exception != NULL) {
|
| 218 |
+
PyErr_NormalizeException(&exception, &v, &tb);
|
| 219 |
+
PyErr_Display(exception, v, tb);
|
| 220 |
+
}
|
| 221 |
+
Py_XDECREF(exception);
|
| 222 |
+
Py_XDECREF(v);
|
| 223 |
+
Py_XDECREF(tb);
|
| 224 |
+
|
| 225 |
+
if (f != NULL && f != Py_None) {
|
| 226 |
+
PyFile_WriteString("\nFrom: " _CFFI_MODULE_NAME
|
| 227 |
+
"\ncompiled with cffi version: 1.12.3"
|
| 228 |
+
"\n_cffi_backend module: ", f);
|
| 229 |
+
modules = PyImport_GetModuleDict();
|
| 230 |
+
mod = PyDict_GetItemString(modules, "_cffi_backend");
|
| 231 |
+
if (mod == NULL) {
|
| 232 |
+
PyFile_WriteString("not loaded", f);
|
| 233 |
+
}
|
| 234 |
+
else {
|
| 235 |
+
v = PyObject_GetAttrString(mod, "__file__");
|
| 236 |
+
PyFile_WriteObject(v, f, 0);
|
| 237 |
+
Py_XDECREF(v);
|
| 238 |
+
}
|
| 239 |
+
PyFile_WriteString("\nsys.path: ", f);
|
| 240 |
+
PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0);
|
| 241 |
+
PyFile_WriteString("\n\n", f);
|
| 242 |
+
}
|
| 243 |
+
_cffi_stop_error_capture(ecap);
|
| 244 |
+
}
|
| 245 |
+
result = -1;
|
| 246 |
+
goto done;
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
PyAPI_DATA(char *) _PyParser_TokenNames[]; /* from CPython */
|
| 250 |
+
|
| 251 |
+
static int _cffi_carefully_make_gil(void)
|
| 252 |
+
{
|
| 253 |
+
/* This does the basic initialization of Python. It can be called
|
| 254 |
+
completely concurrently from unrelated threads. It assumes
|
| 255 |
+
that we don't hold the GIL before (if it exists), and we don't
|
| 256 |
+
hold it afterwards.
|
| 257 |
+
|
| 258 |
+
(What it really does used to be completely different in Python 2
|
| 259 |
+
and Python 3, with the Python 2 solution avoiding the spin-lock
|
| 260 |
+
around the Py_InitializeEx() call. However, after recent changes
|
| 261 |
+
to CPython 2.7 (issue #358) it no longer works. So we use the
|
| 262 |
+
Python 3 solution everywhere.)
|
| 263 |
+
|
| 264 |
+
This initializes Python by calling Py_InitializeEx().
|
| 265 |
+
Important: this must not be called concurrently at all.
|
| 266 |
+
So we use a global variable as a simple spin lock. This global
|
| 267 |
+
variable must be from 'libpythonX.Y.so', not from this
|
| 268 |
+
cffi-based extension module, because it must be shared from
|
| 269 |
+
different cffi-based extension modules.
|
| 270 |
+
|
| 271 |
+
In Python < 3.8, we choose
|
| 272 |
+
_PyParser_TokenNames[0] as a completely arbitrary pointer value
|
| 273 |
+
that is never written to. The default is to point to the
|
| 274 |
+
string "ENDMARKER". We change it temporarily to point to the
|
| 275 |
+
next character in that string. (Yes, I know it's REALLY
|
| 276 |
+
obscure.)
|
| 277 |
+
|
| 278 |
+
In Python >= 3.8, this string array is no longer writable, so
|
| 279 |
+
instead we pick PyCapsuleType.tp_version_tag. We can't change
|
| 280 |
+
Python < 3.8 because someone might use a mixture of cffi
|
| 281 |
+
embedded modules, some of which were compiled before this file
|
| 282 |
+
changed.
|
| 283 |
+
*/
|
| 284 |
+
|
| 285 |
+
#ifdef WITH_THREAD
|
| 286 |
+
# if PY_VERSION_HEX < 0x03080000
|
| 287 |
+
char *volatile *lock = (char *volatile *)_PyParser_TokenNames;
|
| 288 |
+
char *old_value, *locked_value;
|
| 289 |
+
|
| 290 |
+
while (1) { /* spin loop */
|
| 291 |
+
old_value = *lock;
|
| 292 |
+
locked_value = old_value + 1;
|
| 293 |
+
if (old_value[0] == 'E') {
|
| 294 |
+
assert(old_value[1] == 'N');
|
| 295 |
+
if (cffi_compare_and_swap(lock, old_value, locked_value))
|
| 296 |
+
break;
|
| 297 |
+
}
|
| 298 |
+
else {
|
| 299 |
+
assert(old_value[0] == 'N');
|
| 300 |
+
/* should ideally do a spin loop instruction here, but
|
| 301 |
+
hard to do it portably and doesn't really matter I
|
| 302 |
+
think: PyEval_InitThreads() should be very fast, and
|
| 303 |
+
this is only run at start-up anyway. */
|
| 304 |
+
}
|
| 305 |
+
}
|
| 306 |
+
# else
|
| 307 |
+
int volatile *lock = (int volatile *)&PyCapsule_Type.tp_version_tag;
|
| 308 |
+
int old_value, locked_value;
|
| 309 |
+
assert(!(PyCapsule_Type.tp_flags & Py_TPFLAGS_HAVE_VERSION_TAG));
|
| 310 |
+
|
| 311 |
+
while (1) { /* spin loop */
|
| 312 |
+
old_value = *lock;
|
| 313 |
+
locked_value = -42;
|
| 314 |
+
if (old_value == 0) {
|
| 315 |
+
if (cffi_compare_and_swap(lock, old_value, locked_value))
|
| 316 |
+
break;
|
| 317 |
+
}
|
| 318 |
+
else {
|
| 319 |
+
assert(old_value == locked_value);
|
| 320 |
+
/* should ideally do a spin loop instruction here, but
|
| 321 |
+
hard to do it portably and doesn't really matter I
|
| 322 |
+
think: PyEval_InitThreads() should be very fast, and
|
| 323 |
+
this is only run at start-up anyway. */
|
| 324 |
+
}
|
| 325 |
+
}
|
| 326 |
+
# endif
|
| 327 |
+
#endif
|
| 328 |
+
|
| 329 |
+
/* call Py_InitializeEx() */
|
| 330 |
+
{
|
| 331 |
+
PyGILState_STATE state = PyGILState_UNLOCKED;
|
| 332 |
+
if (!Py_IsInitialized())
|
| 333 |
+
_cffi_py_initialize();
|
| 334 |
+
else
|
| 335 |
+
state = PyGILState_Ensure();
|
| 336 |
+
|
| 337 |
+
PyEval_InitThreads();
|
| 338 |
+
PyGILState_Release(state);
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
#ifdef WITH_THREAD
|
| 342 |
+
/* release the lock */
|
| 343 |
+
while (!cffi_compare_and_swap(lock, locked_value, old_value))
|
| 344 |
+
;
|
| 345 |
+
#endif
|
| 346 |
+
|
| 347 |
+
return 0;
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
/********** end CPython-specific section **********/
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
#else
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
/********** PyPy-specific section **********/
|
| 357 |
+
|
| 358 |
+
PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(const void *[]); /* forward */
|
| 359 |
+
|
| 360 |
+
static struct _cffi_pypy_init_s {
|
| 361 |
+
const char *name;
|
| 362 |
+
void (*func)(const void *[]);
|
| 363 |
+
const char *code;
|
| 364 |
+
} _cffi_pypy_init = {
|
| 365 |
+
_CFFI_MODULE_NAME,
|
| 366 |
+
(void(*)(const void *[]))_CFFI_PYTHON_STARTUP_FUNC,
|
| 367 |
+
_CFFI_PYTHON_STARTUP_CODE,
|
| 368 |
+
};
|
| 369 |
+
|
| 370 |
+
extern int pypy_carefully_make_gil(const char *);
|
| 371 |
+
extern int pypy_init_embedded_cffi_module(int, struct _cffi_pypy_init_s *);
|
| 372 |
+
|
| 373 |
+
static int _cffi_carefully_make_gil(void)
|
| 374 |
+
{
|
| 375 |
+
return pypy_carefully_make_gil(_CFFI_MODULE_NAME);
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
static int _cffi_initialize_python(void)
|
| 379 |
+
{
|
| 380 |
+
return pypy_init_embedded_cffi_module(0xB011, &_cffi_pypy_init);
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
/********** end PyPy-specific section **********/
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
#endif
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
#ifdef __GNUC__
|
| 390 |
+
__attribute__((noinline))
|
| 391 |
+
#endif
|
| 392 |
+
static _cffi_call_python_fnptr _cffi_start_python(void)
|
| 393 |
+
{
|
| 394 |
+
/* Delicate logic to initialize Python. This function can be
|
| 395 |
+
called multiple times concurrently, e.g. when the process calls
|
| 396 |
+
its first ``extern "Python"`` functions in multiple threads at
|
| 397 |
+
once. It can also be called recursively, in which case we must
|
| 398 |
+
ignore it. We also have to consider what occurs if several
|
| 399 |
+
different cffi-based extensions reach this code in parallel
|
| 400 |
+
threads---it is a different copy of the code, then, and we
|
| 401 |
+
can't have any shared global variable unless it comes from
|
| 402 |
+
'libpythonX.Y.so'.
|
| 403 |
+
|
| 404 |
+
Idea:
|
| 405 |
+
|
| 406 |
+
* _cffi_carefully_make_gil(): "carefully" call
|
| 407 |
+
PyEval_InitThreads() (possibly with Py_InitializeEx() first).
|
| 408 |
+
|
| 409 |
+
* then we use a (local) custom lock to make sure that a call to this
|
| 410 |
+
cffi-based extension will wait if another call to the *same*
|
| 411 |
+
extension is running the initialization in another thread.
|
| 412 |
+
It is reentrant, so that a recursive call will not block, but
|
| 413 |
+
only one from a different thread.
|
| 414 |
+
|
| 415 |
+
* then we grab the GIL and (Python 2) we call Py_InitializeEx().
|
| 416 |
+
At this point, concurrent calls to Py_InitializeEx() are not
|
| 417 |
+
possible: we have the GIL.
|
| 418 |
+
|
| 419 |
+
* do the rest of the specific initialization, which may
|
| 420 |
+
temporarily release the GIL but not the custom lock.
|
| 421 |
+
Only release the custom lock when we are done.
|
| 422 |
+
*/
|
| 423 |
+
static char called = 0;
|
| 424 |
+
|
| 425 |
+
if (_cffi_carefully_make_gil() != 0)
|
| 426 |
+
return NULL;
|
| 427 |
+
|
| 428 |
+
_cffi_acquire_reentrant_mutex();
|
| 429 |
+
|
| 430 |
+
/* Here the GIL exists, but we don't have it. We're only protected
|
| 431 |
+
from concurrency by the reentrant mutex. */
|
| 432 |
+
|
| 433 |
+
/* This file only initializes the embedded module once, the first
|
| 434 |
+
time this is called, even if there are subinterpreters. */
|
| 435 |
+
if (!called) {
|
| 436 |
+
called = 1; /* invoke _cffi_initialize_python() only once,
|
| 437 |
+
but don't set '_cffi_call_python' right now,
|
| 438 |
+
otherwise concurrent threads won't call
|
| 439 |
+
this function at all (we need them to wait) */
|
| 440 |
+
if (_cffi_initialize_python() == 0) {
|
| 441 |
+
/* now initialization is finished. Switch to the fast-path. */
|
| 442 |
+
|
| 443 |
+
/* We would like nobody to see the new value of
|
| 444 |
+
'_cffi_call_python' without also seeing the rest of the
|
| 445 |
+
data initialized. However, this is not possible. But
|
| 446 |
+
the new value of '_cffi_call_python' is the function
|
| 447 |
+
'cffi_call_python()' from _cffi_backend. So: */
|
| 448 |
+
cffi_write_barrier();
|
| 449 |
+
/* ^^^ we put a write barrier here, and a corresponding
|
| 450 |
+
read barrier at the start of cffi_call_python(). This
|
| 451 |
+
ensures that after that read barrier, we see everything
|
| 452 |
+
done here before the write barrier.
|
| 453 |
+
*/
|
| 454 |
+
|
| 455 |
+
assert(_cffi_call_python_org != NULL);
|
| 456 |
+
_cffi_call_python = (_cffi_call_python_fnptr)_cffi_call_python_org;
|
| 457 |
+
}
|
| 458 |
+
else {
|
| 459 |
+
/* initialization failed. Reset this to NULL, even if it was
|
| 460 |
+
already set to some other value. Future calls to
|
| 461 |
+
_cffi_start_python() are still forced to occur, and will
|
| 462 |
+
always return NULL from now on. */
|
| 463 |
+
_cffi_call_python_org = NULL;
|
| 464 |
+
}
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
_cffi_release_reentrant_mutex();
|
| 468 |
+
|
| 469 |
+
return (_cffi_call_python_fnptr)_cffi_call_python_org;
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
static
|
| 473 |
+
void _cffi_start_and_call_python(struct _cffi_externpy_s *externpy, char *args)
|
| 474 |
+
{
|
| 475 |
+
_cffi_call_python_fnptr fnptr;
|
| 476 |
+
int current_err = errno;
|
| 477 |
+
#ifdef _MSC_VER
|
| 478 |
+
int current_lasterr = GetLastError();
|
| 479 |
+
#endif
|
| 480 |
+
fnptr = _cffi_start_python();
|
| 481 |
+
if (fnptr == NULL) {
|
| 482 |
+
fprintf(stderr, "function %s() called, but initialization code "
|
| 483 |
+
"failed. Returning 0.\n", externpy->name);
|
| 484 |
+
memset(args, 0, externpy->size_of_result);
|
| 485 |
+
}
|
| 486 |
+
#ifdef _MSC_VER
|
| 487 |
+
SetLastError(current_lasterr);
|
| 488 |
+
#endif
|
| 489 |
+
errno = current_err;
|
| 490 |
+
|
| 491 |
+
if (fnptr != NULL)
|
| 492 |
+
fnptr(externpy, args);
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
/* The cffi_start_python() function makes sure Python is initialized
|
| 497 |
+
and our cffi module is set up. It can be called manually from the
|
| 498 |
+
user C code. The same effect is obtained automatically from any
|
| 499 |
+
dll-exported ``extern "Python"`` function. This function returns
|
| 500 |
+
-1 if initialization failed, 0 if all is OK. */
|
| 501 |
+
_CFFI_UNUSED_FN
|
| 502 |
+
static int cffi_start_python(void)
|
| 503 |
+
{
|
| 504 |
+
if (_cffi_call_python == &_cffi_start_and_call_python) {
|
| 505 |
+
if (_cffi_start_python() == NULL)
|
| 506 |
+
return -1;
|
| 507 |
+
}
|
| 508 |
+
cffi_read_barrier();
|
| 509 |
+
return 0;
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
#undef cffi_compare_and_swap
|
| 513 |
+
#undef cffi_write_barrier
|
| 514 |
+
#undef cffi_read_barrier
|
| 515 |
+
|
| 516 |
+
#ifdef __cplusplus
|
| 517 |
+
}
|
| 518 |
+
#endif
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/commontypes.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from . import model
|
| 3 |
+
from .error import FFIError
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
COMMON_TYPES = {}
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
# fetch "bool" and all simple Windows types
|
| 10 |
+
from _cffi_backend import _get_common_types
|
| 11 |
+
_get_common_types(COMMON_TYPES)
|
| 12 |
+
except ImportError:
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
COMMON_TYPES['FILE'] = model.unknown_type('FILE', '_IO_FILE')
|
| 16 |
+
COMMON_TYPES['bool'] = '_Bool' # in case we got ImportError above
|
| 17 |
+
|
| 18 |
+
for _type in model.PrimitiveType.ALL_PRIMITIVE_TYPES:
|
| 19 |
+
if _type.endswith('_t'):
|
| 20 |
+
COMMON_TYPES[_type] = _type
|
| 21 |
+
del _type
|
| 22 |
+
|
| 23 |
+
_CACHE = {}
|
| 24 |
+
|
| 25 |
+
def resolve_common_type(parser, commontype):
|
| 26 |
+
try:
|
| 27 |
+
return _CACHE[commontype]
|
| 28 |
+
except KeyError:
|
| 29 |
+
cdecl = COMMON_TYPES.get(commontype, commontype)
|
| 30 |
+
if not isinstance(cdecl, str):
|
| 31 |
+
result, quals = cdecl, 0 # cdecl is already a BaseType
|
| 32 |
+
elif cdecl in model.PrimitiveType.ALL_PRIMITIVE_TYPES:
|
| 33 |
+
result, quals = model.PrimitiveType(cdecl), 0
|
| 34 |
+
elif cdecl == 'set-unicode-needed':
|
| 35 |
+
raise FFIError("The Windows type %r is only available after "
|
| 36 |
+
"you call ffi.set_unicode()" % (commontype,))
|
| 37 |
+
else:
|
| 38 |
+
if commontype == cdecl:
|
| 39 |
+
raise FFIError(
|
| 40 |
+
"Unsupported type: %r. Please look at "
|
| 41 |
+
"http://cffi.readthedocs.io/en/latest/cdef.html#ffi-cdef-limitations "
|
| 42 |
+
"and file an issue if you think this type should really "
|
| 43 |
+
"be supported." % (commontype,))
|
| 44 |
+
result, quals = parser.parse_type_and_quals(cdecl) # recursive
|
| 45 |
+
|
| 46 |
+
assert isinstance(result, model.BaseTypeByIdentity)
|
| 47 |
+
_CACHE[commontype] = result, quals
|
| 48 |
+
return result, quals
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# ____________________________________________________________
|
| 52 |
+
# extra types for Windows (most of them are in commontypes.c)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def win_common_types():
|
| 56 |
+
return {
|
| 57 |
+
"UNICODE_STRING": model.StructType(
|
| 58 |
+
"_UNICODE_STRING",
|
| 59 |
+
["Length",
|
| 60 |
+
"MaximumLength",
|
| 61 |
+
"Buffer"],
|
| 62 |
+
[model.PrimitiveType("unsigned short"),
|
| 63 |
+
model.PrimitiveType("unsigned short"),
|
| 64 |
+
model.PointerType(model.PrimitiveType("wchar_t"))],
|
| 65 |
+
[-1, -1, -1]),
|
| 66 |
+
"PUNICODE_STRING": "UNICODE_STRING *",
|
| 67 |
+
"PCUNICODE_STRING": "const UNICODE_STRING *",
|
| 68 |
+
|
| 69 |
+
"TBYTE": "set-unicode-needed",
|
| 70 |
+
"TCHAR": "set-unicode-needed",
|
| 71 |
+
"LPCTSTR": "set-unicode-needed",
|
| 72 |
+
"PCTSTR": "set-unicode-needed",
|
| 73 |
+
"LPTSTR": "set-unicode-needed",
|
| 74 |
+
"PTSTR": "set-unicode-needed",
|
| 75 |
+
"PTBYTE": "set-unicode-needed",
|
| 76 |
+
"PTCHAR": "set-unicode-needed",
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
if sys.platform == 'win32':
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import model
|
| 2 |
+
from .commontypes import COMMON_TYPES, resolve_common_type
|
| 3 |
+
from .error import FFIError, CDefError
|
| 4 |
+
try:
|
| 5 |
+
from . import _pycparser as pycparser
|
| 6 |
+
except ImportError:
|
| 7 |
+
import pycparser
|
| 8 |
+
import weakref, re, sys
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
if sys.version_info < (3,):
|
| 12 |
+
import thread as _thread
|
| 13 |
+
else:
|
| 14 |
+
import _thread
|
| 15 |
+
lock = _thread.allocate_lock()
|
| 16 |
+
except ImportError:
|
| 17 |
+
lock = None
|
| 18 |
+
|
| 19 |
+
def _workaround_for_static_import_finders():
|
| 20 |
+
# Issue #392: packaging tools like cx_Freeze can not find these
|
| 21 |
+
# because pycparser uses exec dynamic import. This is an obscure
|
| 22 |
+
# workaround. This function is never called.
|
| 23 |
+
import pycparser.yacctab
|
| 24 |
+
import pycparser.lextab
|
| 25 |
+
|
| 26 |
+
CDEF_SOURCE_STRING = "<cdef source string>"
|
| 27 |
+
_r_comment = re.compile(r"/\*.*?\*/|//([^\n\\]|\\.)*?$",
|
| 28 |
+
re.DOTALL | re.MULTILINE)
|
| 29 |
+
_r_define = re.compile(r"^\s*#\s*define\s+([A-Za-z_][A-Za-z_0-9]*)"
|
| 30 |
+
r"\b((?:[^\n\\]|\\.)*?)$",
|
| 31 |
+
re.DOTALL | re.MULTILINE)
|
| 32 |
+
_r_partial_enum = re.compile(r"=\s*\.\.\.\s*[,}]|\.\.\.\s*\}")
|
| 33 |
+
_r_enum_dotdotdot = re.compile(r"__dotdotdot\d+__$")
|
| 34 |
+
_r_partial_array = re.compile(r"\[\s*\.\.\.\s*\]")
|
| 35 |
+
_r_words = re.compile(r"\w+|\S")
|
| 36 |
+
_parser_cache = None
|
| 37 |
+
_r_int_literal = re.compile(r"-?0?x?[0-9a-f]+[lu]*$", re.IGNORECASE)
|
| 38 |
+
_r_stdcall1 = re.compile(r"\b(__stdcall|WINAPI)\b")
|
| 39 |
+
_r_stdcall2 = re.compile(r"[(]\s*(__stdcall|WINAPI)\b")
|
| 40 |
+
_r_cdecl = re.compile(r"\b__cdecl\b")
|
| 41 |
+
_r_extern_python = re.compile(r'\bextern\s*"'
|
| 42 |
+
r'(Python|Python\s*\+\s*C|C\s*\+\s*Python)"\s*.')
|
| 43 |
+
_r_star_const_space = re.compile( # matches "* const "
|
| 44 |
+
r"[*]\s*((const|volatile|restrict)\b\s*)+")
|
| 45 |
+
_r_int_dotdotdot = re.compile(r"(\b(int|long|short|signed|unsigned|char)\s*)+"
|
| 46 |
+
r"\.\.\.")
|
| 47 |
+
_r_float_dotdotdot = re.compile(r"\b(double|float)\s*\.\.\.")
|
| 48 |
+
|
| 49 |
+
def _get_parser():
|
| 50 |
+
global _parser_cache
|
| 51 |
+
if _parser_cache is None:
|
| 52 |
+
_parser_cache = pycparser.CParser()
|
| 53 |
+
return _parser_cache
|
| 54 |
+
|
| 55 |
+
def _workaround_for_old_pycparser(csource):
|
| 56 |
+
# Workaround for a pycparser issue (fixed between pycparser 2.10 and
|
| 57 |
+
# 2.14): "char*const***" gives us a wrong syntax tree, the same as
|
| 58 |
+
# for "char***(*const)". This means we can't tell the difference
|
| 59 |
+
# afterwards. But "char(*const(***))" gives us the right syntax
|
| 60 |
+
# tree. The issue only occurs if there are several stars in
|
| 61 |
+
# sequence with no parenthesis inbetween, just possibly qualifiers.
|
| 62 |
+
# Attempt to fix it by adding some parentheses in the source: each
|
| 63 |
+
# time we see "* const" or "* const *", we add an opening
|
| 64 |
+
# parenthesis before each star---the hard part is figuring out where
|
| 65 |
+
# to close them.
|
| 66 |
+
parts = []
|
| 67 |
+
while True:
|
| 68 |
+
match = _r_star_const_space.search(csource)
|
| 69 |
+
if not match:
|
| 70 |
+
break
|
| 71 |
+
#print repr(''.join(parts)+csource), '=>',
|
| 72 |
+
parts.append(csource[:match.start()])
|
| 73 |
+
parts.append('('); closing = ')'
|
| 74 |
+
parts.append(match.group()) # e.g. "* const "
|
| 75 |
+
endpos = match.end()
|
| 76 |
+
if csource.startswith('*', endpos):
|
| 77 |
+
parts.append('('); closing += ')'
|
| 78 |
+
level = 0
|
| 79 |
+
i = endpos
|
| 80 |
+
while i < len(csource):
|
| 81 |
+
c = csource[i]
|
| 82 |
+
if c == '(':
|
| 83 |
+
level += 1
|
| 84 |
+
elif c == ')':
|
| 85 |
+
if level == 0:
|
| 86 |
+
break
|
| 87 |
+
level -= 1
|
| 88 |
+
elif c in ',;=':
|
| 89 |
+
if level == 0:
|
| 90 |
+
break
|
| 91 |
+
i += 1
|
| 92 |
+
csource = csource[endpos:i] + closing + csource[i:]
|
| 93 |
+
#print repr(''.join(parts)+csource)
|
| 94 |
+
parts.append(csource)
|
| 95 |
+
return ''.join(parts)
|
| 96 |
+
|
| 97 |
+
def _preprocess_extern_python(csource):
|
| 98 |
+
# input: `extern "Python" int foo(int);` or
|
| 99 |
+
# `extern "Python" { int foo(int); }`
|
| 100 |
+
# output:
|
| 101 |
+
# void __cffi_extern_python_start;
|
| 102 |
+
# int foo(int);
|
| 103 |
+
# void __cffi_extern_python_stop;
|
| 104 |
+
#
|
| 105 |
+
# input: `extern "Python+C" int foo(int);`
|
| 106 |
+
# output:
|
| 107 |
+
# void __cffi_extern_python_plus_c_start;
|
| 108 |
+
# int foo(int);
|
| 109 |
+
# void __cffi_extern_python_stop;
|
| 110 |
+
parts = []
|
| 111 |
+
while True:
|
| 112 |
+
match = _r_extern_python.search(csource)
|
| 113 |
+
if not match:
|
| 114 |
+
break
|
| 115 |
+
endpos = match.end() - 1
|
| 116 |
+
#print
|
| 117 |
+
#print ''.join(parts)+csource
|
| 118 |
+
#print '=>'
|
| 119 |
+
parts.append(csource[:match.start()])
|
| 120 |
+
if 'C' in match.group(1):
|
| 121 |
+
parts.append('void __cffi_extern_python_plus_c_start; ')
|
| 122 |
+
else:
|
| 123 |
+
parts.append('void __cffi_extern_python_start; ')
|
| 124 |
+
if csource[endpos] == '{':
|
| 125 |
+
# grouping variant
|
| 126 |
+
closing = csource.find('}', endpos)
|
| 127 |
+
if closing < 0:
|
| 128 |
+
raise CDefError("'extern \"Python\" {': no '}' found")
|
| 129 |
+
if csource.find('{', endpos + 1, closing) >= 0:
|
| 130 |
+
raise NotImplementedError("cannot use { } inside a block "
|
| 131 |
+
"'extern \"Python\" { ... }'")
|
| 132 |
+
parts.append(csource[endpos+1:closing])
|
| 133 |
+
csource = csource[closing+1:]
|
| 134 |
+
else:
|
| 135 |
+
# non-grouping variant
|
| 136 |
+
semicolon = csource.find(';', endpos)
|
| 137 |
+
if semicolon < 0:
|
| 138 |
+
raise CDefError("'extern \"Python\": no ';' found")
|
| 139 |
+
parts.append(csource[endpos:semicolon+1])
|
| 140 |
+
csource = csource[semicolon+1:]
|
| 141 |
+
parts.append(' void __cffi_extern_python_stop;')
|
| 142 |
+
#print ''.join(parts)+csource
|
| 143 |
+
#print
|
| 144 |
+
parts.append(csource)
|
| 145 |
+
return ''.join(parts)
|
| 146 |
+
|
| 147 |
+
def _warn_for_string_literal(csource):
|
| 148 |
+
if '"' in csource:
|
| 149 |
+
import warnings
|
| 150 |
+
warnings.warn("String literal found in cdef() or type source. "
|
| 151 |
+
"String literals are ignored here, but you should "
|
| 152 |
+
"remove them anyway because some character sequences "
|
| 153 |
+
"confuse pre-parsing.")
|
| 154 |
+
|
| 155 |
+
def _preprocess(csource):
|
| 156 |
+
# Remove comments. NOTE: this only work because the cdef() section
|
| 157 |
+
# should not contain any string literal!
|
| 158 |
+
csource = _r_comment.sub(' ', csource)
|
| 159 |
+
# Remove the "#define FOO x" lines
|
| 160 |
+
macros = {}
|
| 161 |
+
for match in _r_define.finditer(csource):
|
| 162 |
+
macroname, macrovalue = match.groups()
|
| 163 |
+
macrovalue = macrovalue.replace('\\\n', '').strip()
|
| 164 |
+
macros[macroname] = macrovalue
|
| 165 |
+
csource = _r_define.sub('', csource)
|
| 166 |
+
#
|
| 167 |
+
if pycparser.__version__ < '2.14':
|
| 168 |
+
csource = _workaround_for_old_pycparser(csource)
|
| 169 |
+
#
|
| 170 |
+
# BIG HACK: replace WINAPI or __stdcall with "volatile const".
|
| 171 |
+
# It doesn't make sense for the return type of a function to be
|
| 172 |
+
# "volatile volatile const", so we abuse it to detect __stdcall...
|
| 173 |
+
# Hack number 2 is that "int(volatile *fptr)();" is not valid C
|
| 174 |
+
# syntax, so we place the "volatile" before the opening parenthesis.
|
| 175 |
+
csource = _r_stdcall2.sub(' volatile volatile const(', csource)
|
| 176 |
+
csource = _r_stdcall1.sub(' volatile volatile const ', csource)
|
| 177 |
+
csource = _r_cdecl.sub(' ', csource)
|
| 178 |
+
#
|
| 179 |
+
# Replace `extern "Python"` with start/end markers
|
| 180 |
+
csource = _preprocess_extern_python(csource)
|
| 181 |
+
#
|
| 182 |
+
# Now there should not be any string literal left; warn if we get one
|
| 183 |
+
_warn_for_string_literal(csource)
|
| 184 |
+
#
|
| 185 |
+
# Replace "[...]" with "[__dotdotdotarray__]"
|
| 186 |
+
csource = _r_partial_array.sub('[__dotdotdotarray__]', csource)
|
| 187 |
+
#
|
| 188 |
+
# Replace "...}" with "__dotdotdotNUM__}". This construction should
|
| 189 |
+
# occur only at the end of enums; at the end of structs we have "...;}"
|
| 190 |
+
# and at the end of vararg functions "...);". Also replace "=...[,}]"
|
| 191 |
+
# with ",__dotdotdotNUM__[,}]": this occurs in the enums too, when
|
| 192 |
+
# giving an unknown value.
|
| 193 |
+
matches = list(_r_partial_enum.finditer(csource))
|
| 194 |
+
for number, match in enumerate(reversed(matches)):
|
| 195 |
+
p = match.start()
|
| 196 |
+
if csource[p] == '=':
|
| 197 |
+
p2 = csource.find('...', p, match.end())
|
| 198 |
+
assert p2 > p
|
| 199 |
+
csource = '%s,__dotdotdot%d__ %s' % (csource[:p], number,
|
| 200 |
+
csource[p2+3:])
|
| 201 |
+
else:
|
| 202 |
+
assert csource[p:p+3] == '...'
|
| 203 |
+
csource = '%s __dotdotdot%d__ %s' % (csource[:p], number,
|
| 204 |
+
csource[p+3:])
|
| 205 |
+
# Replace "int ..." or "unsigned long int..." with "__dotdotdotint__"
|
| 206 |
+
csource = _r_int_dotdotdot.sub(' __dotdotdotint__ ', csource)
|
| 207 |
+
# Replace "float ..." or "double..." with "__dotdotdotfloat__"
|
| 208 |
+
csource = _r_float_dotdotdot.sub(' __dotdotdotfloat__ ', csource)
|
| 209 |
+
# Replace all remaining "..." with the same name, "__dotdotdot__",
|
| 210 |
+
# which is declared with a typedef for the purpose of C parsing.
|
| 211 |
+
return csource.replace('...', ' __dotdotdot__ '), macros
|
| 212 |
+
|
| 213 |
+
def _common_type_names(csource):
|
| 214 |
+
# Look in the source for what looks like usages of types from the
|
| 215 |
+
# list of common types. A "usage" is approximated here as the
|
| 216 |
+
# appearance of the word, minus a "definition" of the type, which
|
| 217 |
+
# is the last word in a "typedef" statement. Approximative only
|
| 218 |
+
# but should be fine for all the common types.
|
| 219 |
+
look_for_words = set(COMMON_TYPES)
|
| 220 |
+
look_for_words.add(';')
|
| 221 |
+
look_for_words.add(',')
|
| 222 |
+
look_for_words.add('(')
|
| 223 |
+
look_for_words.add(')')
|
| 224 |
+
look_for_words.add('typedef')
|
| 225 |
+
words_used = set()
|
| 226 |
+
is_typedef = False
|
| 227 |
+
paren = 0
|
| 228 |
+
previous_word = ''
|
| 229 |
+
for word in _r_words.findall(csource):
|
| 230 |
+
if word in look_for_words:
|
| 231 |
+
if word == ';':
|
| 232 |
+
if is_typedef:
|
| 233 |
+
words_used.discard(previous_word)
|
| 234 |
+
look_for_words.discard(previous_word)
|
| 235 |
+
is_typedef = False
|
| 236 |
+
elif word == 'typedef':
|
| 237 |
+
is_typedef = True
|
| 238 |
+
paren = 0
|
| 239 |
+
elif word == '(':
|
| 240 |
+
paren += 1
|
| 241 |
+
elif word == ')':
|
| 242 |
+
paren -= 1
|
| 243 |
+
elif word == ',':
|
| 244 |
+
if is_typedef and paren == 0:
|
| 245 |
+
words_used.discard(previous_word)
|
| 246 |
+
look_for_words.discard(previous_word)
|
| 247 |
+
else: # word in COMMON_TYPES
|
| 248 |
+
words_used.add(word)
|
| 249 |
+
previous_word = word
|
| 250 |
+
return words_used
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class Parser(object):
|
| 254 |
+
|
| 255 |
+
def __init__(self):
|
| 256 |
+
self._declarations = {}
|
| 257 |
+
self._included_declarations = set()
|
| 258 |
+
self._anonymous_counter = 0
|
| 259 |
+
self._structnode2type = weakref.WeakKeyDictionary()
|
| 260 |
+
self._options = {}
|
| 261 |
+
self._int_constants = {}
|
| 262 |
+
self._recomplete = []
|
| 263 |
+
self._uses_new_feature = None
|
| 264 |
+
|
| 265 |
+
def _parse(self, csource):
|
| 266 |
+
csource, macros = _preprocess(csource)
|
| 267 |
+
# XXX: for more efficiency we would need to poke into the
|
| 268 |
+
# internals of CParser... the following registers the
|
| 269 |
+
# typedefs, because their presence or absence influences the
|
| 270 |
+
# parsing itself (but what they are typedef'ed to plays no role)
|
| 271 |
+
ctn = _common_type_names(csource)
|
| 272 |
+
typenames = []
|
| 273 |
+
for name in sorted(self._declarations):
|
| 274 |
+
if name.startswith('typedef '):
|
| 275 |
+
name = name[8:]
|
| 276 |
+
typenames.append(name)
|
| 277 |
+
ctn.discard(name)
|
| 278 |
+
typenames += sorted(ctn)
|
| 279 |
+
#
|
| 280 |
+
csourcelines = []
|
| 281 |
+
csourcelines.append('# 1 "<cdef automatic initialization code>"')
|
| 282 |
+
for typename in typenames:
|
| 283 |
+
csourcelines.append('typedef int %s;' % typename)
|
| 284 |
+
csourcelines.append('typedef int __dotdotdotint__, __dotdotdotfloat__,'
|
| 285 |
+
' __dotdotdot__;')
|
| 286 |
+
# this forces pycparser to consider the following in the file
|
| 287 |
+
# called <cdef source string> from line 1
|
| 288 |
+
csourcelines.append('# 1 "%s"' % (CDEF_SOURCE_STRING,))
|
| 289 |
+
csourcelines.append(csource)
|
| 290 |
+
fullcsource = '\n'.join(csourcelines)
|
| 291 |
+
if lock is not None:
|
| 292 |
+
lock.acquire() # pycparser is not thread-safe...
|
| 293 |
+
try:
|
| 294 |
+
ast = _get_parser().parse(fullcsource)
|
| 295 |
+
except pycparser.c_parser.ParseError as e:
|
| 296 |
+
self.convert_pycparser_error(e, csource)
|
| 297 |
+
finally:
|
| 298 |
+
if lock is not None:
|
| 299 |
+
lock.release()
|
| 300 |
+
# csource will be used to find buggy source text
|
| 301 |
+
return ast, macros, csource
|
| 302 |
+
|
| 303 |
+
def _convert_pycparser_error(self, e, csource):
|
| 304 |
+
# xxx look for "<cdef source string>:NUM:" at the start of str(e)
|
| 305 |
+
# and interpret that as a line number. This will not work if
|
| 306 |
+
# the user gives explicit ``# NUM "FILE"`` directives.
|
| 307 |
+
line = None
|
| 308 |
+
msg = str(e)
|
| 309 |
+
match = re.match(r"%s:(\d+):" % (CDEF_SOURCE_STRING,), msg)
|
| 310 |
+
if match:
|
| 311 |
+
linenum = int(match.group(1), 10)
|
| 312 |
+
csourcelines = csource.splitlines()
|
| 313 |
+
if 1 <= linenum <= len(csourcelines):
|
| 314 |
+
line = csourcelines[linenum-1]
|
| 315 |
+
return line
|
| 316 |
+
|
| 317 |
+
def convert_pycparser_error(self, e, csource):
|
| 318 |
+
line = self._convert_pycparser_error(e, csource)
|
| 319 |
+
|
| 320 |
+
msg = str(e)
|
| 321 |
+
if line:
|
| 322 |
+
msg = 'cannot parse "%s"\n%s' % (line.strip(), msg)
|
| 323 |
+
else:
|
| 324 |
+
msg = 'parse error\n%s' % (msg,)
|
| 325 |
+
raise CDefError(msg)
|
| 326 |
+
|
| 327 |
+
def parse(self, csource, override=False, packed=False, pack=None,
|
| 328 |
+
dllexport=False):
|
| 329 |
+
if packed:
|
| 330 |
+
if packed != True:
|
| 331 |
+
raise ValueError("'packed' should be False or True; use "
|
| 332 |
+
"'pack' to give another value")
|
| 333 |
+
if pack:
|
| 334 |
+
raise ValueError("cannot give both 'pack' and 'packed'")
|
| 335 |
+
pack = 1
|
| 336 |
+
elif pack:
|
| 337 |
+
if pack & (pack - 1):
|
| 338 |
+
raise ValueError("'pack' must be a power of two, not %r" %
|
| 339 |
+
(pack,))
|
| 340 |
+
else:
|
| 341 |
+
pack = 0
|
| 342 |
+
prev_options = self._options
|
| 343 |
+
try:
|
| 344 |
+
self._options = {'override': override,
|
| 345 |
+
'packed': pack,
|
| 346 |
+
'dllexport': dllexport}
|
| 347 |
+
self._internal_parse(csource)
|
| 348 |
+
finally:
|
| 349 |
+
self._options = prev_options
|
| 350 |
+
|
| 351 |
+
def _internal_parse(self, csource):
|
| 352 |
+
ast, macros, csource = self._parse(csource)
|
| 353 |
+
# add the macros
|
| 354 |
+
self._process_macros(macros)
|
| 355 |
+
# find the first "__dotdotdot__" and use that as a separator
|
| 356 |
+
# between the repeated typedefs and the real csource
|
| 357 |
+
iterator = iter(ast.ext)
|
| 358 |
+
for decl in iterator:
|
| 359 |
+
if decl.name == '__dotdotdot__':
|
| 360 |
+
break
|
| 361 |
+
else:
|
| 362 |
+
assert 0
|
| 363 |
+
current_decl = None
|
| 364 |
+
#
|
| 365 |
+
try:
|
| 366 |
+
self._inside_extern_python = '__cffi_extern_python_stop'
|
| 367 |
+
for decl in iterator:
|
| 368 |
+
current_decl = decl
|
| 369 |
+
if isinstance(decl, pycparser.c_ast.Decl):
|
| 370 |
+
self._parse_decl(decl)
|
| 371 |
+
elif isinstance(decl, pycparser.c_ast.Typedef):
|
| 372 |
+
if not decl.name:
|
| 373 |
+
raise CDefError("typedef does not declare any name",
|
| 374 |
+
decl)
|
| 375 |
+
quals = 0
|
| 376 |
+
if (isinstance(decl.type.type, pycparser.c_ast.IdentifierType) and
|
| 377 |
+
decl.type.type.names[-1].startswith('__dotdotdot')):
|
| 378 |
+
realtype = self._get_unknown_type(decl)
|
| 379 |
+
elif (isinstance(decl.type, pycparser.c_ast.PtrDecl) and
|
| 380 |
+
isinstance(decl.type.type, pycparser.c_ast.TypeDecl) and
|
| 381 |
+
isinstance(decl.type.type.type,
|
| 382 |
+
pycparser.c_ast.IdentifierType) and
|
| 383 |
+
decl.type.type.type.names[-1].startswith('__dotdotdot')):
|
| 384 |
+
realtype = self._get_unknown_ptr_type(decl)
|
| 385 |
+
else:
|
| 386 |
+
realtype, quals = self._get_type_and_quals(
|
| 387 |
+
decl.type, name=decl.name, partial_length_ok=True)
|
| 388 |
+
self._declare('typedef ' + decl.name, realtype, quals=quals)
|
| 389 |
+
elif decl.__class__.__name__ == 'Pragma':
|
| 390 |
+
pass # skip pragma, only in pycparser 2.15
|
| 391 |
+
else:
|
| 392 |
+
raise CDefError("unexpected <%s>: this construct is valid "
|
| 393 |
+
"C but not valid in cdef()" %
|
| 394 |
+
decl.__class__.__name__, decl)
|
| 395 |
+
except CDefError as e:
|
| 396 |
+
if len(e.args) == 1:
|
| 397 |
+
e.args = e.args + (current_decl,)
|
| 398 |
+
raise
|
| 399 |
+
except FFIError as e:
|
| 400 |
+
msg = self._convert_pycparser_error(e, csource)
|
| 401 |
+
if msg:
|
| 402 |
+
e.args = (e.args[0] + "\n *** Err: %s" % msg,)
|
| 403 |
+
raise
|
| 404 |
+
|
| 405 |
+
def _add_constants(self, key, val):
|
| 406 |
+
if key in self._int_constants:
|
| 407 |
+
if self._int_constants[key] == val:
|
| 408 |
+
return # ignore identical double declarations
|
| 409 |
+
raise FFIError(
|
| 410 |
+
"multiple declarations of constant: %s" % (key,))
|
| 411 |
+
self._int_constants[key] = val
|
| 412 |
+
|
| 413 |
+
def _add_integer_constant(self, name, int_str):
|
| 414 |
+
int_str = int_str.lower().rstrip("ul")
|
| 415 |
+
neg = int_str.startswith('-')
|
| 416 |
+
if neg:
|
| 417 |
+
int_str = int_str[1:]
|
| 418 |
+
# "010" is not valid oct in py3
|
| 419 |
+
if (int_str.startswith("0") and int_str != '0'
|
| 420 |
+
and not int_str.startswith("0x")):
|
| 421 |
+
int_str = "0o" + int_str[1:]
|
| 422 |
+
pyvalue = int(int_str, 0)
|
| 423 |
+
if neg:
|
| 424 |
+
pyvalue = -pyvalue
|
| 425 |
+
self._add_constants(name, pyvalue)
|
| 426 |
+
self._declare('macro ' + name, pyvalue)
|
| 427 |
+
|
| 428 |
+
def _process_macros(self, macros):
|
| 429 |
+
for key, value in macros.items():
|
| 430 |
+
value = value.strip()
|
| 431 |
+
if _r_int_literal.match(value):
|
| 432 |
+
self._add_integer_constant(key, value)
|
| 433 |
+
elif value == '...':
|
| 434 |
+
self._declare('macro ' + key, value)
|
| 435 |
+
else:
|
| 436 |
+
raise CDefError(
|
| 437 |
+
'only supports one of the following syntax:\n'
|
| 438 |
+
' #define %s ... (literally dot-dot-dot)\n'
|
| 439 |
+
' #define %s NUMBER (with NUMBER an integer'
|
| 440 |
+
' constant, decimal/hex/octal)\n'
|
| 441 |
+
'got:\n'
|
| 442 |
+
' #define %s %s'
|
| 443 |
+
% (key, key, key, value))
|
| 444 |
+
|
| 445 |
+
def _declare_function(self, tp, quals, decl):
|
| 446 |
+
tp = self._get_type_pointer(tp, quals)
|
| 447 |
+
if self._options.get('dllexport'):
|
| 448 |
+
tag = 'dllexport_python '
|
| 449 |
+
elif self._inside_extern_python == '__cffi_extern_python_start':
|
| 450 |
+
tag = 'extern_python '
|
| 451 |
+
elif self._inside_extern_python == '__cffi_extern_python_plus_c_start':
|
| 452 |
+
tag = 'extern_python_plus_c '
|
| 453 |
+
else:
|
| 454 |
+
tag = 'function '
|
| 455 |
+
self._declare(tag + decl.name, tp)
|
| 456 |
+
|
| 457 |
+
def _parse_decl(self, decl):
|
| 458 |
+
node = decl.type
|
| 459 |
+
if isinstance(node, pycparser.c_ast.FuncDecl):
|
| 460 |
+
tp, quals = self._get_type_and_quals(node, name=decl.name)
|
| 461 |
+
assert isinstance(tp, model.RawFunctionType)
|
| 462 |
+
self._declare_function(tp, quals, decl)
|
| 463 |
+
else:
|
| 464 |
+
if isinstance(node, pycparser.c_ast.Struct):
|
| 465 |
+
self._get_struct_union_enum_type('struct', node)
|
| 466 |
+
elif isinstance(node, pycparser.c_ast.Union):
|
| 467 |
+
self._get_struct_union_enum_type('union', node)
|
| 468 |
+
elif isinstance(node, pycparser.c_ast.Enum):
|
| 469 |
+
self._get_struct_union_enum_type('enum', node)
|
| 470 |
+
elif not decl.name:
|
| 471 |
+
raise CDefError("construct does not declare any variable",
|
| 472 |
+
decl)
|
| 473 |
+
#
|
| 474 |
+
if decl.name:
|
| 475 |
+
tp, quals = self._get_type_and_quals(node,
|
| 476 |
+
partial_length_ok=True)
|
| 477 |
+
if tp.is_raw_function:
|
| 478 |
+
self._declare_function(tp, quals, decl)
|
| 479 |
+
elif (tp.is_integer_type() and
|
| 480 |
+
hasattr(decl, 'init') and
|
| 481 |
+
hasattr(decl.init, 'value') and
|
| 482 |
+
_r_int_literal.match(decl.init.value)):
|
| 483 |
+
self._add_integer_constant(decl.name, decl.init.value)
|
| 484 |
+
elif (tp.is_integer_type() and
|
| 485 |
+
isinstance(decl.init, pycparser.c_ast.UnaryOp) and
|
| 486 |
+
decl.init.op == '-' and
|
| 487 |
+
hasattr(decl.init.expr, 'value') and
|
| 488 |
+
_r_int_literal.match(decl.init.expr.value)):
|
| 489 |
+
self._add_integer_constant(decl.name,
|
| 490 |
+
'-' + decl.init.expr.value)
|
| 491 |
+
elif (tp is model.void_type and
|
| 492 |
+
decl.name.startswith('__cffi_extern_python_')):
|
| 493 |
+
# hack: `extern "Python"` in the C source is replaced
|
| 494 |
+
# with "void __cffi_extern_python_start;" and
|
| 495 |
+
# "void __cffi_extern_python_stop;"
|
| 496 |
+
self._inside_extern_python = decl.name
|
| 497 |
+
else:
|
| 498 |
+
if self._inside_extern_python !='__cffi_extern_python_stop':
|
| 499 |
+
raise CDefError(
|
| 500 |
+
"cannot declare constants or "
|
| 501 |
+
"variables with 'extern \"Python\"'")
|
| 502 |
+
if (quals & model.Q_CONST) and not tp.is_array_type:
|
| 503 |
+
self._declare('constant ' + decl.name, tp, quals=quals)
|
| 504 |
+
else:
|
| 505 |
+
self._declare('variable ' + decl.name, tp, quals=quals)
|
| 506 |
+
|
| 507 |
+
def parse_type(self, cdecl):
|
| 508 |
+
return self.parse_type_and_quals(cdecl)[0]
|
| 509 |
+
|
| 510 |
+
def parse_type_and_quals(self, cdecl):
|
| 511 |
+
ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)[:2]
|
| 512 |
+
assert not macros
|
| 513 |
+
exprnode = ast.ext[-1].type.args.params[0]
|
| 514 |
+
if isinstance(exprnode, pycparser.c_ast.ID):
|
| 515 |
+
raise CDefError("unknown identifier '%s'" % (exprnode.name,))
|
| 516 |
+
return self._get_type_and_quals(exprnode.type)
|
| 517 |
+
|
| 518 |
+
def _declare(self, name, obj, included=False, quals=0):
|
| 519 |
+
if name in self._declarations:
|
| 520 |
+
prevobj, prevquals = self._declarations[name]
|
| 521 |
+
if prevobj is obj and prevquals == quals:
|
| 522 |
+
return
|
| 523 |
+
if not self._options.get('override'):
|
| 524 |
+
raise FFIError(
|
| 525 |
+
"multiple declarations of %s (for interactive usage, "
|
| 526 |
+
"try cdef(xx, override=True))" % (name,))
|
| 527 |
+
assert '__dotdotdot__' not in name.split()
|
| 528 |
+
self._declarations[name] = (obj, quals)
|
| 529 |
+
if included:
|
| 530 |
+
self._included_declarations.add(obj)
|
| 531 |
+
|
| 532 |
+
def _extract_quals(self, type):
|
| 533 |
+
quals = 0
|
| 534 |
+
if isinstance(type, (pycparser.c_ast.TypeDecl,
|
| 535 |
+
pycparser.c_ast.PtrDecl)):
|
| 536 |
+
if 'const' in type.quals:
|
| 537 |
+
quals |= model.Q_CONST
|
| 538 |
+
if 'volatile' in type.quals:
|
| 539 |
+
quals |= model.Q_VOLATILE
|
| 540 |
+
if 'restrict' in type.quals:
|
| 541 |
+
quals |= model.Q_RESTRICT
|
| 542 |
+
return quals
|
| 543 |
+
|
| 544 |
+
def _get_type_pointer(self, type, quals, declname=None):
|
| 545 |
+
if isinstance(type, model.RawFunctionType):
|
| 546 |
+
return type.as_function_pointer()
|
| 547 |
+
if (isinstance(type, model.StructOrUnionOrEnum) and
|
| 548 |
+
type.name.startswith('$') and type.name[1:].isdigit() and
|
| 549 |
+
type.forcename is None and declname is not None):
|
| 550 |
+
return model.NamedPointerType(type, declname, quals)
|
| 551 |
+
return model.PointerType(type, quals)
|
| 552 |
+
|
| 553 |
+
def _get_type_and_quals(self, typenode, name=None, partial_length_ok=False):
|
| 554 |
+
# first, dereference typedefs, if we have it already parsed, we're good
|
| 555 |
+
if (isinstance(typenode, pycparser.c_ast.TypeDecl) and
|
| 556 |
+
isinstance(typenode.type, pycparser.c_ast.IdentifierType) and
|
| 557 |
+
len(typenode.type.names) == 1 and
|
| 558 |
+
('typedef ' + typenode.type.names[0]) in self._declarations):
|
| 559 |
+
tp, quals = self._declarations['typedef ' + typenode.type.names[0]]
|
| 560 |
+
quals |= self._extract_quals(typenode)
|
| 561 |
+
return tp, quals
|
| 562 |
+
#
|
| 563 |
+
if isinstance(typenode, pycparser.c_ast.ArrayDecl):
|
| 564 |
+
# array type
|
| 565 |
+
if typenode.dim is None:
|
| 566 |
+
length = None
|
| 567 |
+
else:
|
| 568 |
+
length = self._parse_constant(
|
| 569 |
+
typenode.dim, partial_length_ok=partial_length_ok)
|
| 570 |
+
tp, quals = self._get_type_and_quals(typenode.type,
|
| 571 |
+
partial_length_ok=partial_length_ok)
|
| 572 |
+
return model.ArrayType(tp, length), quals
|
| 573 |
+
#
|
| 574 |
+
if isinstance(typenode, pycparser.c_ast.PtrDecl):
|
| 575 |
+
# pointer type
|
| 576 |
+
itemtype, itemquals = self._get_type_and_quals(typenode.type)
|
| 577 |
+
tp = self._get_type_pointer(itemtype, itemquals, declname=name)
|
| 578 |
+
quals = self._extract_quals(typenode)
|
| 579 |
+
return tp, quals
|
| 580 |
+
#
|
| 581 |
+
if isinstance(typenode, pycparser.c_ast.TypeDecl):
|
| 582 |
+
quals = self._extract_quals(typenode)
|
| 583 |
+
type = typenode.type
|
| 584 |
+
if isinstance(type, pycparser.c_ast.IdentifierType):
|
| 585 |
+
# assume a primitive type. get it from .names, but reduce
|
| 586 |
+
# synonyms to a single chosen combination
|
| 587 |
+
names = list(type.names)
|
| 588 |
+
if names != ['signed', 'char']: # keep this unmodified
|
| 589 |
+
prefixes = {}
|
| 590 |
+
while names:
|
| 591 |
+
name = names[0]
|
| 592 |
+
if name in ('short', 'long', 'signed', 'unsigned'):
|
| 593 |
+
prefixes[name] = prefixes.get(name, 0) + 1
|
| 594 |
+
del names[0]
|
| 595 |
+
else:
|
| 596 |
+
break
|
| 597 |
+
# ignore the 'signed' prefix below, and reorder the others
|
| 598 |
+
newnames = []
|
| 599 |
+
for prefix in ('unsigned', 'short', 'long'):
|
| 600 |
+
for i in range(prefixes.get(prefix, 0)):
|
| 601 |
+
newnames.append(prefix)
|
| 602 |
+
if not names:
|
| 603 |
+
names = ['int'] # implicitly
|
| 604 |
+
if names == ['int']: # but kill it if 'short' or 'long'
|
| 605 |
+
if 'short' in prefixes or 'long' in prefixes:
|
| 606 |
+
names = []
|
| 607 |
+
names = newnames + names
|
| 608 |
+
ident = ' '.join(names)
|
| 609 |
+
if ident == 'void':
|
| 610 |
+
return model.void_type, quals
|
| 611 |
+
if ident == '__dotdotdot__':
|
| 612 |
+
raise FFIError(':%d: bad usage of "..."' %
|
| 613 |
+
typenode.coord.line)
|
| 614 |
+
tp0, quals0 = resolve_common_type(self, ident)
|
| 615 |
+
return tp0, (quals | quals0)
|
| 616 |
+
#
|
| 617 |
+
if isinstance(type, pycparser.c_ast.Struct):
|
| 618 |
+
# 'struct foobar'
|
| 619 |
+
tp = self._get_struct_union_enum_type('struct', type, name)
|
| 620 |
+
return tp, quals
|
| 621 |
+
#
|
| 622 |
+
if isinstance(type, pycparser.c_ast.Union):
|
| 623 |
+
# 'union foobar'
|
| 624 |
+
tp = self._get_struct_union_enum_type('union', type, name)
|
| 625 |
+
return tp, quals
|
| 626 |
+
#
|
| 627 |
+
if isinstance(type, pycparser.c_ast.Enum):
|
| 628 |
+
# 'enum foobar'
|
| 629 |
+
tp = self._get_struct_union_enum_type('enum', type, name)
|
| 630 |
+
return tp, quals
|
| 631 |
+
#
|
| 632 |
+
if isinstance(typenode, pycparser.c_ast.FuncDecl):
|
| 633 |
+
# a function type
|
| 634 |
+
return self._parse_function_type(typenode, name), 0
|
| 635 |
+
#
|
| 636 |
+
# nested anonymous structs or unions end up here
|
| 637 |
+
if isinstance(typenode, pycparser.c_ast.Struct):
|
| 638 |
+
return self._get_struct_union_enum_type('struct', typenode, name,
|
| 639 |
+
nested=True), 0
|
| 640 |
+
if isinstance(typenode, pycparser.c_ast.Union):
|
| 641 |
+
return self._get_struct_union_enum_type('union', typenode, name,
|
| 642 |
+
nested=True), 0
|
| 643 |
+
#
|
| 644 |
+
raise FFIError(":%d: bad or unsupported type declaration" %
|
| 645 |
+
typenode.coord.line)
|
| 646 |
+
|
| 647 |
+
def _parse_function_type(self, typenode, funcname=None):
|
| 648 |
+
params = list(getattr(typenode.args, 'params', []))
|
| 649 |
+
for i, arg in enumerate(params):
|
| 650 |
+
if not hasattr(arg, 'type'):
|
| 651 |
+
raise CDefError("%s arg %d: unknown type '%s'"
|
| 652 |
+
" (if you meant to use the old C syntax of giving"
|
| 653 |
+
" untyped arguments, it is not supported)"
|
| 654 |
+
% (funcname or 'in expression', i + 1,
|
| 655 |
+
getattr(arg, 'name', '?')))
|
| 656 |
+
ellipsis = (
|
| 657 |
+
len(params) > 0 and
|
| 658 |
+
isinstance(params[-1].type, pycparser.c_ast.TypeDecl) and
|
| 659 |
+
isinstance(params[-1].type.type,
|
| 660 |
+
pycparser.c_ast.IdentifierType) and
|
| 661 |
+
params[-1].type.type.names == ['__dotdotdot__'])
|
| 662 |
+
if ellipsis:
|
| 663 |
+
params.pop()
|
| 664 |
+
if not params:
|
| 665 |
+
raise CDefError(
|
| 666 |
+
"%s: a function with only '(...)' as argument"
|
| 667 |
+
" is not correct C" % (funcname or 'in expression'))
|
| 668 |
+
args = [self._as_func_arg(*self._get_type_and_quals(argdeclnode.type))
|
| 669 |
+
for argdeclnode in params]
|
| 670 |
+
if not ellipsis and args == [model.void_type]:
|
| 671 |
+
args = []
|
| 672 |
+
result, quals = self._get_type_and_quals(typenode.type)
|
| 673 |
+
# the 'quals' on the result type are ignored. HACK: we absure them
|
| 674 |
+
# to detect __stdcall functions: we textually replace "__stdcall"
|
| 675 |
+
# with "volatile volatile const" above.
|
| 676 |
+
abi = None
|
| 677 |
+
if hasattr(typenode.type, 'quals'): # else, probable syntax error anyway
|
| 678 |
+
if typenode.type.quals[-3:] == ['volatile', 'volatile', 'const']:
|
| 679 |
+
abi = '__stdcall'
|
| 680 |
+
return model.RawFunctionType(tuple(args), result, ellipsis, abi)
|
| 681 |
+
|
| 682 |
+
def _as_func_arg(self, type, quals):
|
| 683 |
+
if isinstance(type, model.ArrayType):
|
| 684 |
+
return model.PointerType(type.item, quals)
|
| 685 |
+
elif isinstance(type, model.RawFunctionType):
|
| 686 |
+
return type.as_function_pointer()
|
| 687 |
+
else:
|
| 688 |
+
return type
|
| 689 |
+
|
| 690 |
+
def _get_struct_union_enum_type(self, kind, type, name=None, nested=False):
|
| 691 |
+
# First, a level of caching on the exact 'type' node of the AST.
|
| 692 |
+
# This is obscure, but needed because pycparser "unrolls" declarations
|
| 693 |
+
# such as "typedef struct { } foo_t, *foo_p" and we end up with
|
| 694 |
+
# an AST that is not a tree, but a DAG, with the "type" node of the
|
| 695 |
+
# two branches foo_t and foo_p of the trees being the same node.
|
| 696 |
+
# It's a bit silly but detecting "DAG-ness" in the AST tree seems
|
| 697 |
+
# to be the only way to distinguish this case from two independent
|
| 698 |
+
# structs. See test_struct_with_two_usages.
|
| 699 |
+
try:
|
| 700 |
+
return self._structnode2type[type]
|
| 701 |
+
except KeyError:
|
| 702 |
+
pass
|
| 703 |
+
#
|
| 704 |
+
# Note that this must handle parsing "struct foo" any number of
|
| 705 |
+
# times and always return the same StructType object. Additionally,
|
| 706 |
+
# one of these times (not necessarily the first), the fields of
|
| 707 |
+
# the struct can be specified with "struct foo { ...fields... }".
|
| 708 |
+
# If no name is given, then we have to create a new anonymous struct
|
| 709 |
+
# with no caching; in this case, the fields are either specified
|
| 710 |
+
# right now or never.
|
| 711 |
+
#
|
| 712 |
+
force_name = name
|
| 713 |
+
name = type.name
|
| 714 |
+
#
|
| 715 |
+
# get the type or create it if needed
|
| 716 |
+
if name is None:
|
| 717 |
+
# 'force_name' is used to guess a more readable name for
|
| 718 |
+
# anonymous structs, for the common case "typedef struct { } foo".
|
| 719 |
+
if force_name is not None:
|
| 720 |
+
explicit_name = '$%s' % force_name
|
| 721 |
+
else:
|
| 722 |
+
self._anonymous_counter += 1
|
| 723 |
+
explicit_name = '$%d' % self._anonymous_counter
|
| 724 |
+
tp = None
|
| 725 |
+
else:
|
| 726 |
+
explicit_name = name
|
| 727 |
+
key = '%s %s' % (kind, name)
|
| 728 |
+
tp, _ = self._declarations.get(key, (None, None))
|
| 729 |
+
#
|
| 730 |
+
if tp is None:
|
| 731 |
+
if kind == 'struct':
|
| 732 |
+
tp = model.StructType(explicit_name, None, None, None)
|
| 733 |
+
elif kind == 'union':
|
| 734 |
+
tp = model.UnionType(explicit_name, None, None, None)
|
| 735 |
+
elif kind == 'enum':
|
| 736 |
+
if explicit_name == '__dotdotdot__':
|
| 737 |
+
raise CDefError("Enums cannot be declared with ...")
|
| 738 |
+
tp = self._build_enum_type(explicit_name, type.values)
|
| 739 |
+
else:
|
| 740 |
+
raise AssertionError("kind = %r" % (kind,))
|
| 741 |
+
if name is not None:
|
| 742 |
+
self._declare(key, tp)
|
| 743 |
+
else:
|
| 744 |
+
if kind == 'enum' and type.values is not None:
|
| 745 |
+
raise NotImplementedError(
|
| 746 |
+
"enum %s: the '{}' declaration should appear on the first "
|
| 747 |
+
"time the enum is mentioned, not later" % explicit_name)
|
| 748 |
+
if not tp.forcename:
|
| 749 |
+
tp.force_the_name(force_name)
|
| 750 |
+
if tp.forcename and '$' in tp.name:
|
| 751 |
+
self._declare('anonymous %s' % tp.forcename, tp)
|
| 752 |
+
#
|
| 753 |
+
self._structnode2type[type] = tp
|
| 754 |
+
#
|
| 755 |
+
# enums: done here
|
| 756 |
+
if kind == 'enum':
|
| 757 |
+
return tp
|
| 758 |
+
#
|
| 759 |
+
# is there a 'type.decls'? If yes, then this is the place in the
|
| 760 |
+
# C sources that declare the fields. If no, then just return the
|
| 761 |
+
# existing type, possibly still incomplete.
|
| 762 |
+
if type.decls is None:
|
| 763 |
+
return tp
|
| 764 |
+
#
|
| 765 |
+
if tp.fldnames is not None:
|
| 766 |
+
raise CDefError("duplicate declaration of struct %s" % name)
|
| 767 |
+
fldnames = []
|
| 768 |
+
fldtypes = []
|
| 769 |
+
fldbitsize = []
|
| 770 |
+
fldquals = []
|
| 771 |
+
for decl in type.decls:
|
| 772 |
+
if (isinstance(decl.type, pycparser.c_ast.IdentifierType) and
|
| 773 |
+
''.join(decl.type.names) == '__dotdotdot__'):
|
| 774 |
+
# XXX pycparser is inconsistent: 'names' should be a list
|
| 775 |
+
# of strings, but is sometimes just one string. Use
|
| 776 |
+
# str.join() as a way to cope with both.
|
| 777 |
+
self._make_partial(tp, nested)
|
| 778 |
+
continue
|
| 779 |
+
if decl.bitsize is None:
|
| 780 |
+
bitsize = -1
|
| 781 |
+
else:
|
| 782 |
+
bitsize = self._parse_constant(decl.bitsize)
|
| 783 |
+
self._partial_length = False
|
| 784 |
+
type, fqual = self._get_type_and_quals(decl.type,
|
| 785 |
+
partial_length_ok=True)
|
| 786 |
+
if self._partial_length:
|
| 787 |
+
self._make_partial(tp, nested)
|
| 788 |
+
if isinstance(type, model.StructType) and type.partial:
|
| 789 |
+
self._make_partial(tp, nested)
|
| 790 |
+
fldnames.append(decl.name or '')
|
| 791 |
+
fldtypes.append(type)
|
| 792 |
+
fldbitsize.append(bitsize)
|
| 793 |
+
fldquals.append(fqual)
|
| 794 |
+
tp.fldnames = tuple(fldnames)
|
| 795 |
+
tp.fldtypes = tuple(fldtypes)
|
| 796 |
+
tp.fldbitsize = tuple(fldbitsize)
|
| 797 |
+
tp.fldquals = tuple(fldquals)
|
| 798 |
+
if fldbitsize != [-1] * len(fldbitsize):
|
| 799 |
+
if isinstance(tp, model.StructType) and tp.partial:
|
| 800 |
+
raise NotImplementedError("%s: using both bitfields and '...;'"
|
| 801 |
+
% (tp,))
|
| 802 |
+
tp.packed = self._options.get('packed')
|
| 803 |
+
if tp.completed: # must be re-completed: it is not opaque any more
|
| 804 |
+
tp.completed = 0
|
| 805 |
+
self._recomplete.append(tp)
|
| 806 |
+
return tp
|
| 807 |
+
|
| 808 |
+
def _make_partial(self, tp, nested):
|
| 809 |
+
if not isinstance(tp, model.StructOrUnion):
|
| 810 |
+
raise CDefError("%s cannot be partial" % (tp,))
|
| 811 |
+
if not tp.has_c_name() and not nested:
|
| 812 |
+
raise NotImplementedError("%s is partial but has no C name" %(tp,))
|
| 813 |
+
tp.partial = True
|
| 814 |
+
|
| 815 |
+
def _parse_constant(self, exprnode, partial_length_ok=False):
|
| 816 |
+
# for now, limited to expressions that are an immediate number
|
| 817 |
+
# or positive/negative number
|
| 818 |
+
if isinstance(exprnode, pycparser.c_ast.Constant):
|
| 819 |
+
s = exprnode.value
|
| 820 |
+
if '0' <= s[0] <= '9':
|
| 821 |
+
s = s.rstrip('uUlL')
|
| 822 |
+
try:
|
| 823 |
+
if s.startswith('0'):
|
| 824 |
+
return int(s, 8)
|
| 825 |
+
else:
|
| 826 |
+
return int(s, 10)
|
| 827 |
+
except ValueError:
|
| 828 |
+
if len(s) > 1:
|
| 829 |
+
if s.lower()[0:2] == '0x':
|
| 830 |
+
return int(s, 16)
|
| 831 |
+
elif s.lower()[0:2] == '0b':
|
| 832 |
+
return int(s, 2)
|
| 833 |
+
raise CDefError("invalid constant %r" % (s,))
|
| 834 |
+
elif s[0] == "'" and s[-1] == "'" and (
|
| 835 |
+
len(s) == 3 or (len(s) == 4 and s[1] == "\\")):
|
| 836 |
+
return ord(s[-2])
|
| 837 |
+
else:
|
| 838 |
+
raise CDefError("invalid constant %r" % (s,))
|
| 839 |
+
#
|
| 840 |
+
if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
|
| 841 |
+
exprnode.op == '+'):
|
| 842 |
+
return self._parse_constant(exprnode.expr)
|
| 843 |
+
#
|
| 844 |
+
if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
|
| 845 |
+
exprnode.op == '-'):
|
| 846 |
+
return -self._parse_constant(exprnode.expr)
|
| 847 |
+
# load previously defined int constant
|
| 848 |
+
if (isinstance(exprnode, pycparser.c_ast.ID) and
|
| 849 |
+
exprnode.name in self._int_constants):
|
| 850 |
+
return self._int_constants[exprnode.name]
|
| 851 |
+
#
|
| 852 |
+
if (isinstance(exprnode, pycparser.c_ast.ID) and
|
| 853 |
+
exprnode.name == '__dotdotdotarray__'):
|
| 854 |
+
if partial_length_ok:
|
| 855 |
+
self._partial_length = True
|
| 856 |
+
return '...'
|
| 857 |
+
raise FFIError(":%d: unsupported '[...]' here, cannot derive "
|
| 858 |
+
"the actual array length in this context"
|
| 859 |
+
% exprnode.coord.line)
|
| 860 |
+
#
|
| 861 |
+
if (isinstance(exprnode, pycparser.c_ast.BinaryOp) and
|
| 862 |
+
exprnode.op == '+'):
|
| 863 |
+
return (self._parse_constant(exprnode.left) +
|
| 864 |
+
self._parse_constant(exprnode.right))
|
| 865 |
+
#
|
| 866 |
+
if (isinstance(exprnode, pycparser.c_ast.BinaryOp) and
|
| 867 |
+
exprnode.op == '-'):
|
| 868 |
+
return (self._parse_constant(exprnode.left) -
|
| 869 |
+
self._parse_constant(exprnode.right))
|
| 870 |
+
#
|
| 871 |
+
raise FFIError(":%d: unsupported expression: expected a "
|
| 872 |
+
"simple numeric constant" % exprnode.coord.line)
|
| 873 |
+
|
| 874 |
+
def _build_enum_type(self, explicit_name, decls):
|
| 875 |
+
if decls is not None:
|
| 876 |
+
partial = False
|
| 877 |
+
enumerators = []
|
| 878 |
+
enumvalues = []
|
| 879 |
+
nextenumvalue = 0
|
| 880 |
+
for enum in decls.enumerators:
|
| 881 |
+
if _r_enum_dotdotdot.match(enum.name):
|
| 882 |
+
partial = True
|
| 883 |
+
continue
|
| 884 |
+
if enum.value is not None:
|
| 885 |
+
nextenumvalue = self._parse_constant(enum.value)
|
| 886 |
+
enumerators.append(enum.name)
|
| 887 |
+
enumvalues.append(nextenumvalue)
|
| 888 |
+
self._add_constants(enum.name, nextenumvalue)
|
| 889 |
+
nextenumvalue += 1
|
| 890 |
+
enumerators = tuple(enumerators)
|
| 891 |
+
enumvalues = tuple(enumvalues)
|
| 892 |
+
tp = model.EnumType(explicit_name, enumerators, enumvalues)
|
| 893 |
+
tp.partial = partial
|
| 894 |
+
else: # opaque enum
|
| 895 |
+
tp = model.EnumType(explicit_name, (), ())
|
| 896 |
+
return tp
|
| 897 |
+
|
| 898 |
+
def include(self, other):
|
| 899 |
+
for name, (tp, quals) in other._declarations.items():
|
| 900 |
+
if name.startswith('anonymous $enum_$'):
|
| 901 |
+
continue # fix for test_anonymous_enum_include
|
| 902 |
+
kind = name.split(' ', 1)[0]
|
| 903 |
+
if kind in ('struct', 'union', 'enum', 'anonymous', 'typedef'):
|
| 904 |
+
self._declare(name, tp, included=True, quals=quals)
|
| 905 |
+
for k, v in other._int_constants.items():
|
| 906 |
+
self._add_constants(k, v)
|
| 907 |
+
|
| 908 |
+
def _get_unknown_type(self, decl):
|
| 909 |
+
typenames = decl.type.type.names
|
| 910 |
+
if typenames == ['__dotdotdot__']:
|
| 911 |
+
return model.unknown_type(decl.name)
|
| 912 |
+
|
| 913 |
+
if typenames == ['__dotdotdotint__']:
|
| 914 |
+
if self._uses_new_feature is None:
|
| 915 |
+
self._uses_new_feature = "'typedef int... %s'" % decl.name
|
| 916 |
+
return model.UnknownIntegerType(decl.name)
|
| 917 |
+
|
| 918 |
+
if typenames == ['__dotdotdotfloat__']:
|
| 919 |
+
# note: not for 'long double' so far
|
| 920 |
+
if self._uses_new_feature is None:
|
| 921 |
+
self._uses_new_feature = "'typedef float... %s'" % decl.name
|
| 922 |
+
return model.UnknownFloatType(decl.name)
|
| 923 |
+
|
| 924 |
+
raise FFIError(':%d: unsupported usage of "..." in typedef'
|
| 925 |
+
% decl.coord.line)
|
| 926 |
+
|
| 927 |
+
def _get_unknown_ptr_type(self, decl):
|
| 928 |
+
if decl.type.type.type.names == ['__dotdotdot__']:
|
| 929 |
+
return model.unknown_ptr_type(decl.name)
|
| 930 |
+
raise FFIError(':%d: unsupported usage of "..." in typedef'
|
| 931 |
+
% decl.coord.line)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/error.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
class FFIError(Exception):
|
| 3 |
+
__module__ = 'cffi'
|
| 4 |
+
|
| 5 |
+
class CDefError(Exception):
|
| 6 |
+
__module__ = 'cffi'
|
| 7 |
+
def __str__(self):
|
| 8 |
+
try:
|
| 9 |
+
current_decl = self.args[1]
|
| 10 |
+
filename = current_decl.coord.file
|
| 11 |
+
linenum = current_decl.coord.line
|
| 12 |
+
prefix = '%s:%d: ' % (filename, linenum)
|
| 13 |
+
except (AttributeError, TypeError, IndexError):
|
| 14 |
+
prefix = ''
|
| 15 |
+
return '%s%s' % (prefix, self.args[0])
|
| 16 |
+
|
| 17 |
+
class VerificationError(Exception):
|
| 18 |
+
""" An error raised when verification fails
|
| 19 |
+
"""
|
| 20 |
+
__module__ = 'cffi'
|
| 21 |
+
|
| 22 |
+
class VerificationMissing(Exception):
|
| 23 |
+
""" An error raised when incomplete structures are passed into
|
| 24 |
+
cdef, but no verification has been done
|
| 25 |
+
"""
|
| 26 |
+
__module__ = 'cffi'
|
| 27 |
+
|
| 28 |
+
class PkgConfigError(Exception):
|
| 29 |
+
""" An error raised for missing modules in pkg-config
|
| 30 |
+
"""
|
| 31 |
+
__module__ = 'cffi'
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/ffiplatform.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys, os
|
| 2 |
+
from .error import VerificationError
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
LIST_OF_FILE_NAMES = ['sources', 'include_dirs', 'library_dirs',
|
| 6 |
+
'extra_objects', 'depends']
|
| 7 |
+
|
| 8 |
+
def get_extension(srcfilename, modname, sources=(), **kwds):
|
| 9 |
+
_hack_at_distutils()
|
| 10 |
+
from distutils.core import Extension
|
| 11 |
+
allsources = [srcfilename]
|
| 12 |
+
for src in sources:
|
| 13 |
+
allsources.append(os.path.normpath(src))
|
| 14 |
+
return Extension(name=modname, sources=allsources, **kwds)
|
| 15 |
+
|
| 16 |
+
def compile(tmpdir, ext, compiler_verbose=0, debug=None):
|
| 17 |
+
"""Compile a C extension module using distutils."""
|
| 18 |
+
|
| 19 |
+
_hack_at_distutils()
|
| 20 |
+
saved_environ = os.environ.copy()
|
| 21 |
+
try:
|
| 22 |
+
outputfilename = _build(tmpdir, ext, compiler_verbose, debug)
|
| 23 |
+
outputfilename = os.path.abspath(outputfilename)
|
| 24 |
+
finally:
|
| 25 |
+
# workaround for a distutils bugs where some env vars can
|
| 26 |
+
# become longer and longer every time it is used
|
| 27 |
+
for key, value in saved_environ.items():
|
| 28 |
+
if os.environ.get(key) != value:
|
| 29 |
+
os.environ[key] = value
|
| 30 |
+
return outputfilename
|
| 31 |
+
|
| 32 |
+
def _build(tmpdir, ext, compiler_verbose=0, debug=None):
|
| 33 |
+
# XXX compact but horrible :-(
|
| 34 |
+
from distutils.core import Distribution
|
| 35 |
+
import distutils.errors, distutils.log
|
| 36 |
+
#
|
| 37 |
+
dist = Distribution({'ext_modules': [ext]})
|
| 38 |
+
dist.parse_config_files()
|
| 39 |
+
options = dist.get_option_dict('build_ext')
|
| 40 |
+
if debug is None:
|
| 41 |
+
debug = sys.flags.debug
|
| 42 |
+
options['debug'] = ('ffiplatform', debug)
|
| 43 |
+
options['force'] = ('ffiplatform', True)
|
| 44 |
+
options['build_lib'] = ('ffiplatform', tmpdir)
|
| 45 |
+
options['build_temp'] = ('ffiplatform', tmpdir)
|
| 46 |
+
#
|
| 47 |
+
try:
|
| 48 |
+
old_level = distutils.log.set_threshold(0) or 0
|
| 49 |
+
try:
|
| 50 |
+
distutils.log.set_verbosity(compiler_verbose)
|
| 51 |
+
dist.run_command('build_ext')
|
| 52 |
+
cmd_obj = dist.get_command_obj('build_ext')
|
| 53 |
+
[soname] = cmd_obj.get_outputs()
|
| 54 |
+
finally:
|
| 55 |
+
distutils.log.set_threshold(old_level)
|
| 56 |
+
except (distutils.errors.CompileError,
|
| 57 |
+
distutils.errors.LinkError) as e:
|
| 58 |
+
raise VerificationError('%s: %s' % (e.__class__.__name__, e))
|
| 59 |
+
#
|
| 60 |
+
return soname
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
from os.path import samefile
|
| 64 |
+
except ImportError:
|
| 65 |
+
def samefile(f1, f2):
|
| 66 |
+
return os.path.abspath(f1) == os.path.abspath(f2)
|
| 67 |
+
|
| 68 |
+
def maybe_relative_path(path):
|
| 69 |
+
if not os.path.isabs(path):
|
| 70 |
+
return path # already relative
|
| 71 |
+
dir = path
|
| 72 |
+
names = []
|
| 73 |
+
while True:
|
| 74 |
+
prevdir = dir
|
| 75 |
+
dir, name = os.path.split(prevdir)
|
| 76 |
+
if dir == prevdir or not dir:
|
| 77 |
+
return path # failed to make it relative
|
| 78 |
+
names.append(name)
|
| 79 |
+
try:
|
| 80 |
+
if samefile(dir, os.curdir):
|
| 81 |
+
names.reverse()
|
| 82 |
+
return os.path.join(*names)
|
| 83 |
+
except OSError:
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
# ____________________________________________________________
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
int_or_long = (int, long)
|
| 90 |
+
import cStringIO
|
| 91 |
+
except NameError:
|
| 92 |
+
int_or_long = int # Python 3
|
| 93 |
+
import io as cStringIO
|
| 94 |
+
|
| 95 |
+
def _flatten(x, f):
|
| 96 |
+
if isinstance(x, str):
|
| 97 |
+
f.write('%ds%s' % (len(x), x))
|
| 98 |
+
elif isinstance(x, dict):
|
| 99 |
+
keys = sorted(x.keys())
|
| 100 |
+
f.write('%dd' % len(keys))
|
| 101 |
+
for key in keys:
|
| 102 |
+
_flatten(key, f)
|
| 103 |
+
_flatten(x[key], f)
|
| 104 |
+
elif isinstance(x, (list, tuple)):
|
| 105 |
+
f.write('%dl' % len(x))
|
| 106 |
+
for value in x:
|
| 107 |
+
_flatten(value, f)
|
| 108 |
+
elif isinstance(x, int_or_long):
|
| 109 |
+
f.write('%di' % (x,))
|
| 110 |
+
else:
|
| 111 |
+
raise TypeError(
|
| 112 |
+
"the keywords to verify() contains unsupported object %r" % (x,))
|
| 113 |
+
|
| 114 |
+
def flatten(x):
|
| 115 |
+
f = cStringIO.StringIO()
|
| 116 |
+
_flatten(x, f)
|
| 117 |
+
return f.getvalue()
|
| 118 |
+
|
| 119 |
+
def _hack_at_distutils():
|
| 120 |
+
# Windows-only workaround for some configurations: see
|
| 121 |
+
# https://bugs.python.org/issue23246 (Python 2.7 with
|
| 122 |
+
# a specific MS compiler suite download)
|
| 123 |
+
if sys.platform == "win32":
|
| 124 |
+
try:
|
| 125 |
+
import setuptools # for side-effects, patches distutils
|
| 126 |
+
except ImportError:
|
| 127 |
+
pass
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/lock.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
if sys.version_info < (3,):
|
| 4 |
+
try:
|
| 5 |
+
from thread import allocate_lock
|
| 6 |
+
except ImportError:
|
| 7 |
+
from dummy_thread import allocate_lock
|
| 8 |
+
else:
|
| 9 |
+
try:
|
| 10 |
+
from _thread import allocate_lock
|
| 11 |
+
except ImportError:
|
| 12 |
+
from _dummy_thread import allocate_lock
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
##import sys
|
| 16 |
+
##l1 = allocate_lock
|
| 17 |
+
|
| 18 |
+
##class allocate_lock(object):
|
| 19 |
+
## def __init__(self):
|
| 20 |
+
## self._real = l1()
|
| 21 |
+
## def __enter__(self):
|
| 22 |
+
## for i in range(4, 0, -1):
|
| 23 |
+
## print sys._getframe(i).f_code
|
| 24 |
+
## print
|
| 25 |
+
## return self._real.__enter__()
|
| 26 |
+
## def __exit__(self, *args):
|
| 27 |
+
## return self._real.__exit__(*args)
|
| 28 |
+
## def acquire(self, f):
|
| 29 |
+
## assert f is False
|
| 30 |
+
## return self._real.acquire(f)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import types
|
| 2 |
+
import weakref
|
| 3 |
+
|
| 4 |
+
from .lock import allocate_lock
|
| 5 |
+
from .error import CDefError, VerificationError, VerificationMissing
|
| 6 |
+
|
| 7 |
+
# type qualifiers
|
| 8 |
+
Q_CONST = 0x01
|
| 9 |
+
Q_RESTRICT = 0x02
|
| 10 |
+
Q_VOLATILE = 0x04
|
| 11 |
+
|
| 12 |
+
def qualify(quals, replace_with):
|
| 13 |
+
if quals & Q_CONST:
|
| 14 |
+
replace_with = ' const ' + replace_with.lstrip()
|
| 15 |
+
if quals & Q_VOLATILE:
|
| 16 |
+
replace_with = ' volatile ' + replace_with.lstrip()
|
| 17 |
+
if quals & Q_RESTRICT:
|
| 18 |
+
# It seems that __restrict is supported by gcc and msvc.
|
| 19 |
+
# If you hit some different compiler, add a #define in
|
| 20 |
+
# _cffi_include.h for it (and in its copies, documented there)
|
| 21 |
+
replace_with = ' __restrict ' + replace_with.lstrip()
|
| 22 |
+
return replace_with
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class BaseTypeByIdentity(object):
|
| 26 |
+
is_array_type = False
|
| 27 |
+
is_raw_function = False
|
| 28 |
+
|
| 29 |
+
def get_c_name(self, replace_with='', context='a C file', quals=0):
|
| 30 |
+
result = self.c_name_with_marker
|
| 31 |
+
assert result.count('&') == 1
|
| 32 |
+
# some logic duplication with ffi.getctype()... :-(
|
| 33 |
+
replace_with = replace_with.strip()
|
| 34 |
+
if replace_with:
|
| 35 |
+
if replace_with.startswith('*') and '&[' in result:
|
| 36 |
+
replace_with = '(%s)' % replace_with
|
| 37 |
+
elif not replace_with[0] in '[(':
|
| 38 |
+
replace_with = ' ' + replace_with
|
| 39 |
+
replace_with = qualify(quals, replace_with)
|
| 40 |
+
result = result.replace('&', replace_with)
|
| 41 |
+
if '$' in result:
|
| 42 |
+
raise VerificationError(
|
| 43 |
+
"cannot generate '%s' in %s: unknown type name"
|
| 44 |
+
% (self._get_c_name(), context))
|
| 45 |
+
return result
|
| 46 |
+
|
| 47 |
+
def _get_c_name(self):
|
| 48 |
+
return self.c_name_with_marker.replace('&', '')
|
| 49 |
+
|
| 50 |
+
def has_c_name(self):
|
| 51 |
+
return '$' not in self._get_c_name()
|
| 52 |
+
|
| 53 |
+
def is_integer_type(self):
|
| 54 |
+
return False
|
| 55 |
+
|
| 56 |
+
def get_cached_btype(self, ffi, finishlist, can_delay=False):
|
| 57 |
+
try:
|
| 58 |
+
BType = ffi._cached_btypes[self]
|
| 59 |
+
except KeyError:
|
| 60 |
+
BType = self.build_backend_type(ffi, finishlist)
|
| 61 |
+
BType2 = ffi._cached_btypes.setdefault(self, BType)
|
| 62 |
+
assert BType2 is BType
|
| 63 |
+
return BType
|
| 64 |
+
|
| 65 |
+
def __repr__(self):
|
| 66 |
+
return '<%s>' % (self._get_c_name(),)
|
| 67 |
+
|
| 68 |
+
def _get_items(self):
|
| 69 |
+
return [(name, getattr(self, name)) for name in self._attrs_]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class BaseType(BaseTypeByIdentity):
|
| 73 |
+
|
| 74 |
+
def __eq__(self, other):
|
| 75 |
+
return (self.__class__ == other.__class__ and
|
| 76 |
+
self._get_items() == other._get_items())
|
| 77 |
+
|
| 78 |
+
def __ne__(self, other):
|
| 79 |
+
return not self == other
|
| 80 |
+
|
| 81 |
+
def __hash__(self):
|
| 82 |
+
return hash((self.__class__, tuple(self._get_items())))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class VoidType(BaseType):
|
| 86 |
+
_attrs_ = ()
|
| 87 |
+
|
| 88 |
+
def __init__(self):
|
| 89 |
+
self.c_name_with_marker = 'void&'
|
| 90 |
+
|
| 91 |
+
def build_backend_type(self, ffi, finishlist):
|
| 92 |
+
return global_cache(self, ffi, 'new_void_type')
|
| 93 |
+
|
| 94 |
+
void_type = VoidType()
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class BasePrimitiveType(BaseType):
|
| 98 |
+
def is_complex_type(self):
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class PrimitiveType(BasePrimitiveType):
|
| 103 |
+
_attrs_ = ('name',)
|
| 104 |
+
|
| 105 |
+
ALL_PRIMITIVE_TYPES = {
|
| 106 |
+
'char': 'c',
|
| 107 |
+
'short': 'i',
|
| 108 |
+
'int': 'i',
|
| 109 |
+
'long': 'i',
|
| 110 |
+
'long long': 'i',
|
| 111 |
+
'signed char': 'i',
|
| 112 |
+
'unsigned char': 'i',
|
| 113 |
+
'unsigned short': 'i',
|
| 114 |
+
'unsigned int': 'i',
|
| 115 |
+
'unsigned long': 'i',
|
| 116 |
+
'unsigned long long': 'i',
|
| 117 |
+
'float': 'f',
|
| 118 |
+
'double': 'f',
|
| 119 |
+
'long double': 'f',
|
| 120 |
+
'float _Complex': 'j',
|
| 121 |
+
'double _Complex': 'j',
|
| 122 |
+
'_Bool': 'i',
|
| 123 |
+
# the following types are not primitive in the C sense
|
| 124 |
+
'wchar_t': 'c',
|
| 125 |
+
'char16_t': 'c',
|
| 126 |
+
'char32_t': 'c',
|
| 127 |
+
'int8_t': 'i',
|
| 128 |
+
'uint8_t': 'i',
|
| 129 |
+
'int16_t': 'i',
|
| 130 |
+
'uint16_t': 'i',
|
| 131 |
+
'int32_t': 'i',
|
| 132 |
+
'uint32_t': 'i',
|
| 133 |
+
'int64_t': 'i',
|
| 134 |
+
'uint64_t': 'i',
|
| 135 |
+
'int_least8_t': 'i',
|
| 136 |
+
'uint_least8_t': 'i',
|
| 137 |
+
'int_least16_t': 'i',
|
| 138 |
+
'uint_least16_t': 'i',
|
| 139 |
+
'int_least32_t': 'i',
|
| 140 |
+
'uint_least32_t': 'i',
|
| 141 |
+
'int_least64_t': 'i',
|
| 142 |
+
'uint_least64_t': 'i',
|
| 143 |
+
'int_fast8_t': 'i',
|
| 144 |
+
'uint_fast8_t': 'i',
|
| 145 |
+
'int_fast16_t': 'i',
|
| 146 |
+
'uint_fast16_t': 'i',
|
| 147 |
+
'int_fast32_t': 'i',
|
| 148 |
+
'uint_fast32_t': 'i',
|
| 149 |
+
'int_fast64_t': 'i',
|
| 150 |
+
'uint_fast64_t': 'i',
|
| 151 |
+
'intptr_t': 'i',
|
| 152 |
+
'uintptr_t': 'i',
|
| 153 |
+
'intmax_t': 'i',
|
| 154 |
+
'uintmax_t': 'i',
|
| 155 |
+
'ptrdiff_t': 'i',
|
| 156 |
+
'size_t': 'i',
|
| 157 |
+
'ssize_t': 'i',
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
def __init__(self, name):
|
| 161 |
+
assert name in self.ALL_PRIMITIVE_TYPES
|
| 162 |
+
self.name = name
|
| 163 |
+
self.c_name_with_marker = name + '&'
|
| 164 |
+
|
| 165 |
+
def is_char_type(self):
|
| 166 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'c'
|
| 167 |
+
def is_integer_type(self):
|
| 168 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'i'
|
| 169 |
+
def is_float_type(self):
|
| 170 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'f'
|
| 171 |
+
def is_complex_type(self):
|
| 172 |
+
return self.ALL_PRIMITIVE_TYPES[self.name] == 'j'
|
| 173 |
+
|
| 174 |
+
def build_backend_type(self, ffi, finishlist):
|
| 175 |
+
return global_cache(self, ffi, 'new_primitive_type', self.name)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class UnknownIntegerType(BasePrimitiveType):
|
| 179 |
+
_attrs_ = ('name',)
|
| 180 |
+
|
| 181 |
+
def __init__(self, name):
|
| 182 |
+
self.name = name
|
| 183 |
+
self.c_name_with_marker = name + '&'
|
| 184 |
+
|
| 185 |
+
def is_integer_type(self):
|
| 186 |
+
return True
|
| 187 |
+
|
| 188 |
+
def build_backend_type(self, ffi, finishlist):
|
| 189 |
+
raise NotImplementedError("integer type '%s' can only be used after "
|
| 190 |
+
"compilation" % self.name)
|
| 191 |
+
|
| 192 |
+
class UnknownFloatType(BasePrimitiveType):
|
| 193 |
+
_attrs_ = ('name', )
|
| 194 |
+
|
| 195 |
+
def __init__(self, name):
|
| 196 |
+
self.name = name
|
| 197 |
+
self.c_name_with_marker = name + '&'
|
| 198 |
+
|
| 199 |
+
def build_backend_type(self, ffi, finishlist):
|
| 200 |
+
raise NotImplementedError("float type '%s' can only be used after "
|
| 201 |
+
"compilation" % self.name)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class BaseFunctionType(BaseType):
|
| 205 |
+
_attrs_ = ('args', 'result', 'ellipsis', 'abi')
|
| 206 |
+
|
| 207 |
+
def __init__(self, args, result, ellipsis, abi=None):
|
| 208 |
+
self.args = args
|
| 209 |
+
self.result = result
|
| 210 |
+
self.ellipsis = ellipsis
|
| 211 |
+
self.abi = abi
|
| 212 |
+
#
|
| 213 |
+
reprargs = [arg._get_c_name() for arg in self.args]
|
| 214 |
+
if self.ellipsis:
|
| 215 |
+
reprargs.append('...')
|
| 216 |
+
reprargs = reprargs or ['void']
|
| 217 |
+
replace_with = self._base_pattern % (', '.join(reprargs),)
|
| 218 |
+
if abi is not None:
|
| 219 |
+
replace_with = replace_with[:1] + abi + ' ' + replace_with[1:]
|
| 220 |
+
self.c_name_with_marker = (
|
| 221 |
+
self.result.c_name_with_marker.replace('&', replace_with))
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class RawFunctionType(BaseFunctionType):
|
| 225 |
+
# Corresponds to a C type like 'int(int)', which is the C type of
|
| 226 |
+
# a function, but not a pointer-to-function. The backend has no
|
| 227 |
+
# notion of such a type; it's used temporarily by parsing.
|
| 228 |
+
_base_pattern = '(&)(%s)'
|
| 229 |
+
is_raw_function = True
|
| 230 |
+
|
| 231 |
+
def build_backend_type(self, ffi, finishlist):
|
| 232 |
+
raise CDefError("cannot render the type %r: it is a function "
|
| 233 |
+
"type, not a pointer-to-function type" % (self,))
|
| 234 |
+
|
| 235 |
+
def as_function_pointer(self):
|
| 236 |
+
return FunctionPtrType(self.args, self.result, self.ellipsis, self.abi)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class FunctionPtrType(BaseFunctionType):
|
| 240 |
+
_base_pattern = '(*&)(%s)'
|
| 241 |
+
|
| 242 |
+
def build_backend_type(self, ffi, finishlist):
|
| 243 |
+
result = self.result.get_cached_btype(ffi, finishlist)
|
| 244 |
+
args = []
|
| 245 |
+
for tp in self.args:
|
| 246 |
+
args.append(tp.get_cached_btype(ffi, finishlist))
|
| 247 |
+
abi_args = ()
|
| 248 |
+
if self.abi == "__stdcall":
|
| 249 |
+
if not self.ellipsis: # __stdcall ignored for variadic funcs
|
| 250 |
+
try:
|
| 251 |
+
abi_args = (ffi._backend.FFI_STDCALL,)
|
| 252 |
+
except AttributeError:
|
| 253 |
+
pass
|
| 254 |
+
return global_cache(self, ffi, 'new_function_type',
|
| 255 |
+
tuple(args), result, self.ellipsis, *abi_args)
|
| 256 |
+
|
| 257 |
+
def as_raw_function(self):
|
| 258 |
+
return RawFunctionType(self.args, self.result, self.ellipsis, self.abi)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class PointerType(BaseType):
|
| 262 |
+
_attrs_ = ('totype', 'quals')
|
| 263 |
+
|
| 264 |
+
def __init__(self, totype, quals=0):
|
| 265 |
+
self.totype = totype
|
| 266 |
+
self.quals = quals
|
| 267 |
+
extra = qualify(quals, " *&")
|
| 268 |
+
if totype.is_array_type:
|
| 269 |
+
extra = "(%s)" % (extra.lstrip(),)
|
| 270 |
+
self.c_name_with_marker = totype.c_name_with_marker.replace('&', extra)
|
| 271 |
+
|
| 272 |
+
def build_backend_type(self, ffi, finishlist):
|
| 273 |
+
BItem = self.totype.get_cached_btype(ffi, finishlist, can_delay=True)
|
| 274 |
+
return global_cache(self, ffi, 'new_pointer_type', BItem)
|
| 275 |
+
|
| 276 |
+
voidp_type = PointerType(void_type)
|
| 277 |
+
|
| 278 |
+
def ConstPointerType(totype):
|
| 279 |
+
return PointerType(totype, Q_CONST)
|
| 280 |
+
|
| 281 |
+
const_voidp_type = ConstPointerType(void_type)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class NamedPointerType(PointerType):
|
| 285 |
+
_attrs_ = ('totype', 'name')
|
| 286 |
+
|
| 287 |
+
def __init__(self, totype, name, quals=0):
|
| 288 |
+
PointerType.__init__(self, totype, quals)
|
| 289 |
+
self.name = name
|
| 290 |
+
self.c_name_with_marker = name + '&'
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class ArrayType(BaseType):
|
| 294 |
+
_attrs_ = ('item', 'length')
|
| 295 |
+
is_array_type = True
|
| 296 |
+
|
| 297 |
+
def __init__(self, item, length):
|
| 298 |
+
self.item = item
|
| 299 |
+
self.length = length
|
| 300 |
+
#
|
| 301 |
+
if length is None:
|
| 302 |
+
brackets = '&[]'
|
| 303 |
+
elif length == '...':
|
| 304 |
+
brackets = '&[/*...*/]'
|
| 305 |
+
else:
|
| 306 |
+
brackets = '&[%s]' % length
|
| 307 |
+
self.c_name_with_marker = (
|
| 308 |
+
self.item.c_name_with_marker.replace('&', brackets))
|
| 309 |
+
|
| 310 |
+
def resolve_length(self, newlength):
|
| 311 |
+
return ArrayType(self.item, newlength)
|
| 312 |
+
|
| 313 |
+
def build_backend_type(self, ffi, finishlist):
|
| 314 |
+
if self.length == '...':
|
| 315 |
+
raise CDefError("cannot render the type %r: unknown length" %
|
| 316 |
+
(self,))
|
| 317 |
+
self.item.get_cached_btype(ffi, finishlist) # force the item BType
|
| 318 |
+
BPtrItem = PointerType(self.item).get_cached_btype(ffi, finishlist)
|
| 319 |
+
return global_cache(self, ffi, 'new_array_type', BPtrItem, self.length)
|
| 320 |
+
|
| 321 |
+
char_array_type = ArrayType(PrimitiveType('char'), None)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class StructOrUnionOrEnum(BaseTypeByIdentity):
|
| 325 |
+
_attrs_ = ('name',)
|
| 326 |
+
forcename = None
|
| 327 |
+
|
| 328 |
+
def build_c_name_with_marker(self):
|
| 329 |
+
name = self.forcename or '%s %s' % (self.kind, self.name)
|
| 330 |
+
self.c_name_with_marker = name + '&'
|
| 331 |
+
|
| 332 |
+
def force_the_name(self, forcename):
|
| 333 |
+
self.forcename = forcename
|
| 334 |
+
self.build_c_name_with_marker()
|
| 335 |
+
|
| 336 |
+
def get_official_name(self):
|
| 337 |
+
assert self.c_name_with_marker.endswith('&')
|
| 338 |
+
return self.c_name_with_marker[:-1]
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class StructOrUnion(StructOrUnionOrEnum):
|
| 342 |
+
fixedlayout = None
|
| 343 |
+
completed = 0
|
| 344 |
+
partial = False
|
| 345 |
+
packed = 0
|
| 346 |
+
|
| 347 |
+
def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None):
|
| 348 |
+
self.name = name
|
| 349 |
+
self.fldnames = fldnames
|
| 350 |
+
self.fldtypes = fldtypes
|
| 351 |
+
self.fldbitsize = fldbitsize
|
| 352 |
+
self.fldquals = fldquals
|
| 353 |
+
self.build_c_name_with_marker()
|
| 354 |
+
|
| 355 |
+
def anonymous_struct_fields(self):
|
| 356 |
+
if self.fldtypes is not None:
|
| 357 |
+
for name, type in zip(self.fldnames, self.fldtypes):
|
| 358 |
+
if name == '' and isinstance(type, StructOrUnion):
|
| 359 |
+
yield type
|
| 360 |
+
|
| 361 |
+
def enumfields(self, expand_anonymous_struct_union=True):
|
| 362 |
+
fldquals = self.fldquals
|
| 363 |
+
if fldquals is None:
|
| 364 |
+
fldquals = (0,) * len(self.fldnames)
|
| 365 |
+
for name, type, bitsize, quals in zip(self.fldnames, self.fldtypes,
|
| 366 |
+
self.fldbitsize, fldquals):
|
| 367 |
+
if (name == '' and isinstance(type, StructOrUnion)
|
| 368 |
+
and expand_anonymous_struct_union):
|
| 369 |
+
# nested anonymous struct/union
|
| 370 |
+
for result in type.enumfields():
|
| 371 |
+
yield result
|
| 372 |
+
else:
|
| 373 |
+
yield (name, type, bitsize, quals)
|
| 374 |
+
|
| 375 |
+
def force_flatten(self):
|
| 376 |
+
# force the struct or union to have a declaration that lists
|
| 377 |
+
# directly all fields returned by enumfields(), flattening
|
| 378 |
+
# nested anonymous structs/unions.
|
| 379 |
+
names = []
|
| 380 |
+
types = []
|
| 381 |
+
bitsizes = []
|
| 382 |
+
fldquals = []
|
| 383 |
+
for name, type, bitsize, quals in self.enumfields():
|
| 384 |
+
names.append(name)
|
| 385 |
+
types.append(type)
|
| 386 |
+
bitsizes.append(bitsize)
|
| 387 |
+
fldquals.append(quals)
|
| 388 |
+
self.fldnames = tuple(names)
|
| 389 |
+
self.fldtypes = tuple(types)
|
| 390 |
+
self.fldbitsize = tuple(bitsizes)
|
| 391 |
+
self.fldquals = tuple(fldquals)
|
| 392 |
+
|
| 393 |
+
def get_cached_btype(self, ffi, finishlist, can_delay=False):
|
| 394 |
+
BType = StructOrUnionOrEnum.get_cached_btype(self, ffi, finishlist,
|
| 395 |
+
can_delay)
|
| 396 |
+
if not can_delay:
|
| 397 |
+
self.finish_backend_type(ffi, finishlist)
|
| 398 |
+
return BType
|
| 399 |
+
|
| 400 |
+
def finish_backend_type(self, ffi, finishlist):
|
| 401 |
+
if self.completed:
|
| 402 |
+
if self.completed != 2:
|
| 403 |
+
raise NotImplementedError("recursive structure declaration "
|
| 404 |
+
"for '%s'" % (self.name,))
|
| 405 |
+
return
|
| 406 |
+
BType = ffi._cached_btypes[self]
|
| 407 |
+
#
|
| 408 |
+
self.completed = 1
|
| 409 |
+
#
|
| 410 |
+
if self.fldtypes is None:
|
| 411 |
+
pass # not completing it: it's an opaque struct
|
| 412 |
+
#
|
| 413 |
+
elif self.fixedlayout is None:
|
| 414 |
+
fldtypes = [tp.get_cached_btype(ffi, finishlist)
|
| 415 |
+
for tp in self.fldtypes]
|
| 416 |
+
lst = list(zip(self.fldnames, fldtypes, self.fldbitsize))
|
| 417 |
+
extra_flags = ()
|
| 418 |
+
if self.packed:
|
| 419 |
+
if self.packed == 1:
|
| 420 |
+
extra_flags = (8,) # SF_PACKED
|
| 421 |
+
else:
|
| 422 |
+
extra_flags = (0, self.packed)
|
| 423 |
+
ffi._backend.complete_struct_or_union(BType, lst, self,
|
| 424 |
+
-1, -1, *extra_flags)
|
| 425 |
+
#
|
| 426 |
+
else:
|
| 427 |
+
fldtypes = []
|
| 428 |
+
fieldofs, fieldsize, totalsize, totalalignment = self.fixedlayout
|
| 429 |
+
for i in range(len(self.fldnames)):
|
| 430 |
+
fsize = fieldsize[i]
|
| 431 |
+
ftype = self.fldtypes[i]
|
| 432 |
+
#
|
| 433 |
+
if isinstance(ftype, ArrayType) and ftype.length == '...':
|
| 434 |
+
# fix the length to match the total size
|
| 435 |
+
BItemType = ftype.item.get_cached_btype(ffi, finishlist)
|
| 436 |
+
nlen, nrest = divmod(fsize, ffi.sizeof(BItemType))
|
| 437 |
+
if nrest != 0:
|
| 438 |
+
self._verification_error(
|
| 439 |
+
"field '%s.%s' has a bogus size?" % (
|
| 440 |
+
self.name, self.fldnames[i] or '{}'))
|
| 441 |
+
ftype = ftype.resolve_length(nlen)
|
| 442 |
+
self.fldtypes = (self.fldtypes[:i] + (ftype,) +
|
| 443 |
+
self.fldtypes[i+1:])
|
| 444 |
+
#
|
| 445 |
+
BFieldType = ftype.get_cached_btype(ffi, finishlist)
|
| 446 |
+
if isinstance(ftype, ArrayType) and ftype.length is None:
|
| 447 |
+
assert fsize == 0
|
| 448 |
+
else:
|
| 449 |
+
bitemsize = ffi.sizeof(BFieldType)
|
| 450 |
+
if bitemsize != fsize:
|
| 451 |
+
self._verification_error(
|
| 452 |
+
"field '%s.%s' is declared as %d bytes, but is "
|
| 453 |
+
"really %d bytes" % (self.name,
|
| 454 |
+
self.fldnames[i] or '{}',
|
| 455 |
+
bitemsize, fsize))
|
| 456 |
+
fldtypes.append(BFieldType)
|
| 457 |
+
#
|
| 458 |
+
lst = list(zip(self.fldnames, fldtypes, self.fldbitsize, fieldofs))
|
| 459 |
+
ffi._backend.complete_struct_or_union(BType, lst, self,
|
| 460 |
+
totalsize, totalalignment)
|
| 461 |
+
self.completed = 2
|
| 462 |
+
|
| 463 |
+
def _verification_error(self, msg):
|
| 464 |
+
raise VerificationError(msg)
|
| 465 |
+
|
| 466 |
+
def check_not_partial(self):
|
| 467 |
+
if self.partial and self.fixedlayout is None:
|
| 468 |
+
raise VerificationMissing(self._get_c_name())
|
| 469 |
+
|
| 470 |
+
def build_backend_type(self, ffi, finishlist):
|
| 471 |
+
self.check_not_partial()
|
| 472 |
+
finishlist.append(self)
|
| 473 |
+
#
|
| 474 |
+
return global_cache(self, ffi, 'new_%s_type' % self.kind,
|
| 475 |
+
self.get_official_name(), key=self)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class StructType(StructOrUnion):
|
| 479 |
+
kind = 'struct'
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class UnionType(StructOrUnion):
|
| 483 |
+
kind = 'union'
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class EnumType(StructOrUnionOrEnum):
|
| 487 |
+
kind = 'enum'
|
| 488 |
+
partial = False
|
| 489 |
+
partial_resolved = False
|
| 490 |
+
|
| 491 |
+
def __init__(self, name, enumerators, enumvalues, baseinttype=None):
|
| 492 |
+
self.name = name
|
| 493 |
+
self.enumerators = enumerators
|
| 494 |
+
self.enumvalues = enumvalues
|
| 495 |
+
self.baseinttype = baseinttype
|
| 496 |
+
self.build_c_name_with_marker()
|
| 497 |
+
|
| 498 |
+
def force_the_name(self, forcename):
|
| 499 |
+
StructOrUnionOrEnum.force_the_name(self, forcename)
|
| 500 |
+
if self.forcename is None:
|
| 501 |
+
name = self.get_official_name()
|
| 502 |
+
self.forcename = '$' + name.replace(' ', '_')
|
| 503 |
+
|
| 504 |
+
def check_not_partial(self):
|
| 505 |
+
if self.partial and not self.partial_resolved:
|
| 506 |
+
raise VerificationMissing(self._get_c_name())
|
| 507 |
+
|
| 508 |
+
def build_backend_type(self, ffi, finishlist):
|
| 509 |
+
self.check_not_partial()
|
| 510 |
+
base_btype = self.build_baseinttype(ffi, finishlist)
|
| 511 |
+
return global_cache(self, ffi, 'new_enum_type',
|
| 512 |
+
self.get_official_name(),
|
| 513 |
+
self.enumerators, self.enumvalues,
|
| 514 |
+
base_btype, key=self)
|
| 515 |
+
|
| 516 |
+
def build_baseinttype(self, ffi, finishlist):
|
| 517 |
+
if self.baseinttype is not None:
|
| 518 |
+
return self.baseinttype.get_cached_btype(ffi, finishlist)
|
| 519 |
+
#
|
| 520 |
+
if self.enumvalues:
|
| 521 |
+
smallest_value = min(self.enumvalues)
|
| 522 |
+
largest_value = max(self.enumvalues)
|
| 523 |
+
else:
|
| 524 |
+
import warnings
|
| 525 |
+
try:
|
| 526 |
+
# XXX! The goal is to ensure that the warnings.warn()
|
| 527 |
+
# will not suppress the warning. We want to get it
|
| 528 |
+
# several times if we reach this point several times.
|
| 529 |
+
__warningregistry__.clear()
|
| 530 |
+
except NameError:
|
| 531 |
+
pass
|
| 532 |
+
warnings.warn("%r has no values explicitly defined; "
|
| 533 |
+
"guessing that it is equivalent to 'unsigned int'"
|
| 534 |
+
% self._get_c_name())
|
| 535 |
+
smallest_value = largest_value = 0
|
| 536 |
+
if smallest_value < 0: # needs a signed type
|
| 537 |
+
sign = 1
|
| 538 |
+
candidate1 = PrimitiveType("int")
|
| 539 |
+
candidate2 = PrimitiveType("long")
|
| 540 |
+
else:
|
| 541 |
+
sign = 0
|
| 542 |
+
candidate1 = PrimitiveType("unsigned int")
|
| 543 |
+
candidate2 = PrimitiveType("unsigned long")
|
| 544 |
+
btype1 = candidate1.get_cached_btype(ffi, finishlist)
|
| 545 |
+
btype2 = candidate2.get_cached_btype(ffi, finishlist)
|
| 546 |
+
size1 = ffi.sizeof(btype1)
|
| 547 |
+
size2 = ffi.sizeof(btype2)
|
| 548 |
+
if (smallest_value >= ((-1) << (8*size1-1)) and
|
| 549 |
+
largest_value < (1 << (8*size1-sign))):
|
| 550 |
+
return btype1
|
| 551 |
+
if (smallest_value >= ((-1) << (8*size2-1)) and
|
| 552 |
+
largest_value < (1 << (8*size2-sign))):
|
| 553 |
+
return btype2
|
| 554 |
+
raise CDefError("%s values don't all fit into either 'long' "
|
| 555 |
+
"or 'unsigned long'" % self._get_c_name())
|
| 556 |
+
|
| 557 |
+
def unknown_type(name, structname=None):
|
| 558 |
+
if structname is None:
|
| 559 |
+
structname = '$%s' % name
|
| 560 |
+
tp = StructType(structname, None, None, None)
|
| 561 |
+
tp.force_the_name(name)
|
| 562 |
+
tp.origin = "unknown_type"
|
| 563 |
+
return tp
|
| 564 |
+
|
| 565 |
+
def unknown_ptr_type(name, structname=None):
|
| 566 |
+
if structname is None:
|
| 567 |
+
structname = '$$%s' % name
|
| 568 |
+
tp = StructType(structname, None, None, None)
|
| 569 |
+
return NamedPointerType(tp, name)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
global_lock = allocate_lock()
|
| 573 |
+
_typecache_cffi_backend = weakref.WeakValueDictionary()
|
| 574 |
+
|
| 575 |
+
def get_typecache(backend):
|
| 576 |
+
# returns _typecache_cffi_backend if backend is the _cffi_backend
|
| 577 |
+
# module, or type(backend).__typecache if backend is an instance of
|
| 578 |
+
# CTypesBackend (or some FakeBackend class during tests)
|
| 579 |
+
if isinstance(backend, types.ModuleType):
|
| 580 |
+
return _typecache_cffi_backend
|
| 581 |
+
with global_lock:
|
| 582 |
+
if not hasattr(type(backend), '__typecache'):
|
| 583 |
+
type(backend).__typecache = weakref.WeakValueDictionary()
|
| 584 |
+
return type(backend).__typecache
|
| 585 |
+
|
| 586 |
+
def global_cache(srctype, ffi, funcname, *args, **kwds):
|
| 587 |
+
key = kwds.pop('key', (funcname, args))
|
| 588 |
+
assert not kwds
|
| 589 |
+
try:
|
| 590 |
+
return ffi._typecache[key]
|
| 591 |
+
except KeyError:
|
| 592 |
+
pass
|
| 593 |
+
try:
|
| 594 |
+
res = getattr(ffi._backend, funcname)(*args)
|
| 595 |
+
except NotImplementedError as e:
|
| 596 |
+
raise NotImplementedError("%s: %r: %s" % (funcname, srctype, e))
|
| 597 |
+
# note that setdefault() on WeakValueDictionary is not atomic
|
| 598 |
+
# and contains a rare bug (http://bugs.python.org/issue19542);
|
| 599 |
+
# we have to use a lock and do it ourselves
|
| 600 |
+
cache = ffi._typecache
|
| 601 |
+
with global_lock:
|
| 602 |
+
res1 = cache.get(key)
|
| 603 |
+
if res1 is None:
|
| 604 |
+
cache[key] = res
|
| 605 |
+
return res
|
| 606 |
+
else:
|
| 607 |
+
return res1
|
| 608 |
+
|
| 609 |
+
def pointer_cache(ffi, BType):
|
| 610 |
+
return global_cache('?', ffi, 'new_pointer_type', BType)
|
| 611 |
+
|
| 612 |
+
def attach_exception_info(e, name):
|
| 613 |
+
if e.args and type(e.args[0]) is str:
|
| 614 |
+
e.args = ('%s: %s' % (name, e.args[0]),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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
/* This part is from file 'cffi/parse_c_type.h'. It is copied at the
|
| 3 |
+
beginning of C sources generated by CFFI's ffi.set_source(). */
|
| 4 |
+
|
| 5 |
+
typedef void *_cffi_opcode_t;
|
| 6 |
+
|
| 7 |
+
#define _CFFI_OP(opcode, arg) (_cffi_opcode_t)(opcode | (((uintptr_t)(arg)) << 8))
|
| 8 |
+
#define _CFFI_GETOP(cffi_opcode) ((unsigned char)(uintptr_t)cffi_opcode)
|
| 9 |
+
#define _CFFI_GETARG(cffi_opcode) (((intptr_t)cffi_opcode) >> 8)
|
| 10 |
+
|
| 11 |
+
#define _CFFI_OP_PRIMITIVE 1
|
| 12 |
+
#define _CFFI_OP_POINTER 3
|
| 13 |
+
#define _CFFI_OP_ARRAY 5
|
| 14 |
+
#define _CFFI_OP_OPEN_ARRAY 7
|
| 15 |
+
#define _CFFI_OP_STRUCT_UNION 9
|
| 16 |
+
#define _CFFI_OP_ENUM 11
|
| 17 |
+
#define _CFFI_OP_FUNCTION 13
|
| 18 |
+
#define _CFFI_OP_FUNCTION_END 15
|
| 19 |
+
#define _CFFI_OP_NOOP 17
|
| 20 |
+
#define _CFFI_OP_BITFIELD 19
|
| 21 |
+
#define _CFFI_OP_TYPENAME 21
|
| 22 |
+
#define _CFFI_OP_CPYTHON_BLTN_V 23 // varargs
|
| 23 |
+
#define _CFFI_OP_CPYTHON_BLTN_N 25 // noargs
|
| 24 |
+
#define _CFFI_OP_CPYTHON_BLTN_O 27 // O (i.e. a single arg)
|
| 25 |
+
#define _CFFI_OP_CONSTANT 29
|
| 26 |
+
#define _CFFI_OP_CONSTANT_INT 31
|
| 27 |
+
#define _CFFI_OP_GLOBAL_VAR 33
|
| 28 |
+
#define _CFFI_OP_DLOPEN_FUNC 35
|
| 29 |
+
#define _CFFI_OP_DLOPEN_CONST 37
|
| 30 |
+
#define _CFFI_OP_GLOBAL_VAR_F 39
|
| 31 |
+
#define _CFFI_OP_EXTERN_PYTHON 41
|
| 32 |
+
|
| 33 |
+
#define _CFFI_PRIM_VOID 0
|
| 34 |
+
#define _CFFI_PRIM_BOOL 1
|
| 35 |
+
#define _CFFI_PRIM_CHAR 2
|
| 36 |
+
#define _CFFI_PRIM_SCHAR 3
|
| 37 |
+
#define _CFFI_PRIM_UCHAR 4
|
| 38 |
+
#define _CFFI_PRIM_SHORT 5
|
| 39 |
+
#define _CFFI_PRIM_USHORT 6
|
| 40 |
+
#define _CFFI_PRIM_INT 7
|
| 41 |
+
#define _CFFI_PRIM_UINT 8
|
| 42 |
+
#define _CFFI_PRIM_LONG 9
|
| 43 |
+
#define _CFFI_PRIM_ULONG 10
|
| 44 |
+
#define _CFFI_PRIM_LONGLONG 11
|
| 45 |
+
#define _CFFI_PRIM_ULONGLONG 12
|
| 46 |
+
#define _CFFI_PRIM_FLOAT 13
|
| 47 |
+
#define _CFFI_PRIM_DOUBLE 14
|
| 48 |
+
#define _CFFI_PRIM_LONGDOUBLE 15
|
| 49 |
+
|
| 50 |
+
#define _CFFI_PRIM_WCHAR 16
|
| 51 |
+
#define _CFFI_PRIM_INT8 17
|
| 52 |
+
#define _CFFI_PRIM_UINT8 18
|
| 53 |
+
#define _CFFI_PRIM_INT16 19
|
| 54 |
+
#define _CFFI_PRIM_UINT16 20
|
| 55 |
+
#define _CFFI_PRIM_INT32 21
|
| 56 |
+
#define _CFFI_PRIM_UINT32 22
|
| 57 |
+
#define _CFFI_PRIM_INT64 23
|
| 58 |
+
#define _CFFI_PRIM_UINT64 24
|
| 59 |
+
#define _CFFI_PRIM_INTPTR 25
|
| 60 |
+
#define _CFFI_PRIM_UINTPTR 26
|
| 61 |
+
#define _CFFI_PRIM_PTRDIFF 27
|
| 62 |
+
#define _CFFI_PRIM_SIZE 28
|
| 63 |
+
#define _CFFI_PRIM_SSIZE 29
|
| 64 |
+
#define _CFFI_PRIM_INT_LEAST8 30
|
| 65 |
+
#define _CFFI_PRIM_UINT_LEAST8 31
|
| 66 |
+
#define _CFFI_PRIM_INT_LEAST16 32
|
| 67 |
+
#define _CFFI_PRIM_UINT_LEAST16 33
|
| 68 |
+
#define _CFFI_PRIM_INT_LEAST32 34
|
| 69 |
+
#define _CFFI_PRIM_UINT_LEAST32 35
|
| 70 |
+
#define _CFFI_PRIM_INT_LEAST64 36
|
| 71 |
+
#define _CFFI_PRIM_UINT_LEAST64 37
|
| 72 |
+
#define _CFFI_PRIM_INT_FAST8 38
|
| 73 |
+
#define _CFFI_PRIM_UINT_FAST8 39
|
| 74 |
+
#define _CFFI_PRIM_INT_FAST16 40
|
| 75 |
+
#define _CFFI_PRIM_UINT_FAST16 41
|
| 76 |
+
#define _CFFI_PRIM_INT_FAST32 42
|
| 77 |
+
#define _CFFI_PRIM_UINT_FAST32 43
|
| 78 |
+
#define _CFFI_PRIM_INT_FAST64 44
|
| 79 |
+
#define _CFFI_PRIM_UINT_FAST64 45
|
| 80 |
+
#define _CFFI_PRIM_INTMAX 46
|
| 81 |
+
#define _CFFI_PRIM_UINTMAX 47
|
| 82 |
+
#define _CFFI_PRIM_FLOATCOMPLEX 48
|
| 83 |
+
#define _CFFI_PRIM_DOUBLECOMPLEX 49
|
| 84 |
+
#define _CFFI_PRIM_CHAR16 50
|
| 85 |
+
#define _CFFI_PRIM_CHAR32 51
|
| 86 |
+
|
| 87 |
+
#define _CFFI__NUM_PRIM 52
|
| 88 |
+
#define _CFFI__UNKNOWN_PRIM (-1)
|
| 89 |
+
#define _CFFI__UNKNOWN_FLOAT_PRIM (-2)
|
| 90 |
+
#define _CFFI__UNKNOWN_LONG_DOUBLE (-3)
|
| 91 |
+
|
| 92 |
+
#define _CFFI__IO_FILE_STRUCT (-1)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
struct _cffi_global_s {
|
| 96 |
+
const char *name;
|
| 97 |
+
void *address;
|
| 98 |
+
_cffi_opcode_t type_op;
|
| 99 |
+
void *size_or_direct_fn; // OP_GLOBAL_VAR: size, or 0 if unknown
|
| 100 |
+
// OP_CPYTHON_BLTN_*: addr of direct function
|
| 101 |
+
};
|
| 102 |
+
|
| 103 |
+
struct _cffi_getconst_s {
|
| 104 |
+
unsigned long long value;
|
| 105 |
+
const struct _cffi_type_context_s *ctx;
|
| 106 |
+
int gindex;
|
| 107 |
+
};
|
| 108 |
+
|
| 109 |
+
struct _cffi_struct_union_s {
|
| 110 |
+
const char *name;
|
| 111 |
+
int type_index; // -> _cffi_types, on a OP_STRUCT_UNION
|
| 112 |
+
int flags; // _CFFI_F_* flags below
|
| 113 |
+
size_t size;
|
| 114 |
+
int alignment;
|
| 115 |
+
int first_field_index; // -> _cffi_fields array
|
| 116 |
+
int num_fields;
|
| 117 |
+
};
|
| 118 |
+
#define _CFFI_F_UNION 0x01 // is a union, not a struct
|
| 119 |
+
#define _CFFI_F_CHECK_FIELDS 0x02 // complain if fields are not in the
|
| 120 |
+
// "standard layout" or if some are missing
|
| 121 |
+
#define _CFFI_F_PACKED 0x04 // for CHECK_FIELDS, assume a packed struct
|
| 122 |
+
#define _CFFI_F_EXTERNAL 0x08 // in some other ffi.include()
|
| 123 |
+
#define _CFFI_F_OPAQUE 0x10 // opaque
|
| 124 |
+
|
| 125 |
+
struct _cffi_field_s {
|
| 126 |
+
const char *name;
|
| 127 |
+
size_t field_offset;
|
| 128 |
+
size_t field_size;
|
| 129 |
+
_cffi_opcode_t field_type_op;
|
| 130 |
+
};
|
| 131 |
+
|
| 132 |
+
struct _cffi_enum_s {
|
| 133 |
+
const char *name;
|
| 134 |
+
int type_index; // -> _cffi_types, on a OP_ENUM
|
| 135 |
+
int type_prim; // _CFFI_PRIM_xxx
|
| 136 |
+
const char *enumerators; // comma-delimited string
|
| 137 |
+
};
|
| 138 |
+
|
| 139 |
+
struct _cffi_typename_s {
|
| 140 |
+
const char *name;
|
| 141 |
+
int type_index; /* if opaque, points to a possibly artificial
|
| 142 |
+
OP_STRUCT which is itself opaque */
|
| 143 |
+
};
|
| 144 |
+
|
| 145 |
+
struct _cffi_type_context_s {
|
| 146 |
+
_cffi_opcode_t *types;
|
| 147 |
+
const struct _cffi_global_s *globals;
|
| 148 |
+
const struct _cffi_field_s *fields;
|
| 149 |
+
const struct _cffi_struct_union_s *struct_unions;
|
| 150 |
+
const struct _cffi_enum_s *enums;
|
| 151 |
+
const struct _cffi_typename_s *typenames;
|
| 152 |
+
int num_globals;
|
| 153 |
+
int num_struct_unions;
|
| 154 |
+
int num_enums;
|
| 155 |
+
int num_typenames;
|
| 156 |
+
const char *const *includes;
|
| 157 |
+
int num_types;
|
| 158 |
+
int flags; /* future extension */
|
| 159 |
+
};
|
| 160 |
+
|
| 161 |
+
struct _cffi_parse_info_s {
|
| 162 |
+
const struct _cffi_type_context_s *ctx;
|
| 163 |
+
_cffi_opcode_t *output;
|
| 164 |
+
unsigned int output_size;
|
| 165 |
+
size_t error_location;
|
| 166 |
+
const char *error_message;
|
| 167 |
+
};
|
| 168 |
+
|
| 169 |
+
struct _cffi_externpy_s {
|
| 170 |
+
const char *name;
|
| 171 |
+
size_t size_of_result;
|
| 172 |
+
void *reserved1, *reserved2;
|
| 173 |
+
};
|
| 174 |
+
|
| 175 |
+
#ifdef _CFFI_INTERNAL
|
| 176 |
+
static int parse_c_type(struct _cffi_parse_info_s *info, const char *input);
|
| 177 |
+
static int search_in_globals(const struct _cffi_type_context_s *ctx,
|
| 178 |
+
const char *search, size_t search_len);
|
| 179 |
+
static int search_in_struct_unions(const struct _cffi_type_context_s *ctx,
|
| 180 |
+
const char *search, size_t search_len);
|
| 181 |
+
#endif
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/pkgconfig.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pkg-config, https://www.freedesktop.org/wiki/Software/pkg-config/ integration for cffi
|
| 2 |
+
import sys, os, subprocess
|
| 3 |
+
|
| 4 |
+
from .error import PkgConfigError
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def merge_flags(cfg1, cfg2):
|
| 8 |
+
"""Merge values from cffi config flags cfg2 to cf1
|
| 9 |
+
|
| 10 |
+
Example:
|
| 11 |
+
merge_flags({"libraries": ["one"]}, {"libraries": ["two"]})
|
| 12 |
+
{"libraries": ["one", "two"]}
|
| 13 |
+
"""
|
| 14 |
+
for key, value in cfg2.items():
|
| 15 |
+
if key not in cfg1:
|
| 16 |
+
cfg1[key] = value
|
| 17 |
+
else:
|
| 18 |
+
if not isinstance(cfg1[key], list):
|
| 19 |
+
raise TypeError("cfg1[%r] should be a list of strings" % (key,))
|
| 20 |
+
if not isinstance(value, list):
|
| 21 |
+
raise TypeError("cfg2[%r] should be a list of strings" % (key,))
|
| 22 |
+
cfg1[key].extend(value)
|
| 23 |
+
return cfg1
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def call(libname, flag, encoding=sys.getfilesystemencoding()):
|
| 27 |
+
"""Calls pkg-config and returns the output if found
|
| 28 |
+
"""
|
| 29 |
+
a = ["pkg-config", "--print-errors"]
|
| 30 |
+
a.append(flag)
|
| 31 |
+
a.append(libname)
|
| 32 |
+
try:
|
| 33 |
+
pc = subprocess.Popen(a, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 34 |
+
except EnvironmentError as e:
|
| 35 |
+
raise PkgConfigError("cannot run pkg-config: %s" % (str(e).strip(),))
|
| 36 |
+
|
| 37 |
+
bout, berr = pc.communicate()
|
| 38 |
+
if pc.returncode != 0:
|
| 39 |
+
try:
|
| 40 |
+
berr = berr.decode(encoding)
|
| 41 |
+
except Exception:
|
| 42 |
+
pass
|
| 43 |
+
raise PkgConfigError(berr.strip())
|
| 44 |
+
|
| 45 |
+
if sys.version_info >= (3,) and not isinstance(bout, str): # Python 3.x
|
| 46 |
+
try:
|
| 47 |
+
bout = bout.decode(encoding)
|
| 48 |
+
except UnicodeDecodeError:
|
| 49 |
+
raise PkgConfigError("pkg-config %s %s returned bytes that cannot "
|
| 50 |
+
"be decoded with encoding %r:\n%r" %
|
| 51 |
+
(flag, libname, encoding, bout))
|
| 52 |
+
|
| 53 |
+
if os.altsep != '\\' and '\\' in bout:
|
| 54 |
+
raise PkgConfigError("pkg-config %s %s returned an unsupported "
|
| 55 |
+
"backslash-escaped output:\n%r" %
|
| 56 |
+
(flag, libname, bout))
|
| 57 |
+
return bout
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def flags_from_pkgconfig(libs):
|
| 61 |
+
r"""Return compiler line flags for FFI.set_source based on pkg-config output
|
| 62 |
+
|
| 63 |
+
Usage
|
| 64 |
+
...
|
| 65 |
+
ffibuilder.set_source("_foo", pkgconfig = ["libfoo", "libbar >= 1.8.3"])
|
| 66 |
+
|
| 67 |
+
If pkg-config is installed on build machine, then arguments include_dirs,
|
| 68 |
+
library_dirs, libraries, define_macros, extra_compile_args and
|
| 69 |
+
extra_link_args are extended with an output of pkg-config for libfoo and
|
| 70 |
+
libbar.
|
| 71 |
+
|
| 72 |
+
Raises PkgConfigError in case the pkg-config call fails.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
def get_include_dirs(string):
|
| 76 |
+
return [x[2:] for x in string.split() if x.startswith("-I")]
|
| 77 |
+
|
| 78 |
+
def get_library_dirs(string):
|
| 79 |
+
return [x[2:] for x in string.split() if x.startswith("-L")]
|
| 80 |
+
|
| 81 |
+
def get_libraries(string):
|
| 82 |
+
return [x[2:] for x in string.split() if x.startswith("-l")]
|
| 83 |
+
|
| 84 |
+
# convert -Dfoo=bar to list of tuples [("foo", "bar")] expected by distutils
|
| 85 |
+
def get_macros(string):
|
| 86 |
+
def _macro(x):
|
| 87 |
+
x = x[2:] # drop "-D"
|
| 88 |
+
if '=' in x:
|
| 89 |
+
return tuple(x.split("=", 1)) # "-Dfoo=bar" => ("foo", "bar")
|
| 90 |
+
else:
|
| 91 |
+
return (x, None) # "-Dfoo" => ("foo", None)
|
| 92 |
+
return [_macro(x) for x in string.split() if x.startswith("-D")]
|
| 93 |
+
|
| 94 |
+
def get_other_cflags(string):
|
| 95 |
+
return [x for x in string.split() if not x.startswith("-I") and
|
| 96 |
+
not x.startswith("-D")]
|
| 97 |
+
|
| 98 |
+
def get_other_libs(string):
|
| 99 |
+
return [x for x in string.split() if not x.startswith("-L") and
|
| 100 |
+
not x.startswith("-l")]
|
| 101 |
+
|
| 102 |
+
# return kwargs for given libname
|
| 103 |
+
def kwargs(libname):
|
| 104 |
+
fse = sys.getfilesystemencoding()
|
| 105 |
+
all_cflags = call(libname, "--cflags")
|
| 106 |
+
all_libs = call(libname, "--libs")
|
| 107 |
+
return {
|
| 108 |
+
"include_dirs": get_include_dirs(all_cflags),
|
| 109 |
+
"library_dirs": get_library_dirs(all_libs),
|
| 110 |
+
"libraries": get_libraries(all_libs),
|
| 111 |
+
"define_macros": get_macros(all_cflags),
|
| 112 |
+
"extra_compile_args": get_other_cflags(all_cflags),
|
| 113 |
+
"extra_link_args": get_other_libs(all_libs),
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
# merge all arguments together
|
| 117 |
+
ret = {}
|
| 118 |
+
for libname in libs:
|
| 119 |
+
lib_flags = kwargs(libname)
|
| 120 |
+
merge_flags(ret, lib_flags)
|
| 121 |
+
return ret
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/recompiler.py
ADDED
|
@@ -0,0 +1,1542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, sys, io
|
| 2 |
+
from . import ffiplatform, model
|
| 3 |
+
from .error import VerificationError
|
| 4 |
+
from .cffi_opcode import *
|
| 5 |
+
|
| 6 |
+
VERSION_BASE = 0x2601
|
| 7 |
+
VERSION_EMBEDDED = 0x2701
|
| 8 |
+
VERSION_CHAR16CHAR32 = 0x2801
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class GlobalExpr:
|
| 12 |
+
def __init__(self, name, address, type_op, size=0, check_value=0):
|
| 13 |
+
self.name = name
|
| 14 |
+
self.address = address
|
| 15 |
+
self.type_op = type_op
|
| 16 |
+
self.size = size
|
| 17 |
+
self.check_value = check_value
|
| 18 |
+
|
| 19 |
+
def as_c_expr(self):
|
| 20 |
+
return ' { "%s", (void *)%s, %s, (void *)%s },' % (
|
| 21 |
+
self.name, self.address, self.type_op.as_c_expr(), self.size)
|
| 22 |
+
|
| 23 |
+
def as_python_expr(self):
|
| 24 |
+
return "b'%s%s',%d" % (self.type_op.as_python_bytes(), self.name,
|
| 25 |
+
self.check_value)
|
| 26 |
+
|
| 27 |
+
class FieldExpr:
|
| 28 |
+
def __init__(self, name, field_offset, field_size, fbitsize, field_type_op):
|
| 29 |
+
self.name = name
|
| 30 |
+
self.field_offset = field_offset
|
| 31 |
+
self.field_size = field_size
|
| 32 |
+
self.fbitsize = fbitsize
|
| 33 |
+
self.field_type_op = field_type_op
|
| 34 |
+
|
| 35 |
+
def as_c_expr(self):
|
| 36 |
+
spaces = " " * len(self.name)
|
| 37 |
+
return (' { "%s", %s,\n' % (self.name, self.field_offset) +
|
| 38 |
+
' %s %s,\n' % (spaces, self.field_size) +
|
| 39 |
+
' %s %s },' % (spaces, self.field_type_op.as_c_expr()))
|
| 40 |
+
|
| 41 |
+
def as_python_expr(self):
|
| 42 |
+
raise NotImplementedError
|
| 43 |
+
|
| 44 |
+
def as_field_python_expr(self):
|
| 45 |
+
if self.field_type_op.op == OP_NOOP:
|
| 46 |
+
size_expr = ''
|
| 47 |
+
elif self.field_type_op.op == OP_BITFIELD:
|
| 48 |
+
size_expr = format_four_bytes(self.fbitsize)
|
| 49 |
+
else:
|
| 50 |
+
raise NotImplementedError
|
| 51 |
+
return "b'%s%s%s'" % (self.field_type_op.as_python_bytes(),
|
| 52 |
+
size_expr,
|
| 53 |
+
self.name)
|
| 54 |
+
|
| 55 |
+
class StructUnionExpr:
|
| 56 |
+
def __init__(self, name, type_index, flags, size, alignment, comment,
|
| 57 |
+
first_field_index, c_fields):
|
| 58 |
+
self.name = name
|
| 59 |
+
self.type_index = type_index
|
| 60 |
+
self.flags = flags
|
| 61 |
+
self.size = size
|
| 62 |
+
self.alignment = alignment
|
| 63 |
+
self.comment = comment
|
| 64 |
+
self.first_field_index = first_field_index
|
| 65 |
+
self.c_fields = c_fields
|
| 66 |
+
|
| 67 |
+
def as_c_expr(self):
|
| 68 |
+
return (' { "%s", %d, %s,' % (self.name, self.type_index, self.flags)
|
| 69 |
+
+ '\n %s, %s, ' % (self.size, self.alignment)
|
| 70 |
+
+ '%d, %d ' % (self.first_field_index, len(self.c_fields))
|
| 71 |
+
+ ('/* %s */ ' % self.comment if self.comment else '')
|
| 72 |
+
+ '},')
|
| 73 |
+
|
| 74 |
+
def as_python_expr(self):
|
| 75 |
+
flags = eval(self.flags, G_FLAGS)
|
| 76 |
+
fields_expr = [c_field.as_field_python_expr()
|
| 77 |
+
for c_field in self.c_fields]
|
| 78 |
+
return "(b'%s%s%s',%s)" % (
|
| 79 |
+
format_four_bytes(self.type_index),
|
| 80 |
+
format_four_bytes(flags),
|
| 81 |
+
self.name,
|
| 82 |
+
','.join(fields_expr))
|
| 83 |
+
|
| 84 |
+
class EnumExpr:
|
| 85 |
+
def __init__(self, name, type_index, size, signed, allenums):
|
| 86 |
+
self.name = name
|
| 87 |
+
self.type_index = type_index
|
| 88 |
+
self.size = size
|
| 89 |
+
self.signed = signed
|
| 90 |
+
self.allenums = allenums
|
| 91 |
+
|
| 92 |
+
def as_c_expr(self):
|
| 93 |
+
return (' { "%s", %d, _cffi_prim_int(%s, %s),\n'
|
| 94 |
+
' "%s" },' % (self.name, self.type_index,
|
| 95 |
+
self.size, self.signed, self.allenums))
|
| 96 |
+
|
| 97 |
+
def as_python_expr(self):
|
| 98 |
+
prim_index = {
|
| 99 |
+
(1, 0): PRIM_UINT8, (1, 1): PRIM_INT8,
|
| 100 |
+
(2, 0): PRIM_UINT16, (2, 1): PRIM_INT16,
|
| 101 |
+
(4, 0): PRIM_UINT32, (4, 1): PRIM_INT32,
|
| 102 |
+
(8, 0): PRIM_UINT64, (8, 1): PRIM_INT64,
|
| 103 |
+
}[self.size, self.signed]
|
| 104 |
+
return "b'%s%s%s\\x00%s'" % (format_four_bytes(self.type_index),
|
| 105 |
+
format_four_bytes(prim_index),
|
| 106 |
+
self.name, self.allenums)
|
| 107 |
+
|
| 108 |
+
class TypenameExpr:
|
| 109 |
+
def __init__(self, name, type_index):
|
| 110 |
+
self.name = name
|
| 111 |
+
self.type_index = type_index
|
| 112 |
+
|
| 113 |
+
def as_c_expr(self):
|
| 114 |
+
return ' { "%s", %d },' % (self.name, self.type_index)
|
| 115 |
+
|
| 116 |
+
def as_python_expr(self):
|
| 117 |
+
return "b'%s%s'" % (format_four_bytes(self.type_index), self.name)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# ____________________________________________________________
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class Recompiler:
|
| 124 |
+
_num_externpy = 0
|
| 125 |
+
|
| 126 |
+
def __init__(self, ffi, module_name, target_is_python=False):
|
| 127 |
+
self.ffi = ffi
|
| 128 |
+
self.module_name = module_name
|
| 129 |
+
self.target_is_python = target_is_python
|
| 130 |
+
self._version = VERSION_BASE
|
| 131 |
+
|
| 132 |
+
def needs_version(self, ver):
|
| 133 |
+
self._version = max(self._version, ver)
|
| 134 |
+
|
| 135 |
+
def collect_type_table(self):
|
| 136 |
+
self._typesdict = {}
|
| 137 |
+
self._generate("collecttype")
|
| 138 |
+
#
|
| 139 |
+
all_decls = sorted(self._typesdict, key=str)
|
| 140 |
+
#
|
| 141 |
+
# prepare all FUNCTION bytecode sequences first
|
| 142 |
+
self.cffi_types = []
|
| 143 |
+
for tp in all_decls:
|
| 144 |
+
if tp.is_raw_function:
|
| 145 |
+
assert self._typesdict[tp] is None
|
| 146 |
+
self._typesdict[tp] = len(self.cffi_types)
|
| 147 |
+
self.cffi_types.append(tp) # placeholder
|
| 148 |
+
for tp1 in tp.args:
|
| 149 |
+
assert isinstance(tp1, (model.VoidType,
|
| 150 |
+
model.BasePrimitiveType,
|
| 151 |
+
model.PointerType,
|
| 152 |
+
model.StructOrUnionOrEnum,
|
| 153 |
+
model.FunctionPtrType))
|
| 154 |
+
if self._typesdict[tp1] is None:
|
| 155 |
+
self._typesdict[tp1] = len(self.cffi_types)
|
| 156 |
+
self.cffi_types.append(tp1) # placeholder
|
| 157 |
+
self.cffi_types.append('END') # placeholder
|
| 158 |
+
#
|
| 159 |
+
# prepare all OTHER bytecode sequences
|
| 160 |
+
for tp in all_decls:
|
| 161 |
+
if not tp.is_raw_function and self._typesdict[tp] is None:
|
| 162 |
+
self._typesdict[tp] = len(self.cffi_types)
|
| 163 |
+
self.cffi_types.append(tp) # placeholder
|
| 164 |
+
if tp.is_array_type and tp.length is not None:
|
| 165 |
+
self.cffi_types.append('LEN') # placeholder
|
| 166 |
+
assert None not in self._typesdict.values()
|
| 167 |
+
#
|
| 168 |
+
# collect all structs and unions and enums
|
| 169 |
+
self._struct_unions = {}
|
| 170 |
+
self._enums = {}
|
| 171 |
+
for tp in all_decls:
|
| 172 |
+
if isinstance(tp, model.StructOrUnion):
|
| 173 |
+
self._struct_unions[tp] = None
|
| 174 |
+
elif isinstance(tp, model.EnumType):
|
| 175 |
+
self._enums[tp] = None
|
| 176 |
+
for i, tp in enumerate(sorted(self._struct_unions,
|
| 177 |
+
key=lambda tp: tp.name)):
|
| 178 |
+
self._struct_unions[tp] = i
|
| 179 |
+
for i, tp in enumerate(sorted(self._enums,
|
| 180 |
+
key=lambda tp: tp.name)):
|
| 181 |
+
self._enums[tp] = i
|
| 182 |
+
#
|
| 183 |
+
# emit all bytecode sequences now
|
| 184 |
+
for tp in all_decls:
|
| 185 |
+
method = getattr(self, '_emit_bytecode_' + tp.__class__.__name__)
|
| 186 |
+
method(tp, self._typesdict[tp])
|
| 187 |
+
#
|
| 188 |
+
# consistency check
|
| 189 |
+
for op in self.cffi_types:
|
| 190 |
+
assert isinstance(op, CffiOp)
|
| 191 |
+
self.cffi_types = tuple(self.cffi_types) # don't change any more
|
| 192 |
+
|
| 193 |
+
def _do_collect_type(self, tp):
|
| 194 |
+
if not isinstance(tp, model.BaseTypeByIdentity):
|
| 195 |
+
if isinstance(tp, tuple):
|
| 196 |
+
for x in tp:
|
| 197 |
+
self._do_collect_type(x)
|
| 198 |
+
return
|
| 199 |
+
if tp not in self._typesdict:
|
| 200 |
+
self._typesdict[tp] = None
|
| 201 |
+
if isinstance(tp, model.FunctionPtrType):
|
| 202 |
+
self._do_collect_type(tp.as_raw_function())
|
| 203 |
+
elif isinstance(tp, model.StructOrUnion):
|
| 204 |
+
if tp.fldtypes is not None and (
|
| 205 |
+
tp not in self.ffi._parser._included_declarations):
|
| 206 |
+
for name1, tp1, _, _ in tp.enumfields():
|
| 207 |
+
self._do_collect_type(self._field_type(tp, name1, tp1))
|
| 208 |
+
else:
|
| 209 |
+
for _, x in tp._get_items():
|
| 210 |
+
self._do_collect_type(x)
|
| 211 |
+
|
| 212 |
+
def _generate(self, step_name):
|
| 213 |
+
lst = self.ffi._parser._declarations.items()
|
| 214 |
+
for name, (tp, quals) in sorted(lst):
|
| 215 |
+
kind, realname = name.split(' ', 1)
|
| 216 |
+
try:
|
| 217 |
+
method = getattr(self, '_generate_cpy_%s_%s' % (kind,
|
| 218 |
+
step_name))
|
| 219 |
+
except AttributeError:
|
| 220 |
+
raise VerificationError(
|
| 221 |
+
"not implemented in recompile(): %r" % name)
|
| 222 |
+
try:
|
| 223 |
+
self._current_quals = quals
|
| 224 |
+
method(tp, realname)
|
| 225 |
+
except Exception as e:
|
| 226 |
+
model.attach_exception_info(e, name)
|
| 227 |
+
raise
|
| 228 |
+
|
| 229 |
+
# ----------
|
| 230 |
+
|
| 231 |
+
ALL_STEPS = ["global", "field", "struct_union", "enum", "typename"]
|
| 232 |
+
|
| 233 |
+
def collect_step_tables(self):
|
| 234 |
+
# collect the declarations for '_cffi_globals', '_cffi_typenames', etc.
|
| 235 |
+
self._lsts = {}
|
| 236 |
+
for step_name in self.ALL_STEPS:
|
| 237 |
+
self._lsts[step_name] = []
|
| 238 |
+
self._seen_struct_unions = set()
|
| 239 |
+
self._generate("ctx")
|
| 240 |
+
self._add_missing_struct_unions()
|
| 241 |
+
#
|
| 242 |
+
for step_name in self.ALL_STEPS:
|
| 243 |
+
lst = self._lsts[step_name]
|
| 244 |
+
if step_name != "field":
|
| 245 |
+
lst.sort(key=lambda entry: entry.name)
|
| 246 |
+
self._lsts[step_name] = tuple(lst) # don't change any more
|
| 247 |
+
#
|
| 248 |
+
# check for a possible internal inconsistency: _cffi_struct_unions
|
| 249 |
+
# should have been generated with exactly self._struct_unions
|
| 250 |
+
lst = self._lsts["struct_union"]
|
| 251 |
+
for tp, i in self._struct_unions.items():
|
| 252 |
+
assert i < len(lst)
|
| 253 |
+
assert lst[i].name == tp.name
|
| 254 |
+
assert len(lst) == len(self._struct_unions)
|
| 255 |
+
# same with enums
|
| 256 |
+
lst = self._lsts["enum"]
|
| 257 |
+
for tp, i in self._enums.items():
|
| 258 |
+
assert i < len(lst)
|
| 259 |
+
assert lst[i].name == tp.name
|
| 260 |
+
assert len(lst) == len(self._enums)
|
| 261 |
+
|
| 262 |
+
# ----------
|
| 263 |
+
|
| 264 |
+
def _prnt(self, what=''):
|
| 265 |
+
self._f.write(what + '\n')
|
| 266 |
+
|
| 267 |
+
def write_source_to_f(self, f, preamble):
|
| 268 |
+
if self.target_is_python:
|
| 269 |
+
assert preamble is None
|
| 270 |
+
self.write_py_source_to_f(f)
|
| 271 |
+
else:
|
| 272 |
+
assert preamble is not None
|
| 273 |
+
self.write_c_source_to_f(f, preamble)
|
| 274 |
+
|
| 275 |
+
def _rel_readlines(self, filename):
|
| 276 |
+
g = open(os.path.join(os.path.dirname(__file__), filename), 'r')
|
| 277 |
+
lines = g.readlines()
|
| 278 |
+
g.close()
|
| 279 |
+
return lines
|
| 280 |
+
|
| 281 |
+
def write_c_source_to_f(self, f, preamble):
|
| 282 |
+
self._f = f
|
| 283 |
+
prnt = self._prnt
|
| 284 |
+
if self.ffi._embedding is not None:
|
| 285 |
+
prnt('#define _CFFI_USE_EMBEDDING')
|
| 286 |
+
#
|
| 287 |
+
# first the '#include' (actually done by inlining the file's content)
|
| 288 |
+
lines = self._rel_readlines('_cffi_include.h')
|
| 289 |
+
i = lines.index('#include "parse_c_type.h"\n')
|
| 290 |
+
lines[i:i+1] = self._rel_readlines('parse_c_type.h')
|
| 291 |
+
prnt(''.join(lines))
|
| 292 |
+
#
|
| 293 |
+
# if we have ffi._embedding != None, we give it here as a macro
|
| 294 |
+
# and include an extra file
|
| 295 |
+
base_module_name = self.module_name.split('.')[-1]
|
| 296 |
+
if self.ffi._embedding is not None:
|
| 297 |
+
prnt('#define _CFFI_MODULE_NAME "%s"' % (self.module_name,))
|
| 298 |
+
prnt('static const char _CFFI_PYTHON_STARTUP_CODE[] = {')
|
| 299 |
+
self._print_string_literal_in_array(self.ffi._embedding)
|
| 300 |
+
prnt('0 };')
|
| 301 |
+
prnt('#ifdef PYPY_VERSION')
|
| 302 |
+
prnt('# define _CFFI_PYTHON_STARTUP_FUNC _cffi_pypyinit_%s' % (
|
| 303 |
+
base_module_name,))
|
| 304 |
+
prnt('#elif PY_MAJOR_VERSION >= 3')
|
| 305 |
+
prnt('# define _CFFI_PYTHON_STARTUP_FUNC PyInit_%s' % (
|
| 306 |
+
base_module_name,))
|
| 307 |
+
prnt('#else')
|
| 308 |
+
prnt('# define _CFFI_PYTHON_STARTUP_FUNC init%s' % (
|
| 309 |
+
base_module_name,))
|
| 310 |
+
prnt('#endif')
|
| 311 |
+
lines = self._rel_readlines('_embedding.h')
|
| 312 |
+
i = lines.index('#include "_cffi_errors.h"\n')
|
| 313 |
+
lines[i:i+1] = self._rel_readlines('_cffi_errors.h')
|
| 314 |
+
prnt(''.join(lines))
|
| 315 |
+
self.needs_version(VERSION_EMBEDDED)
|
| 316 |
+
#
|
| 317 |
+
# then paste the C source given by the user, verbatim.
|
| 318 |
+
prnt('/************************************************************/')
|
| 319 |
+
prnt()
|
| 320 |
+
prnt(preamble)
|
| 321 |
+
prnt()
|
| 322 |
+
prnt('/************************************************************/')
|
| 323 |
+
prnt()
|
| 324 |
+
#
|
| 325 |
+
# the declaration of '_cffi_types'
|
| 326 |
+
prnt('static void *_cffi_types[] = {')
|
| 327 |
+
typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()])
|
| 328 |
+
for i, op in enumerate(self.cffi_types):
|
| 329 |
+
comment = ''
|
| 330 |
+
if i in typeindex2type:
|
| 331 |
+
comment = ' // ' + typeindex2type[i]._get_c_name()
|
| 332 |
+
prnt('/* %2d */ %s,%s' % (i, op.as_c_expr(), comment))
|
| 333 |
+
if not self.cffi_types:
|
| 334 |
+
prnt(' 0')
|
| 335 |
+
prnt('};')
|
| 336 |
+
prnt()
|
| 337 |
+
#
|
| 338 |
+
# call generate_cpy_xxx_decl(), for every xxx found from
|
| 339 |
+
# ffi._parser._declarations. This generates all the functions.
|
| 340 |
+
self._seen_constants = set()
|
| 341 |
+
self._generate("decl")
|
| 342 |
+
#
|
| 343 |
+
# the declaration of '_cffi_globals' and '_cffi_typenames'
|
| 344 |
+
nums = {}
|
| 345 |
+
for step_name in self.ALL_STEPS:
|
| 346 |
+
lst = self._lsts[step_name]
|
| 347 |
+
nums[step_name] = len(lst)
|
| 348 |
+
if nums[step_name] > 0:
|
| 349 |
+
prnt('static const struct _cffi_%s_s _cffi_%ss[] = {' % (
|
| 350 |
+
step_name, step_name))
|
| 351 |
+
for entry in lst:
|
| 352 |
+
prnt(entry.as_c_expr())
|
| 353 |
+
prnt('};')
|
| 354 |
+
prnt()
|
| 355 |
+
#
|
| 356 |
+
# the declaration of '_cffi_includes'
|
| 357 |
+
if self.ffi._included_ffis:
|
| 358 |
+
prnt('static const char * const _cffi_includes[] = {')
|
| 359 |
+
for ffi_to_include in self.ffi._included_ffis:
|
| 360 |
+
try:
|
| 361 |
+
included_module_name, included_source = (
|
| 362 |
+
ffi_to_include._assigned_source[:2])
|
| 363 |
+
except AttributeError:
|
| 364 |
+
raise VerificationError(
|
| 365 |
+
"ffi object %r includes %r, but the latter has not "
|
| 366 |
+
"been prepared with set_source()" % (
|
| 367 |
+
self.ffi, ffi_to_include,))
|
| 368 |
+
if included_source is None:
|
| 369 |
+
raise VerificationError(
|
| 370 |
+
"not implemented yet: ffi.include() of a Python-based "
|
| 371 |
+
"ffi inside a C-based ffi")
|
| 372 |
+
prnt(' "%s",' % (included_module_name,))
|
| 373 |
+
prnt(' NULL')
|
| 374 |
+
prnt('};')
|
| 375 |
+
prnt()
|
| 376 |
+
#
|
| 377 |
+
# the declaration of '_cffi_type_context'
|
| 378 |
+
prnt('static const struct _cffi_type_context_s _cffi_type_context = {')
|
| 379 |
+
prnt(' _cffi_types,')
|
| 380 |
+
for step_name in self.ALL_STEPS:
|
| 381 |
+
if nums[step_name] > 0:
|
| 382 |
+
prnt(' _cffi_%ss,' % step_name)
|
| 383 |
+
else:
|
| 384 |
+
prnt(' NULL, /* no %ss */' % step_name)
|
| 385 |
+
for step_name in self.ALL_STEPS:
|
| 386 |
+
if step_name != "field":
|
| 387 |
+
prnt(' %d, /* num_%ss */' % (nums[step_name], step_name))
|
| 388 |
+
if self.ffi._included_ffis:
|
| 389 |
+
prnt(' _cffi_includes,')
|
| 390 |
+
else:
|
| 391 |
+
prnt(' NULL, /* no includes */')
|
| 392 |
+
prnt(' %d, /* num_types */' % (len(self.cffi_types),))
|
| 393 |
+
flags = 0
|
| 394 |
+
if self._num_externpy:
|
| 395 |
+
flags |= 1 # set to mean that we use extern "Python"
|
| 396 |
+
prnt(' %d, /* flags */' % flags)
|
| 397 |
+
prnt('};')
|
| 398 |
+
prnt()
|
| 399 |
+
#
|
| 400 |
+
# the init function
|
| 401 |
+
prnt('#ifdef __GNUC__')
|
| 402 |
+
prnt('# pragma GCC visibility push(default) /* for -fvisibility= */')
|
| 403 |
+
prnt('#endif')
|
| 404 |
+
prnt()
|
| 405 |
+
prnt('#ifdef PYPY_VERSION')
|
| 406 |
+
prnt('PyMODINIT_FUNC')
|
| 407 |
+
prnt('_cffi_pypyinit_%s(const void *p[])' % (base_module_name,))
|
| 408 |
+
prnt('{')
|
| 409 |
+
if self._num_externpy:
|
| 410 |
+
prnt(' if (((intptr_t)p[0]) >= 0x0A03) {')
|
| 411 |
+
prnt(' _cffi_call_python_org = '
|
| 412 |
+
'(void(*)(struct _cffi_externpy_s *, char *))p[1];')
|
| 413 |
+
prnt(' }')
|
| 414 |
+
prnt(' p[0] = (const void *)0x%x;' % self._version)
|
| 415 |
+
prnt(' p[1] = &_cffi_type_context;')
|
| 416 |
+
prnt('#if PY_MAJOR_VERSION >= 3')
|
| 417 |
+
prnt(' return NULL;')
|
| 418 |
+
prnt('#endif')
|
| 419 |
+
prnt('}')
|
| 420 |
+
# on Windows, distutils insists on putting init_cffi_xyz in
|
| 421 |
+
# 'export_symbols', so instead of fighting it, just give up and
|
| 422 |
+
# give it one
|
| 423 |
+
prnt('# ifdef _MSC_VER')
|
| 424 |
+
prnt(' PyMODINIT_FUNC')
|
| 425 |
+
prnt('# if PY_MAJOR_VERSION >= 3')
|
| 426 |
+
prnt(' PyInit_%s(void) { return NULL; }' % (base_module_name,))
|
| 427 |
+
prnt('# else')
|
| 428 |
+
prnt(' init%s(void) { }' % (base_module_name,))
|
| 429 |
+
prnt('# endif')
|
| 430 |
+
prnt('# endif')
|
| 431 |
+
prnt('#elif PY_MAJOR_VERSION >= 3')
|
| 432 |
+
prnt('PyMODINIT_FUNC')
|
| 433 |
+
prnt('PyInit_%s(void)' % (base_module_name,))
|
| 434 |
+
prnt('{')
|
| 435 |
+
prnt(' return _cffi_init("%s", 0x%x, &_cffi_type_context);' % (
|
| 436 |
+
self.module_name, self._version))
|
| 437 |
+
prnt('}')
|
| 438 |
+
prnt('#else')
|
| 439 |
+
prnt('PyMODINIT_FUNC')
|
| 440 |
+
prnt('init%s(void)' % (base_module_name,))
|
| 441 |
+
prnt('{')
|
| 442 |
+
prnt(' _cffi_init("%s", 0x%x, &_cffi_type_context);' % (
|
| 443 |
+
self.module_name, self._version))
|
| 444 |
+
prnt('}')
|
| 445 |
+
prnt('#endif')
|
| 446 |
+
prnt()
|
| 447 |
+
prnt('#ifdef __GNUC__')
|
| 448 |
+
prnt('# pragma GCC visibility pop')
|
| 449 |
+
prnt('#endif')
|
| 450 |
+
self._version = None
|
| 451 |
+
|
| 452 |
+
def _to_py(self, x):
|
| 453 |
+
if isinstance(x, str):
|
| 454 |
+
return "b'%s'" % (x,)
|
| 455 |
+
if isinstance(x, (list, tuple)):
|
| 456 |
+
rep = [self._to_py(item) for item in x]
|
| 457 |
+
if len(rep) == 1:
|
| 458 |
+
rep.append('')
|
| 459 |
+
return "(%s)" % (','.join(rep),)
|
| 460 |
+
return x.as_python_expr() # Py2: unicode unexpected; Py3: bytes unexp.
|
| 461 |
+
|
| 462 |
+
def write_py_source_to_f(self, f):
|
| 463 |
+
self._f = f
|
| 464 |
+
prnt = self._prnt
|
| 465 |
+
#
|
| 466 |
+
# header
|
| 467 |
+
prnt("# auto-generated file")
|
| 468 |
+
prnt("import _cffi_backend")
|
| 469 |
+
#
|
| 470 |
+
# the 'import' of the included ffis
|
| 471 |
+
num_includes = len(self.ffi._included_ffis or ())
|
| 472 |
+
for i in range(num_includes):
|
| 473 |
+
ffi_to_include = self.ffi._included_ffis[i]
|
| 474 |
+
try:
|
| 475 |
+
included_module_name, included_source = (
|
| 476 |
+
ffi_to_include._assigned_source[:2])
|
| 477 |
+
except AttributeError:
|
| 478 |
+
raise VerificationError(
|
| 479 |
+
"ffi object %r includes %r, but the latter has not "
|
| 480 |
+
"been prepared with set_source()" % (
|
| 481 |
+
self.ffi, ffi_to_include,))
|
| 482 |
+
if included_source is not None:
|
| 483 |
+
raise VerificationError(
|
| 484 |
+
"not implemented yet: ffi.include() of a C-based "
|
| 485 |
+
"ffi inside a Python-based ffi")
|
| 486 |
+
prnt('from %s import ffi as _ffi%d' % (included_module_name, i))
|
| 487 |
+
prnt()
|
| 488 |
+
prnt("ffi = _cffi_backend.FFI('%s'," % (self.module_name,))
|
| 489 |
+
prnt(" _version = 0x%x," % (self._version,))
|
| 490 |
+
self._version = None
|
| 491 |
+
#
|
| 492 |
+
# the '_types' keyword argument
|
| 493 |
+
self.cffi_types = tuple(self.cffi_types) # don't change any more
|
| 494 |
+
types_lst = [op.as_python_bytes() for op in self.cffi_types]
|
| 495 |
+
prnt(' _types = %s,' % (self._to_py(''.join(types_lst)),))
|
| 496 |
+
typeindex2type = dict([(i, tp) for (tp, i) in self._typesdict.items()])
|
| 497 |
+
#
|
| 498 |
+
# the keyword arguments from ALL_STEPS
|
| 499 |
+
for step_name in self.ALL_STEPS:
|
| 500 |
+
lst = self._lsts[step_name]
|
| 501 |
+
if len(lst) > 0 and step_name != "field":
|
| 502 |
+
prnt(' _%ss = %s,' % (step_name, self._to_py(lst)))
|
| 503 |
+
#
|
| 504 |
+
# the '_includes' keyword argument
|
| 505 |
+
if num_includes > 0:
|
| 506 |
+
prnt(' _includes = (%s,),' % (
|
| 507 |
+
', '.join(['_ffi%d' % i for i in range(num_includes)]),))
|
| 508 |
+
#
|
| 509 |
+
# the footer
|
| 510 |
+
prnt(')')
|
| 511 |
+
|
| 512 |
+
# ----------
|
| 513 |
+
|
| 514 |
+
def _gettypenum(self, type):
|
| 515 |
+
# a KeyError here is a bug. please report it! :-)
|
| 516 |
+
return self._typesdict[type]
|
| 517 |
+
|
| 518 |
+
def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode):
|
| 519 |
+
extraarg = ''
|
| 520 |
+
if isinstance(tp, model.BasePrimitiveType) and not tp.is_complex_type():
|
| 521 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
| 522 |
+
converter = '_cffi_to_c_int'
|
| 523 |
+
extraarg = ', %s' % tp.name
|
| 524 |
+
elif isinstance(tp, model.UnknownFloatType):
|
| 525 |
+
# don't check with is_float_type(): it may be a 'long
|
| 526 |
+
# double' here, and _cffi_to_c_double would loose precision
|
| 527 |
+
converter = '(%s)_cffi_to_c_double' % (tp.get_c_name(''),)
|
| 528 |
+
else:
|
| 529 |
+
cname = tp.get_c_name('')
|
| 530 |
+
converter = '(%s)_cffi_to_c_%s' % (cname,
|
| 531 |
+
tp.name.replace(' ', '_'))
|
| 532 |
+
if cname in ('char16_t', 'char32_t'):
|
| 533 |
+
self.needs_version(VERSION_CHAR16CHAR32)
|
| 534 |
+
errvalue = '-1'
|
| 535 |
+
#
|
| 536 |
+
elif isinstance(tp, model.PointerType):
|
| 537 |
+
self._convert_funcarg_to_c_ptr_or_array(tp, fromvar,
|
| 538 |
+
tovar, errcode)
|
| 539 |
+
return
|
| 540 |
+
#
|
| 541 |
+
elif (isinstance(tp, model.StructOrUnionOrEnum) or
|
| 542 |
+
isinstance(tp, model.BasePrimitiveType)):
|
| 543 |
+
# a struct (not a struct pointer) as a function argument;
|
| 544 |
+
# or, a complex (the same code works)
|
| 545 |
+
self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)'
|
| 546 |
+
% (tovar, self._gettypenum(tp), fromvar))
|
| 547 |
+
self._prnt(' %s;' % errcode)
|
| 548 |
+
return
|
| 549 |
+
#
|
| 550 |
+
elif isinstance(tp, model.FunctionPtrType):
|
| 551 |
+
converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('')
|
| 552 |
+
extraarg = ', _cffi_type(%d)' % self._gettypenum(tp)
|
| 553 |
+
errvalue = 'NULL'
|
| 554 |
+
#
|
| 555 |
+
else:
|
| 556 |
+
raise NotImplementedError(tp)
|
| 557 |
+
#
|
| 558 |
+
self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg))
|
| 559 |
+
self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % (
|
| 560 |
+
tovar, tp.get_c_name(''), errvalue))
|
| 561 |
+
self._prnt(' %s;' % errcode)
|
| 562 |
+
|
| 563 |
+
def _extra_local_variables(self, tp, localvars):
|
| 564 |
+
if isinstance(tp, model.PointerType):
|
| 565 |
+
localvars.add('Py_ssize_t datasize')
|
| 566 |
+
|
| 567 |
+
def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode):
|
| 568 |
+
self._prnt(' datasize = _cffi_prepare_pointer_call_argument(')
|
| 569 |
+
self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % (
|
| 570 |
+
self._gettypenum(tp), fromvar, tovar))
|
| 571 |
+
self._prnt(' if (datasize != 0) {')
|
| 572 |
+
self._prnt(' if (datasize < 0)')
|
| 573 |
+
self._prnt(' %s;' % errcode)
|
| 574 |
+
self._prnt(' %s = (%s)alloca((size_t)datasize);' % (
|
| 575 |
+
tovar, tp.get_c_name('')))
|
| 576 |
+
self._prnt(' memset((void *)%s, 0, (size_t)datasize);' % (tovar,))
|
| 577 |
+
self._prnt(' if (_cffi_convert_array_from_object('
|
| 578 |
+
'(char *)%s, _cffi_type(%d), %s) < 0)' % (
|
| 579 |
+
tovar, self._gettypenum(tp), fromvar))
|
| 580 |
+
self._prnt(' %s;' % errcode)
|
| 581 |
+
self._prnt(' }')
|
| 582 |
+
|
| 583 |
+
def _convert_expr_from_c(self, tp, var, context):
|
| 584 |
+
if isinstance(tp, model.BasePrimitiveType):
|
| 585 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
| 586 |
+
return '_cffi_from_c_int(%s, %s)' % (var, tp.name)
|
| 587 |
+
elif isinstance(tp, model.UnknownFloatType):
|
| 588 |
+
return '_cffi_from_c_double(%s)' % (var,)
|
| 589 |
+
elif tp.name != 'long double' and not tp.is_complex_type():
|
| 590 |
+
cname = tp.name.replace(' ', '_')
|
| 591 |
+
if cname in ('char16_t', 'char32_t'):
|
| 592 |
+
self.needs_version(VERSION_CHAR16CHAR32)
|
| 593 |
+
return '_cffi_from_c_%s(%s)' % (cname, var)
|
| 594 |
+
else:
|
| 595 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
| 596 |
+
var, self._gettypenum(tp))
|
| 597 |
+
elif isinstance(tp, (model.PointerType, model.FunctionPtrType)):
|
| 598 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
| 599 |
+
var, self._gettypenum(tp))
|
| 600 |
+
elif isinstance(tp, model.ArrayType):
|
| 601 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
| 602 |
+
var, self._gettypenum(model.PointerType(tp.item)))
|
| 603 |
+
elif isinstance(tp, model.StructOrUnion):
|
| 604 |
+
if tp.fldnames is None:
|
| 605 |
+
raise TypeError("'%s' is used as %s, but is opaque" % (
|
| 606 |
+
tp._get_c_name(), context))
|
| 607 |
+
return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % (
|
| 608 |
+
var, self._gettypenum(tp))
|
| 609 |
+
elif isinstance(tp, model.EnumType):
|
| 610 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
| 611 |
+
var, self._gettypenum(tp))
|
| 612 |
+
else:
|
| 613 |
+
raise NotImplementedError(tp)
|
| 614 |
+
|
| 615 |
+
# ----------
|
| 616 |
+
# typedefs
|
| 617 |
+
|
| 618 |
+
def _typedef_type(self, tp, name):
|
| 619 |
+
return self._global_type(tp, "(*(%s *)0)" % (name,))
|
| 620 |
+
|
| 621 |
+
def _generate_cpy_typedef_collecttype(self, tp, name):
|
| 622 |
+
self._do_collect_type(self._typedef_type(tp, name))
|
| 623 |
+
|
| 624 |
+
def _generate_cpy_typedef_decl(self, tp, name):
|
| 625 |
+
pass
|
| 626 |
+
|
| 627 |
+
def _typedef_ctx(self, tp, name):
|
| 628 |
+
type_index = self._typesdict[tp]
|
| 629 |
+
self._lsts["typename"].append(TypenameExpr(name, type_index))
|
| 630 |
+
|
| 631 |
+
def _generate_cpy_typedef_ctx(self, tp, name):
|
| 632 |
+
tp = self._typedef_type(tp, name)
|
| 633 |
+
self._typedef_ctx(tp, name)
|
| 634 |
+
if getattr(tp, "origin", None) == "unknown_type":
|
| 635 |
+
self._struct_ctx(tp, tp.name, approxname=None)
|
| 636 |
+
elif isinstance(tp, model.NamedPointerType):
|
| 637 |
+
self._struct_ctx(tp.totype, tp.totype.name, approxname=tp.name,
|
| 638 |
+
named_ptr=tp)
|
| 639 |
+
|
| 640 |
+
# ----------
|
| 641 |
+
# function declarations
|
| 642 |
+
|
| 643 |
+
def _generate_cpy_function_collecttype(self, tp, name):
|
| 644 |
+
self._do_collect_type(tp.as_raw_function())
|
| 645 |
+
if tp.ellipsis and not self.target_is_python:
|
| 646 |
+
self._do_collect_type(tp)
|
| 647 |
+
|
| 648 |
+
def _generate_cpy_function_decl(self, tp, name):
|
| 649 |
+
assert not self.target_is_python
|
| 650 |
+
assert isinstance(tp, model.FunctionPtrType)
|
| 651 |
+
if tp.ellipsis:
|
| 652 |
+
# cannot support vararg functions better than this: check for its
|
| 653 |
+
# exact type (including the fixed arguments), and build it as a
|
| 654 |
+
# constant function pointer (no CPython wrapper)
|
| 655 |
+
self._generate_cpy_constant_decl(tp, name)
|
| 656 |
+
return
|
| 657 |
+
prnt = self._prnt
|
| 658 |
+
numargs = len(tp.args)
|
| 659 |
+
if numargs == 0:
|
| 660 |
+
argname = 'noarg'
|
| 661 |
+
elif numargs == 1:
|
| 662 |
+
argname = 'arg0'
|
| 663 |
+
else:
|
| 664 |
+
argname = 'args'
|
| 665 |
+
#
|
| 666 |
+
# ------------------------------
|
| 667 |
+
# the 'd' version of the function, only for addressof(lib, 'func')
|
| 668 |
+
arguments = []
|
| 669 |
+
call_arguments = []
|
| 670 |
+
context = 'argument of %s' % name
|
| 671 |
+
for i, type in enumerate(tp.args):
|
| 672 |
+
arguments.append(type.get_c_name(' x%d' % i, context))
|
| 673 |
+
call_arguments.append('x%d' % i)
|
| 674 |
+
repr_arguments = ', '.join(arguments)
|
| 675 |
+
repr_arguments = repr_arguments or 'void'
|
| 676 |
+
if tp.abi:
|
| 677 |
+
abi = tp.abi + ' '
|
| 678 |
+
else:
|
| 679 |
+
abi = ''
|
| 680 |
+
name_and_arguments = '%s_cffi_d_%s(%s)' % (abi, name, repr_arguments)
|
| 681 |
+
prnt('static %s' % (tp.result.get_c_name(name_and_arguments),))
|
| 682 |
+
prnt('{')
|
| 683 |
+
call_arguments = ', '.join(call_arguments)
|
| 684 |
+
result_code = 'return '
|
| 685 |
+
if isinstance(tp.result, model.VoidType):
|
| 686 |
+
result_code = ''
|
| 687 |
+
prnt(' %s%s(%s);' % (result_code, name, call_arguments))
|
| 688 |
+
prnt('}')
|
| 689 |
+
#
|
| 690 |
+
prnt('#ifndef PYPY_VERSION') # ------------------------------
|
| 691 |
+
#
|
| 692 |
+
prnt('static PyObject *')
|
| 693 |
+
prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname))
|
| 694 |
+
prnt('{')
|
| 695 |
+
#
|
| 696 |
+
context = 'argument of %s' % name
|
| 697 |
+
for i, type in enumerate(tp.args):
|
| 698 |
+
arg = type.get_c_name(' x%d' % i, context)
|
| 699 |
+
prnt(' %s;' % arg)
|
| 700 |
+
#
|
| 701 |
+
localvars = set()
|
| 702 |
+
for type in tp.args:
|
| 703 |
+
self._extra_local_variables(type, localvars)
|
| 704 |
+
for decl in localvars:
|
| 705 |
+
prnt(' %s;' % (decl,))
|
| 706 |
+
#
|
| 707 |
+
if not isinstance(tp.result, model.VoidType):
|
| 708 |
+
result_code = 'result = '
|
| 709 |
+
context = 'result of %s' % name
|
| 710 |
+
result_decl = ' %s;' % tp.result.get_c_name(' result', context)
|
| 711 |
+
prnt(result_decl)
|
| 712 |
+
else:
|
| 713 |
+
result_decl = None
|
| 714 |
+
result_code = ''
|
| 715 |
+
#
|
| 716 |
+
if len(tp.args) > 1:
|
| 717 |
+
rng = range(len(tp.args))
|
| 718 |
+
for i in rng:
|
| 719 |
+
prnt(' PyObject *arg%d;' % i)
|
| 720 |
+
prnt()
|
| 721 |
+
prnt(' if (!PyArg_UnpackTuple(args, "%s", %d, %d, %s))' % (
|
| 722 |
+
name, len(rng), len(rng),
|
| 723 |
+
', '.join(['&arg%d' % i for i in rng])))
|
| 724 |
+
prnt(' return NULL;')
|
| 725 |
+
prnt()
|
| 726 |
+
#
|
| 727 |
+
for i, type in enumerate(tp.args):
|
| 728 |
+
self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i,
|
| 729 |
+
'return NULL')
|
| 730 |
+
prnt()
|
| 731 |
+
#
|
| 732 |
+
prnt(' Py_BEGIN_ALLOW_THREADS')
|
| 733 |
+
prnt(' _cffi_restore_errno();')
|
| 734 |
+
call_arguments = ['x%d' % i for i in range(len(tp.args))]
|
| 735 |
+
call_arguments = ', '.join(call_arguments)
|
| 736 |
+
prnt(' { %s%s(%s); }' % (result_code, name, call_arguments))
|
| 737 |
+
prnt(' _cffi_save_errno();')
|
| 738 |
+
prnt(' Py_END_ALLOW_THREADS')
|
| 739 |
+
prnt()
|
| 740 |
+
#
|
| 741 |
+
prnt(' (void)self; /* unused */')
|
| 742 |
+
if numargs == 0:
|
| 743 |
+
prnt(' (void)noarg; /* unused */')
|
| 744 |
+
if result_code:
|
| 745 |
+
prnt(' return %s;' %
|
| 746 |
+
self._convert_expr_from_c(tp.result, 'result', 'result type'))
|
| 747 |
+
else:
|
| 748 |
+
prnt(' Py_INCREF(Py_None);')
|
| 749 |
+
prnt(' return Py_None;')
|
| 750 |
+
prnt('}')
|
| 751 |
+
#
|
| 752 |
+
prnt('#else') # ------------------------------
|
| 753 |
+
#
|
| 754 |
+
# the PyPy version: need to replace struct/union arguments with
|
| 755 |
+
# pointers, and if the result is a struct/union, insert a first
|
| 756 |
+
# arg that is a pointer to the result. We also do that for
|
| 757 |
+
# complex args and return type.
|
| 758 |
+
def need_indirection(type):
|
| 759 |
+
return (isinstance(type, model.StructOrUnion) or
|
| 760 |
+
(isinstance(type, model.PrimitiveType) and
|
| 761 |
+
type.is_complex_type()))
|
| 762 |
+
difference = False
|
| 763 |
+
arguments = []
|
| 764 |
+
call_arguments = []
|
| 765 |
+
context = 'argument of %s' % name
|
| 766 |
+
for i, type in enumerate(tp.args):
|
| 767 |
+
indirection = ''
|
| 768 |
+
if need_indirection(type):
|
| 769 |
+
indirection = '*'
|
| 770 |
+
difference = True
|
| 771 |
+
arg = type.get_c_name(' %sx%d' % (indirection, i), context)
|
| 772 |
+
arguments.append(arg)
|
| 773 |
+
call_arguments.append('%sx%d' % (indirection, i))
|
| 774 |
+
tp_result = tp.result
|
| 775 |
+
if need_indirection(tp_result):
|
| 776 |
+
context = 'result of %s' % name
|
| 777 |
+
arg = tp_result.get_c_name(' *result', context)
|
| 778 |
+
arguments.insert(0, arg)
|
| 779 |
+
tp_result = model.void_type
|
| 780 |
+
result_decl = None
|
| 781 |
+
result_code = '*result = '
|
| 782 |
+
difference = True
|
| 783 |
+
if difference:
|
| 784 |
+
repr_arguments = ', '.join(arguments)
|
| 785 |
+
repr_arguments = repr_arguments or 'void'
|
| 786 |
+
name_and_arguments = '%s_cffi_f_%s(%s)' % (abi, name,
|
| 787 |
+
repr_arguments)
|
| 788 |
+
prnt('static %s' % (tp_result.get_c_name(name_and_arguments),))
|
| 789 |
+
prnt('{')
|
| 790 |
+
if result_decl:
|
| 791 |
+
prnt(result_decl)
|
| 792 |
+
call_arguments = ', '.join(call_arguments)
|
| 793 |
+
prnt(' { %s%s(%s); }' % (result_code, name, call_arguments))
|
| 794 |
+
if result_decl:
|
| 795 |
+
prnt(' return result;')
|
| 796 |
+
prnt('}')
|
| 797 |
+
else:
|
| 798 |
+
prnt('# define _cffi_f_%s _cffi_d_%s' % (name, name))
|
| 799 |
+
#
|
| 800 |
+
prnt('#endif') # ------------------------------
|
| 801 |
+
prnt()
|
| 802 |
+
|
| 803 |
+
def _generate_cpy_function_ctx(self, tp, name):
|
| 804 |
+
if tp.ellipsis and not self.target_is_python:
|
| 805 |
+
self._generate_cpy_constant_ctx(tp, name)
|
| 806 |
+
return
|
| 807 |
+
type_index = self._typesdict[tp.as_raw_function()]
|
| 808 |
+
numargs = len(tp.args)
|
| 809 |
+
if self.target_is_python:
|
| 810 |
+
meth_kind = OP_DLOPEN_FUNC
|
| 811 |
+
elif numargs == 0:
|
| 812 |
+
meth_kind = OP_CPYTHON_BLTN_N # 'METH_NOARGS'
|
| 813 |
+
elif numargs == 1:
|
| 814 |
+
meth_kind = OP_CPYTHON_BLTN_O # 'METH_O'
|
| 815 |
+
else:
|
| 816 |
+
meth_kind = OP_CPYTHON_BLTN_V # 'METH_VARARGS'
|
| 817 |
+
self._lsts["global"].append(
|
| 818 |
+
GlobalExpr(name, '_cffi_f_%s' % name,
|
| 819 |
+
CffiOp(meth_kind, type_index),
|
| 820 |
+
size='_cffi_d_%s' % name))
|
| 821 |
+
|
| 822 |
+
# ----------
|
| 823 |
+
# named structs or unions
|
| 824 |
+
|
| 825 |
+
def _field_type(self, tp_struct, field_name, tp_field):
|
| 826 |
+
if isinstance(tp_field, model.ArrayType):
|
| 827 |
+
actual_length = tp_field.length
|
| 828 |
+
if actual_length == '...':
|
| 829 |
+
ptr_struct_name = tp_struct.get_c_name('*')
|
| 830 |
+
actual_length = '_cffi_array_len(((%s)0)->%s)' % (
|
| 831 |
+
ptr_struct_name, field_name)
|
| 832 |
+
tp_item = self._field_type(tp_struct, '%s[0]' % field_name,
|
| 833 |
+
tp_field.item)
|
| 834 |
+
tp_field = model.ArrayType(tp_item, actual_length)
|
| 835 |
+
return tp_field
|
| 836 |
+
|
| 837 |
+
def _struct_collecttype(self, tp):
|
| 838 |
+
self._do_collect_type(tp)
|
| 839 |
+
if self.target_is_python:
|
| 840 |
+
# also requires nested anon struct/unions in ABI mode, recursively
|
| 841 |
+
for fldtype in tp.anonymous_struct_fields():
|
| 842 |
+
self._struct_collecttype(fldtype)
|
| 843 |
+
|
| 844 |
+
def _struct_decl(self, tp, cname, approxname):
|
| 845 |
+
if tp.fldtypes is None:
|
| 846 |
+
return
|
| 847 |
+
prnt = self._prnt
|
| 848 |
+
checkfuncname = '_cffi_checkfld_%s' % (approxname,)
|
| 849 |
+
prnt('_CFFI_UNUSED_FN')
|
| 850 |
+
prnt('static void %s(%s *p)' % (checkfuncname, cname))
|
| 851 |
+
prnt('{')
|
| 852 |
+
prnt(' /* only to generate compile-time warnings or errors */')
|
| 853 |
+
prnt(' (void)p;')
|
| 854 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
| 855 |
+
try:
|
| 856 |
+
if ftype.is_integer_type() or fbitsize >= 0:
|
| 857 |
+
# accept all integers, but complain on float or double
|
| 858 |
+
prnt(" (void)((p->%s) | 0); /* check that '%s.%s' is "
|
| 859 |
+
"an integer */" % (fname, cname, fname))
|
| 860 |
+
continue
|
| 861 |
+
# only accept exactly the type declared, except that '[]'
|
| 862 |
+
# is interpreted as a '*' and so will match any array length.
|
| 863 |
+
# (It would also match '*', but that's harder to detect...)
|
| 864 |
+
while (isinstance(ftype, model.ArrayType)
|
| 865 |
+
and (ftype.length is None or ftype.length == '...')):
|
| 866 |
+
ftype = ftype.item
|
| 867 |
+
fname = fname + '[0]'
|
| 868 |
+
prnt(' { %s = &p->%s; (void)tmp; }' % (
|
| 869 |
+
ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),
|
| 870 |
+
fname))
|
| 871 |
+
except VerificationError as e:
|
| 872 |
+
prnt(' /* %s */' % str(e)) # cannot verify it, ignore
|
| 873 |
+
prnt('}')
|
| 874 |
+
prnt('struct _cffi_align_%s { char x; %s y; };' % (approxname, cname))
|
| 875 |
+
prnt()
|
| 876 |
+
|
| 877 |
+
def _struct_ctx(self, tp, cname, approxname, named_ptr=None):
|
| 878 |
+
type_index = self._typesdict[tp]
|
| 879 |
+
reason_for_not_expanding = None
|
| 880 |
+
flags = []
|
| 881 |
+
if isinstance(tp, model.UnionType):
|
| 882 |
+
flags.append("_CFFI_F_UNION")
|
| 883 |
+
if tp.fldtypes is None:
|
| 884 |
+
flags.append("_CFFI_F_OPAQUE")
|
| 885 |
+
reason_for_not_expanding = "opaque"
|
| 886 |
+
if (tp not in self.ffi._parser._included_declarations and
|
| 887 |
+
(named_ptr is None or
|
| 888 |
+
named_ptr not in self.ffi._parser._included_declarations)):
|
| 889 |
+
if tp.fldtypes is None:
|
| 890 |
+
pass # opaque
|
| 891 |
+
elif tp.partial or any(tp.anonymous_struct_fields()):
|
| 892 |
+
pass # field layout obtained silently from the C compiler
|
| 893 |
+
else:
|
| 894 |
+
flags.append("_CFFI_F_CHECK_FIELDS")
|
| 895 |
+
if tp.packed:
|
| 896 |
+
if tp.packed > 1:
|
| 897 |
+
raise NotImplementedError(
|
| 898 |
+
"%r is declared with 'pack=%r'; only 0 or 1 are "
|
| 899 |
+
"supported in API mode (try to use \"...;\", which "
|
| 900 |
+
"does not require a 'pack' declaration)" %
|
| 901 |
+
(tp, tp.packed))
|
| 902 |
+
flags.append("_CFFI_F_PACKED")
|
| 903 |
+
else:
|
| 904 |
+
flags.append("_CFFI_F_EXTERNAL")
|
| 905 |
+
reason_for_not_expanding = "external"
|
| 906 |
+
flags = '|'.join(flags) or '0'
|
| 907 |
+
c_fields = []
|
| 908 |
+
if reason_for_not_expanding is None:
|
| 909 |
+
expand_anonymous_struct_union = not self.target_is_python
|
| 910 |
+
enumfields = list(tp.enumfields(expand_anonymous_struct_union))
|
| 911 |
+
for fldname, fldtype, fbitsize, fqual in enumfields:
|
| 912 |
+
fldtype = self._field_type(tp, fldname, fldtype)
|
| 913 |
+
self._check_not_opaque(fldtype,
|
| 914 |
+
"field '%s.%s'" % (tp.name, fldname))
|
| 915 |
+
# cname is None for _add_missing_struct_unions() only
|
| 916 |
+
op = OP_NOOP
|
| 917 |
+
if fbitsize >= 0:
|
| 918 |
+
op = OP_BITFIELD
|
| 919 |
+
size = '%d /* bits */' % fbitsize
|
| 920 |
+
elif cname is None or (
|
| 921 |
+
isinstance(fldtype, model.ArrayType) and
|
| 922 |
+
fldtype.length is None):
|
| 923 |
+
size = '(size_t)-1'
|
| 924 |
+
else:
|
| 925 |
+
size = 'sizeof(((%s)0)->%s)' % (
|
| 926 |
+
tp.get_c_name('*') if named_ptr is None
|
| 927 |
+
else named_ptr.name,
|
| 928 |
+
fldname)
|
| 929 |
+
if cname is None or fbitsize >= 0:
|
| 930 |
+
offset = '(size_t)-1'
|
| 931 |
+
elif named_ptr is not None:
|
| 932 |
+
offset = '((char *)&((%s)0)->%s) - (char *)0' % (
|
| 933 |
+
named_ptr.name, fldname)
|
| 934 |
+
else:
|
| 935 |
+
offset = 'offsetof(%s, %s)' % (tp.get_c_name(''), fldname)
|
| 936 |
+
c_fields.append(
|
| 937 |
+
FieldExpr(fldname, offset, size, fbitsize,
|
| 938 |
+
CffiOp(op, self._typesdict[fldtype])))
|
| 939 |
+
first_field_index = len(self._lsts["field"])
|
| 940 |
+
self._lsts["field"].extend(c_fields)
|
| 941 |
+
#
|
| 942 |
+
if cname is None: # unknown name, for _add_missing_struct_unions
|
| 943 |
+
size = '(size_t)-2'
|
| 944 |
+
align = -2
|
| 945 |
+
comment = "unnamed"
|
| 946 |
+
else:
|
| 947 |
+
if named_ptr is not None:
|
| 948 |
+
size = 'sizeof(*(%s)0)' % (named_ptr.name,)
|
| 949 |
+
align = '-1 /* unknown alignment */'
|
| 950 |
+
else:
|
| 951 |
+
size = 'sizeof(%s)' % (cname,)
|
| 952 |
+
align = 'offsetof(struct _cffi_align_%s, y)' % (approxname,)
|
| 953 |
+
comment = None
|
| 954 |
+
else:
|
| 955 |
+
size = '(size_t)-1'
|
| 956 |
+
align = -1
|
| 957 |
+
first_field_index = -1
|
| 958 |
+
comment = reason_for_not_expanding
|
| 959 |
+
self._lsts["struct_union"].append(
|
| 960 |
+
StructUnionExpr(tp.name, type_index, flags, size, align, comment,
|
| 961 |
+
first_field_index, c_fields))
|
| 962 |
+
self._seen_struct_unions.add(tp)
|
| 963 |
+
|
| 964 |
+
def _check_not_opaque(self, tp, location):
|
| 965 |
+
while isinstance(tp, model.ArrayType):
|
| 966 |
+
tp = tp.item
|
| 967 |
+
if isinstance(tp, model.StructOrUnion) and tp.fldtypes is None:
|
| 968 |
+
raise TypeError(
|
| 969 |
+
"%s is of an opaque type (not declared in cdef())" % location)
|
| 970 |
+
|
| 971 |
+
def _add_missing_struct_unions(self):
|
| 972 |
+
# not very nice, but some struct declarations might be missing
|
| 973 |
+
# because they don't have any known C name. Check that they are
|
| 974 |
+
# not partial (we can't complete or verify them!) and emit them
|
| 975 |
+
# anonymously.
|
| 976 |
+
lst = list(self._struct_unions.items())
|
| 977 |
+
lst.sort(key=lambda tp_order: tp_order[1])
|
| 978 |
+
for tp, order in lst:
|
| 979 |
+
if tp not in self._seen_struct_unions:
|
| 980 |
+
if tp.partial:
|
| 981 |
+
raise NotImplementedError("internal inconsistency: %r is "
|
| 982 |
+
"partial but was not seen at "
|
| 983 |
+
"this point" % (tp,))
|
| 984 |
+
if tp.name.startswith('$') and tp.name[1:].isdigit():
|
| 985 |
+
approxname = tp.name[1:]
|
| 986 |
+
elif tp.name == '_IO_FILE' and tp.forcename == 'FILE':
|
| 987 |
+
approxname = 'FILE'
|
| 988 |
+
self._typedef_ctx(tp, 'FILE')
|
| 989 |
+
else:
|
| 990 |
+
raise NotImplementedError("internal inconsistency: %r" %
|
| 991 |
+
(tp,))
|
| 992 |
+
self._struct_ctx(tp, None, approxname)
|
| 993 |
+
|
| 994 |
+
def _generate_cpy_struct_collecttype(self, tp, name):
|
| 995 |
+
self._struct_collecttype(tp)
|
| 996 |
+
_generate_cpy_union_collecttype = _generate_cpy_struct_collecttype
|
| 997 |
+
|
| 998 |
+
def _struct_names(self, tp):
|
| 999 |
+
cname = tp.get_c_name('')
|
| 1000 |
+
if ' ' in cname:
|
| 1001 |
+
return cname, cname.replace(' ', '_')
|
| 1002 |
+
else:
|
| 1003 |
+
return cname, '_' + cname
|
| 1004 |
+
|
| 1005 |
+
def _generate_cpy_struct_decl(self, tp, name):
|
| 1006 |
+
self._struct_decl(tp, *self._struct_names(tp))
|
| 1007 |
+
_generate_cpy_union_decl = _generate_cpy_struct_decl
|
| 1008 |
+
|
| 1009 |
+
def _generate_cpy_struct_ctx(self, tp, name):
|
| 1010 |
+
self._struct_ctx(tp, *self._struct_names(tp))
|
| 1011 |
+
_generate_cpy_union_ctx = _generate_cpy_struct_ctx
|
| 1012 |
+
|
| 1013 |
+
# ----------
|
| 1014 |
+
# 'anonymous' declarations. These are produced for anonymous structs
|
| 1015 |
+
# or unions; the 'name' is obtained by a typedef.
|
| 1016 |
+
|
| 1017 |
+
def _generate_cpy_anonymous_collecttype(self, tp, name):
|
| 1018 |
+
if isinstance(tp, model.EnumType):
|
| 1019 |
+
self._generate_cpy_enum_collecttype(tp, name)
|
| 1020 |
+
else:
|
| 1021 |
+
self._struct_collecttype(tp)
|
| 1022 |
+
|
| 1023 |
+
def _generate_cpy_anonymous_decl(self, tp, name):
|
| 1024 |
+
if isinstance(tp, model.EnumType):
|
| 1025 |
+
self._generate_cpy_enum_decl(tp)
|
| 1026 |
+
else:
|
| 1027 |
+
self._struct_decl(tp, name, 'typedef_' + name)
|
| 1028 |
+
|
| 1029 |
+
def _generate_cpy_anonymous_ctx(self, tp, name):
|
| 1030 |
+
if isinstance(tp, model.EnumType):
|
| 1031 |
+
self._enum_ctx(tp, name)
|
| 1032 |
+
else:
|
| 1033 |
+
self._struct_ctx(tp, name, 'typedef_' + name)
|
| 1034 |
+
|
| 1035 |
+
# ----------
|
| 1036 |
+
# constants, declared with "static const ..."
|
| 1037 |
+
|
| 1038 |
+
def _generate_cpy_const(self, is_int, name, tp=None, category='const',
|
| 1039 |
+
check_value=None):
|
| 1040 |
+
if (category, name) in self._seen_constants:
|
| 1041 |
+
raise VerificationError(
|
| 1042 |
+
"duplicate declaration of %s '%s'" % (category, name))
|
| 1043 |
+
self._seen_constants.add((category, name))
|
| 1044 |
+
#
|
| 1045 |
+
prnt = self._prnt
|
| 1046 |
+
funcname = '_cffi_%s_%s' % (category, name)
|
| 1047 |
+
if is_int:
|
| 1048 |
+
prnt('static int %s(unsigned long long *o)' % funcname)
|
| 1049 |
+
prnt('{')
|
| 1050 |
+
prnt(' int n = (%s) <= 0;' % (name,))
|
| 1051 |
+
prnt(' *o = (unsigned long long)((%s) | 0);'
|
| 1052 |
+
' /* check that %s is an integer */' % (name, name))
|
| 1053 |
+
if check_value is not None:
|
| 1054 |
+
if check_value > 0:
|
| 1055 |
+
check_value = '%dU' % (check_value,)
|
| 1056 |
+
prnt(' if (!_cffi_check_int(*o, n, %s))' % (check_value,))
|
| 1057 |
+
prnt(' n |= 2;')
|
| 1058 |
+
prnt(' return n;')
|
| 1059 |
+
prnt('}')
|
| 1060 |
+
else:
|
| 1061 |
+
assert check_value is None
|
| 1062 |
+
prnt('static void %s(char *o)' % funcname)
|
| 1063 |
+
prnt('{')
|
| 1064 |
+
prnt(' *(%s)o = %s;' % (tp.get_c_name('*'), name))
|
| 1065 |
+
prnt('}')
|
| 1066 |
+
prnt()
|
| 1067 |
+
|
| 1068 |
+
def _generate_cpy_constant_collecttype(self, tp, name):
|
| 1069 |
+
is_int = tp.is_integer_type()
|
| 1070 |
+
if not is_int or self.target_is_python:
|
| 1071 |
+
self._do_collect_type(tp)
|
| 1072 |
+
|
| 1073 |
+
def _generate_cpy_constant_decl(self, tp, name):
|
| 1074 |
+
is_int = tp.is_integer_type()
|
| 1075 |
+
self._generate_cpy_const(is_int, name, tp)
|
| 1076 |
+
|
| 1077 |
+
def _generate_cpy_constant_ctx(self, tp, name):
|
| 1078 |
+
if not self.target_is_python and tp.is_integer_type():
|
| 1079 |
+
type_op = CffiOp(OP_CONSTANT_INT, -1)
|
| 1080 |
+
else:
|
| 1081 |
+
if self.target_is_python:
|
| 1082 |
+
const_kind = OP_DLOPEN_CONST
|
| 1083 |
+
else:
|
| 1084 |
+
const_kind = OP_CONSTANT
|
| 1085 |
+
type_index = self._typesdict[tp]
|
| 1086 |
+
type_op = CffiOp(const_kind, type_index)
|
| 1087 |
+
self._lsts["global"].append(
|
| 1088 |
+
GlobalExpr(name, '_cffi_const_%s' % name, type_op))
|
| 1089 |
+
|
| 1090 |
+
# ----------
|
| 1091 |
+
# enums
|
| 1092 |
+
|
| 1093 |
+
def _generate_cpy_enum_collecttype(self, tp, name):
|
| 1094 |
+
self._do_collect_type(tp)
|
| 1095 |
+
|
| 1096 |
+
def _generate_cpy_enum_decl(self, tp, name=None):
|
| 1097 |
+
for enumerator in tp.enumerators:
|
| 1098 |
+
self._generate_cpy_const(True, enumerator)
|
| 1099 |
+
|
| 1100 |
+
def _enum_ctx(self, tp, cname):
|
| 1101 |
+
type_index = self._typesdict[tp]
|
| 1102 |
+
type_op = CffiOp(OP_ENUM, -1)
|
| 1103 |
+
if self.target_is_python:
|
| 1104 |
+
tp.check_not_partial()
|
| 1105 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
| 1106 |
+
self._lsts["global"].append(
|
| 1107 |
+
GlobalExpr(enumerator, '_cffi_const_%s' % enumerator, type_op,
|
| 1108 |
+
check_value=enumvalue))
|
| 1109 |
+
#
|
| 1110 |
+
if cname is not None and '$' not in cname and not self.target_is_python:
|
| 1111 |
+
size = "sizeof(%s)" % cname
|
| 1112 |
+
signed = "((%s)-1) <= 0" % cname
|
| 1113 |
+
else:
|
| 1114 |
+
basetp = tp.build_baseinttype(self.ffi, [])
|
| 1115 |
+
size = self.ffi.sizeof(basetp)
|
| 1116 |
+
signed = int(int(self.ffi.cast(basetp, -1)) < 0)
|
| 1117 |
+
allenums = ",".join(tp.enumerators)
|
| 1118 |
+
self._lsts["enum"].append(
|
| 1119 |
+
EnumExpr(tp.name, type_index, size, signed, allenums))
|
| 1120 |
+
|
| 1121 |
+
def _generate_cpy_enum_ctx(self, tp, name):
|
| 1122 |
+
self._enum_ctx(tp, tp._get_c_name())
|
| 1123 |
+
|
| 1124 |
+
# ----------
|
| 1125 |
+
# macros: for now only for integers
|
| 1126 |
+
|
| 1127 |
+
def _generate_cpy_macro_collecttype(self, tp, name):
|
| 1128 |
+
pass
|
| 1129 |
+
|
| 1130 |
+
def _generate_cpy_macro_decl(self, tp, name):
|
| 1131 |
+
if tp == '...':
|
| 1132 |
+
check_value = None
|
| 1133 |
+
else:
|
| 1134 |
+
check_value = tp # an integer
|
| 1135 |
+
self._generate_cpy_const(True, name, check_value=check_value)
|
| 1136 |
+
|
| 1137 |
+
def _generate_cpy_macro_ctx(self, tp, name):
|
| 1138 |
+
if tp == '...':
|
| 1139 |
+
if self.target_is_python:
|
| 1140 |
+
raise VerificationError(
|
| 1141 |
+
"cannot use the syntax '...' in '#define %s ...' when "
|
| 1142 |
+
"using the ABI mode" % (name,))
|
| 1143 |
+
check_value = None
|
| 1144 |
+
else:
|
| 1145 |
+
check_value = tp # an integer
|
| 1146 |
+
type_op = CffiOp(OP_CONSTANT_INT, -1)
|
| 1147 |
+
self._lsts["global"].append(
|
| 1148 |
+
GlobalExpr(name, '_cffi_const_%s' % name, type_op,
|
| 1149 |
+
check_value=check_value))
|
| 1150 |
+
|
| 1151 |
+
# ----------
|
| 1152 |
+
# global variables
|
| 1153 |
+
|
| 1154 |
+
def _global_type(self, tp, global_name):
|
| 1155 |
+
if isinstance(tp, model.ArrayType):
|
| 1156 |
+
actual_length = tp.length
|
| 1157 |
+
if actual_length == '...':
|
| 1158 |
+
actual_length = '_cffi_array_len(%s)' % (global_name,)
|
| 1159 |
+
tp_item = self._global_type(tp.item, '%s[0]' % global_name)
|
| 1160 |
+
tp = model.ArrayType(tp_item, actual_length)
|
| 1161 |
+
return tp
|
| 1162 |
+
|
| 1163 |
+
def _generate_cpy_variable_collecttype(self, tp, name):
|
| 1164 |
+
self._do_collect_type(self._global_type(tp, name))
|
| 1165 |
+
|
| 1166 |
+
def _generate_cpy_variable_decl(self, tp, name):
|
| 1167 |
+
prnt = self._prnt
|
| 1168 |
+
tp = self._global_type(tp, name)
|
| 1169 |
+
if isinstance(tp, model.ArrayType) and tp.length is None:
|
| 1170 |
+
tp = tp.item
|
| 1171 |
+
ampersand = ''
|
| 1172 |
+
else:
|
| 1173 |
+
ampersand = '&'
|
| 1174 |
+
# This code assumes that casts from "tp *" to "void *" is a
|
| 1175 |
+
# no-op, i.e. a function that returns a "tp *" can be called
|
| 1176 |
+
# as if it returned a "void *". This should be generally true
|
| 1177 |
+
# on any modern machine. The only exception to that rule (on
|
| 1178 |
+
# uncommon architectures, and as far as I can tell) might be
|
| 1179 |
+
# if 'tp' were a function type, but that is not possible here.
|
| 1180 |
+
# (If 'tp' is a function _pointer_ type, then casts from "fn_t
|
| 1181 |
+
# **" to "void *" are again no-ops, as far as I can tell.)
|
| 1182 |
+
decl = '*_cffi_var_%s(void)' % (name,)
|
| 1183 |
+
prnt('static ' + tp.get_c_name(decl, quals=self._current_quals))
|
| 1184 |
+
prnt('{')
|
| 1185 |
+
prnt(' return %s(%s);' % (ampersand, name))
|
| 1186 |
+
prnt('}')
|
| 1187 |
+
prnt()
|
| 1188 |
+
|
| 1189 |
+
def _generate_cpy_variable_ctx(self, tp, name):
|
| 1190 |
+
tp = self._global_type(tp, name)
|
| 1191 |
+
type_index = self._typesdict[tp]
|
| 1192 |
+
if self.target_is_python:
|
| 1193 |
+
op = OP_GLOBAL_VAR
|
| 1194 |
+
else:
|
| 1195 |
+
op = OP_GLOBAL_VAR_F
|
| 1196 |
+
self._lsts["global"].append(
|
| 1197 |
+
GlobalExpr(name, '_cffi_var_%s' % name, CffiOp(op, type_index)))
|
| 1198 |
+
|
| 1199 |
+
# ----------
|
| 1200 |
+
# extern "Python"
|
| 1201 |
+
|
| 1202 |
+
def _generate_cpy_extern_python_collecttype(self, tp, name):
|
| 1203 |
+
assert isinstance(tp, model.FunctionPtrType)
|
| 1204 |
+
self._do_collect_type(tp)
|
| 1205 |
+
_generate_cpy_dllexport_python_collecttype = \
|
| 1206 |
+
_generate_cpy_extern_python_plus_c_collecttype = \
|
| 1207 |
+
_generate_cpy_extern_python_collecttype
|
| 1208 |
+
|
| 1209 |
+
def _extern_python_decl(self, tp, name, tag_and_space):
|
| 1210 |
+
prnt = self._prnt
|
| 1211 |
+
if isinstance(tp.result, model.VoidType):
|
| 1212 |
+
size_of_result = '0'
|
| 1213 |
+
else:
|
| 1214 |
+
context = 'result of %s' % name
|
| 1215 |
+
size_of_result = '(int)sizeof(%s)' % (
|
| 1216 |
+
tp.result.get_c_name('', context),)
|
| 1217 |
+
prnt('static struct _cffi_externpy_s _cffi_externpy__%s =' % name)
|
| 1218 |
+
prnt(' { "%s.%s", %s };' % (self.module_name, name, size_of_result))
|
| 1219 |
+
prnt()
|
| 1220 |
+
#
|
| 1221 |
+
arguments = []
|
| 1222 |
+
context = 'argument of %s' % name
|
| 1223 |
+
for i, type in enumerate(tp.args):
|
| 1224 |
+
arg = type.get_c_name(' a%d' % i, context)
|
| 1225 |
+
arguments.append(arg)
|
| 1226 |
+
#
|
| 1227 |
+
repr_arguments = ', '.join(arguments)
|
| 1228 |
+
repr_arguments = repr_arguments or 'void'
|
| 1229 |
+
name_and_arguments = '%s(%s)' % (name, repr_arguments)
|
| 1230 |
+
if tp.abi == "__stdcall":
|
| 1231 |
+
name_and_arguments = '_cffi_stdcall ' + name_and_arguments
|
| 1232 |
+
#
|
| 1233 |
+
def may_need_128_bits(tp):
|
| 1234 |
+
return (isinstance(tp, model.PrimitiveType) and
|
| 1235 |
+
tp.name == 'long double')
|
| 1236 |
+
#
|
| 1237 |
+
size_of_a = max(len(tp.args)*8, 8)
|
| 1238 |
+
if may_need_128_bits(tp.result):
|
| 1239 |
+
size_of_a = max(size_of_a, 16)
|
| 1240 |
+
if isinstance(tp.result, model.StructOrUnion):
|
| 1241 |
+
size_of_a = 'sizeof(%s) > %d ? sizeof(%s) : %d' % (
|
| 1242 |
+
tp.result.get_c_name(''), size_of_a,
|
| 1243 |
+
tp.result.get_c_name(''), size_of_a)
|
| 1244 |
+
prnt('%s%s' % (tag_and_space, tp.result.get_c_name(name_and_arguments)))
|
| 1245 |
+
prnt('{')
|
| 1246 |
+
prnt(' char a[%s];' % size_of_a)
|
| 1247 |
+
prnt(' char *p = a;')
|
| 1248 |
+
for i, type in enumerate(tp.args):
|
| 1249 |
+
arg = 'a%d' % i
|
| 1250 |
+
if (isinstance(type, model.StructOrUnion) or
|
| 1251 |
+
may_need_128_bits(type)):
|
| 1252 |
+
arg = '&' + arg
|
| 1253 |
+
type = model.PointerType(type)
|
| 1254 |
+
prnt(' *(%s)(p + %d) = %s;' % (type.get_c_name('*'), i*8, arg))
|
| 1255 |
+
prnt(' _cffi_call_python(&_cffi_externpy__%s, p);' % name)
|
| 1256 |
+
if not isinstance(tp.result, model.VoidType):
|
| 1257 |
+
prnt(' return *(%s)p;' % (tp.result.get_c_name('*'),))
|
| 1258 |
+
prnt('}')
|
| 1259 |
+
prnt()
|
| 1260 |
+
self._num_externpy += 1
|
| 1261 |
+
|
| 1262 |
+
def _generate_cpy_extern_python_decl(self, tp, name):
|
| 1263 |
+
self._extern_python_decl(tp, name, 'static ')
|
| 1264 |
+
|
| 1265 |
+
def _generate_cpy_dllexport_python_decl(self, tp, name):
|
| 1266 |
+
self._extern_python_decl(tp, name, 'CFFI_DLLEXPORT ')
|
| 1267 |
+
|
| 1268 |
+
def _generate_cpy_extern_python_plus_c_decl(self, tp, name):
|
| 1269 |
+
self._extern_python_decl(tp, name, '')
|
| 1270 |
+
|
| 1271 |
+
def _generate_cpy_extern_python_ctx(self, tp, name):
|
| 1272 |
+
if self.target_is_python:
|
| 1273 |
+
raise VerificationError(
|
| 1274 |
+
"cannot use 'extern \"Python\"' in the ABI mode")
|
| 1275 |
+
if tp.ellipsis:
|
| 1276 |
+
raise NotImplementedError("a vararg function is extern \"Python\"")
|
| 1277 |
+
type_index = self._typesdict[tp]
|
| 1278 |
+
type_op = CffiOp(OP_EXTERN_PYTHON, type_index)
|
| 1279 |
+
self._lsts["global"].append(
|
| 1280 |
+
GlobalExpr(name, '&_cffi_externpy__%s' % name, type_op, name))
|
| 1281 |
+
|
| 1282 |
+
_generate_cpy_dllexport_python_ctx = \
|
| 1283 |
+
_generate_cpy_extern_python_plus_c_ctx = \
|
| 1284 |
+
_generate_cpy_extern_python_ctx
|
| 1285 |
+
|
| 1286 |
+
def _print_string_literal_in_array(self, s):
|
| 1287 |
+
prnt = self._prnt
|
| 1288 |
+
prnt('// # NB. this is not a string because of a size limit in MSVC')
|
| 1289 |
+
for line in s.splitlines(True):
|
| 1290 |
+
prnt(('// ' + line).rstrip())
|
| 1291 |
+
printed_line = ''
|
| 1292 |
+
for c in line:
|
| 1293 |
+
if len(printed_line) >= 76:
|
| 1294 |
+
prnt(printed_line)
|
| 1295 |
+
printed_line = ''
|
| 1296 |
+
printed_line += '%d,' % (ord(c),)
|
| 1297 |
+
prnt(printed_line)
|
| 1298 |
+
|
| 1299 |
+
# ----------
|
| 1300 |
+
# emitting the opcodes for individual types
|
| 1301 |
+
|
| 1302 |
+
def _emit_bytecode_VoidType(self, tp, index):
|
| 1303 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, PRIM_VOID)
|
| 1304 |
+
|
| 1305 |
+
def _emit_bytecode_PrimitiveType(self, tp, index):
|
| 1306 |
+
prim_index = PRIMITIVE_TO_INDEX[tp.name]
|
| 1307 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, prim_index)
|
| 1308 |
+
|
| 1309 |
+
def _emit_bytecode_UnknownIntegerType(self, tp, index):
|
| 1310 |
+
s = ('_cffi_prim_int(sizeof(%s), (\n'
|
| 1311 |
+
' ((%s)-1) | 0 /* check that %s is an integer type */\n'
|
| 1312 |
+
' ) <= 0)' % (tp.name, tp.name, tp.name))
|
| 1313 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s)
|
| 1314 |
+
|
| 1315 |
+
def _emit_bytecode_UnknownFloatType(self, tp, index):
|
| 1316 |
+
s = ('_cffi_prim_float(sizeof(%s) *\n'
|
| 1317 |
+
' (((%s)1) / 2) * 2 /* integer => 0, float => 1 */\n'
|
| 1318 |
+
' )' % (tp.name, tp.name))
|
| 1319 |
+
self.cffi_types[index] = CffiOp(OP_PRIMITIVE, s)
|
| 1320 |
+
|
| 1321 |
+
def _emit_bytecode_RawFunctionType(self, tp, index):
|
| 1322 |
+
self.cffi_types[index] = CffiOp(OP_FUNCTION, self._typesdict[tp.result])
|
| 1323 |
+
index += 1
|
| 1324 |
+
for tp1 in tp.args:
|
| 1325 |
+
realindex = self._typesdict[tp1]
|
| 1326 |
+
if index != realindex:
|
| 1327 |
+
if isinstance(tp1, model.PrimitiveType):
|
| 1328 |
+
self._emit_bytecode_PrimitiveType(tp1, index)
|
| 1329 |
+
else:
|
| 1330 |
+
self.cffi_types[index] = CffiOp(OP_NOOP, realindex)
|
| 1331 |
+
index += 1
|
| 1332 |
+
flags = int(tp.ellipsis)
|
| 1333 |
+
if tp.abi is not None:
|
| 1334 |
+
if tp.abi == '__stdcall':
|
| 1335 |
+
flags |= 2
|
| 1336 |
+
else:
|
| 1337 |
+
raise NotImplementedError("abi=%r" % (tp.abi,))
|
| 1338 |
+
self.cffi_types[index] = CffiOp(OP_FUNCTION_END, flags)
|
| 1339 |
+
|
| 1340 |
+
def _emit_bytecode_PointerType(self, tp, index):
|
| 1341 |
+
self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[tp.totype])
|
| 1342 |
+
|
| 1343 |
+
_emit_bytecode_ConstPointerType = _emit_bytecode_PointerType
|
| 1344 |
+
_emit_bytecode_NamedPointerType = _emit_bytecode_PointerType
|
| 1345 |
+
|
| 1346 |
+
def _emit_bytecode_FunctionPtrType(self, tp, index):
|
| 1347 |
+
raw = tp.as_raw_function()
|
| 1348 |
+
self.cffi_types[index] = CffiOp(OP_POINTER, self._typesdict[raw])
|
| 1349 |
+
|
| 1350 |
+
def _emit_bytecode_ArrayType(self, tp, index):
|
| 1351 |
+
item_index = self._typesdict[tp.item]
|
| 1352 |
+
if tp.length is None:
|
| 1353 |
+
self.cffi_types[index] = CffiOp(OP_OPEN_ARRAY, item_index)
|
| 1354 |
+
elif tp.length == '...':
|
| 1355 |
+
raise VerificationError(
|
| 1356 |
+
"type %s badly placed: the '...' array length can only be "
|
| 1357 |
+
"used on global arrays or on fields of structures" % (
|
| 1358 |
+
str(tp).replace('/*...*/', '...'),))
|
| 1359 |
+
else:
|
| 1360 |
+
assert self.cffi_types[index + 1] == 'LEN'
|
| 1361 |
+
self.cffi_types[index] = CffiOp(OP_ARRAY, item_index)
|
| 1362 |
+
self.cffi_types[index + 1] = CffiOp(None, str(tp.length))
|
| 1363 |
+
|
| 1364 |
+
def _emit_bytecode_StructType(self, tp, index):
|
| 1365 |
+
struct_index = self._struct_unions[tp]
|
| 1366 |
+
self.cffi_types[index] = CffiOp(OP_STRUCT_UNION, struct_index)
|
| 1367 |
+
_emit_bytecode_UnionType = _emit_bytecode_StructType
|
| 1368 |
+
|
| 1369 |
+
def _emit_bytecode_EnumType(self, tp, index):
|
| 1370 |
+
enum_index = self._enums[tp]
|
| 1371 |
+
self.cffi_types[index] = CffiOp(OP_ENUM, enum_index)
|
| 1372 |
+
|
| 1373 |
+
|
| 1374 |
+
if sys.version_info >= (3,):
|
| 1375 |
+
NativeIO = io.StringIO
|
| 1376 |
+
else:
|
| 1377 |
+
class NativeIO(io.BytesIO):
|
| 1378 |
+
def write(self, s):
|
| 1379 |
+
if isinstance(s, unicode):
|
| 1380 |
+
s = s.encode('ascii')
|
| 1381 |
+
super(NativeIO, self).write(s)
|
| 1382 |
+
|
| 1383 |
+
def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose):
|
| 1384 |
+
if verbose:
|
| 1385 |
+
print("generating %s" % (target_file,))
|
| 1386 |
+
recompiler = Recompiler(ffi, module_name,
|
| 1387 |
+
target_is_python=(preamble is None))
|
| 1388 |
+
recompiler.collect_type_table()
|
| 1389 |
+
recompiler.collect_step_tables()
|
| 1390 |
+
f = NativeIO()
|
| 1391 |
+
recompiler.write_source_to_f(f, preamble)
|
| 1392 |
+
output = f.getvalue()
|
| 1393 |
+
try:
|
| 1394 |
+
with open(target_file, 'r') as f1:
|
| 1395 |
+
if f1.read(len(output) + 1) != output:
|
| 1396 |
+
raise IOError
|
| 1397 |
+
if verbose:
|
| 1398 |
+
print("(already up-to-date)")
|
| 1399 |
+
return False # already up-to-date
|
| 1400 |
+
except IOError:
|
| 1401 |
+
tmp_file = '%s.~%d' % (target_file, os.getpid())
|
| 1402 |
+
with open(tmp_file, 'w') as f1:
|
| 1403 |
+
f1.write(output)
|
| 1404 |
+
try:
|
| 1405 |
+
os.rename(tmp_file, target_file)
|
| 1406 |
+
except OSError:
|
| 1407 |
+
os.unlink(target_file)
|
| 1408 |
+
os.rename(tmp_file, target_file)
|
| 1409 |
+
return True
|
| 1410 |
+
|
| 1411 |
+
def make_c_source(ffi, module_name, preamble, target_c_file, verbose=False):
|
| 1412 |
+
assert preamble is not None
|
| 1413 |
+
return _make_c_or_py_source(ffi, module_name, preamble, target_c_file,
|
| 1414 |
+
verbose)
|
| 1415 |
+
|
| 1416 |
+
def make_py_source(ffi, module_name, target_py_file, verbose=False):
|
| 1417 |
+
return _make_c_or_py_source(ffi, module_name, None, target_py_file,
|
| 1418 |
+
verbose)
|
| 1419 |
+
|
| 1420 |
+
def _modname_to_file(outputdir, modname, extension):
|
| 1421 |
+
parts = modname.split('.')
|
| 1422 |
+
try:
|
| 1423 |
+
os.makedirs(os.path.join(outputdir, *parts[:-1]))
|
| 1424 |
+
except OSError:
|
| 1425 |
+
pass
|
| 1426 |
+
parts[-1] += extension
|
| 1427 |
+
return os.path.join(outputdir, *parts), parts
|
| 1428 |
+
|
| 1429 |
+
|
| 1430 |
+
# Aaargh. Distutils is not tested at all for the purpose of compiling
|
| 1431 |
+
# DLLs that are not extension modules. Here are some hacks to work
|
| 1432 |
+
# around that, in the _patch_for_*() functions...
|
| 1433 |
+
|
| 1434 |
+
def _patch_meth(patchlist, cls, name, new_meth):
|
| 1435 |
+
old = getattr(cls, name)
|
| 1436 |
+
patchlist.append((cls, name, old))
|
| 1437 |
+
setattr(cls, name, new_meth)
|
| 1438 |
+
return old
|
| 1439 |
+
|
| 1440 |
+
def _unpatch_meths(patchlist):
|
| 1441 |
+
for cls, name, old_meth in reversed(patchlist):
|
| 1442 |
+
setattr(cls, name, old_meth)
|
| 1443 |
+
|
| 1444 |
+
def _patch_for_embedding(patchlist):
|
| 1445 |
+
if sys.platform == 'win32':
|
| 1446 |
+
# we must not remove the manifest when building for embedding!
|
| 1447 |
+
from distutils.msvc9compiler import MSVCCompiler
|
| 1448 |
+
_patch_meth(patchlist, MSVCCompiler, '_remove_visual_c_ref',
|
| 1449 |
+
lambda self, manifest_file: manifest_file)
|
| 1450 |
+
|
| 1451 |
+
if sys.platform == 'darwin':
|
| 1452 |
+
# we must not make a '-bundle', but a '-dynamiclib' instead
|
| 1453 |
+
from distutils.ccompiler import CCompiler
|
| 1454 |
+
def my_link_shared_object(self, *args, **kwds):
|
| 1455 |
+
if '-bundle' in self.linker_so:
|
| 1456 |
+
self.linker_so = list(self.linker_so)
|
| 1457 |
+
i = self.linker_so.index('-bundle')
|
| 1458 |
+
self.linker_so[i] = '-dynamiclib'
|
| 1459 |
+
return old_link_shared_object(self, *args, **kwds)
|
| 1460 |
+
old_link_shared_object = _patch_meth(patchlist, CCompiler,
|
| 1461 |
+
'link_shared_object',
|
| 1462 |
+
my_link_shared_object)
|
| 1463 |
+
|
| 1464 |
+
def _patch_for_target(patchlist, target):
|
| 1465 |
+
from distutils.command.build_ext import build_ext
|
| 1466 |
+
# if 'target' is different from '*', we need to patch some internal
|
| 1467 |
+
# method to just return this 'target' value, instead of having it
|
| 1468 |
+
# built from module_name
|
| 1469 |
+
if target.endswith('.*'):
|
| 1470 |
+
target = target[:-2]
|
| 1471 |
+
if sys.platform == 'win32':
|
| 1472 |
+
target += '.dll'
|
| 1473 |
+
elif sys.platform == 'darwin':
|
| 1474 |
+
target += '.dylib'
|
| 1475 |
+
else:
|
| 1476 |
+
target += '.so'
|
| 1477 |
+
_patch_meth(patchlist, build_ext, 'get_ext_filename',
|
| 1478 |
+
lambda self, ext_name: target)
|
| 1479 |
+
|
| 1480 |
+
|
| 1481 |
+
def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True,
|
| 1482 |
+
c_file=None, source_extension='.c', extradir=None,
|
| 1483 |
+
compiler_verbose=1, target=None, debug=None, **kwds):
|
| 1484 |
+
if not isinstance(module_name, str):
|
| 1485 |
+
module_name = module_name.encode('ascii')
|
| 1486 |
+
if ffi._windows_unicode:
|
| 1487 |
+
ffi._apply_windows_unicode(kwds)
|
| 1488 |
+
if preamble is not None:
|
| 1489 |
+
embedding = (ffi._embedding is not None)
|
| 1490 |
+
if embedding:
|
| 1491 |
+
ffi._apply_embedding_fix(kwds)
|
| 1492 |
+
if c_file is None:
|
| 1493 |
+
c_file, parts = _modname_to_file(tmpdir, module_name,
|
| 1494 |
+
source_extension)
|
| 1495 |
+
if extradir:
|
| 1496 |
+
parts = [extradir] + parts
|
| 1497 |
+
ext_c_file = os.path.join(*parts)
|
| 1498 |
+
else:
|
| 1499 |
+
ext_c_file = c_file
|
| 1500 |
+
#
|
| 1501 |
+
if target is None:
|
| 1502 |
+
if embedding:
|
| 1503 |
+
target = '%s.*' % module_name
|
| 1504 |
+
else:
|
| 1505 |
+
target = '*'
|
| 1506 |
+
#
|
| 1507 |
+
ext = ffiplatform.get_extension(ext_c_file, module_name, **kwds)
|
| 1508 |
+
updated = make_c_source(ffi, module_name, preamble, c_file,
|
| 1509 |
+
verbose=compiler_verbose)
|
| 1510 |
+
if call_c_compiler:
|
| 1511 |
+
patchlist = []
|
| 1512 |
+
cwd = os.getcwd()
|
| 1513 |
+
try:
|
| 1514 |
+
if embedding:
|
| 1515 |
+
_patch_for_embedding(patchlist)
|
| 1516 |
+
if target != '*':
|
| 1517 |
+
_patch_for_target(patchlist, target)
|
| 1518 |
+
if compiler_verbose:
|
| 1519 |
+
if tmpdir == '.':
|
| 1520 |
+
msg = 'the current directory is'
|
| 1521 |
+
else:
|
| 1522 |
+
msg = 'setting the current directory to'
|
| 1523 |
+
print('%s %r' % (msg, os.path.abspath(tmpdir)))
|
| 1524 |
+
os.chdir(tmpdir)
|
| 1525 |
+
outputfilename = ffiplatform.compile('.', ext,
|
| 1526 |
+
compiler_verbose, debug)
|
| 1527 |
+
finally:
|
| 1528 |
+
os.chdir(cwd)
|
| 1529 |
+
_unpatch_meths(patchlist)
|
| 1530 |
+
return outputfilename
|
| 1531 |
+
else:
|
| 1532 |
+
return ext, updated
|
| 1533 |
+
else:
|
| 1534 |
+
if c_file is None:
|
| 1535 |
+
c_file, _ = _modname_to_file(tmpdir, module_name, '.py')
|
| 1536 |
+
updated = make_py_source(ffi, module_name, c_file,
|
| 1537 |
+
verbose=compiler_verbose)
|
| 1538 |
+
if call_c_compiler:
|
| 1539 |
+
return c_file
|
| 1540 |
+
else:
|
| 1541 |
+
return None, updated
|
| 1542 |
+
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/setuptools_ext.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
try:
|
| 5 |
+
basestring
|
| 6 |
+
except NameError:
|
| 7 |
+
# Python 3.x
|
| 8 |
+
basestring = str
|
| 9 |
+
|
| 10 |
+
def error(msg):
|
| 11 |
+
from distutils.errors import DistutilsSetupError
|
| 12 |
+
raise DistutilsSetupError(msg)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def execfile(filename, glob):
|
| 16 |
+
# We use execfile() (here rewritten for Python 3) instead of
|
| 17 |
+
# __import__() to load the build script. The problem with
|
| 18 |
+
# a normal import is that in some packages, the intermediate
|
| 19 |
+
# __init__.py files may already try to import the file that
|
| 20 |
+
# we are generating.
|
| 21 |
+
with open(filename) as f:
|
| 22 |
+
src = f.read()
|
| 23 |
+
src += '\n' # Python 2.6 compatibility
|
| 24 |
+
code = compile(src, filename, 'exec')
|
| 25 |
+
exec(code, glob, glob)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def add_cffi_module(dist, mod_spec):
|
| 29 |
+
from cffi.api import FFI
|
| 30 |
+
|
| 31 |
+
if not isinstance(mod_spec, basestring):
|
| 32 |
+
error("argument to 'cffi_modules=...' must be a str or a list of str,"
|
| 33 |
+
" not %r" % (type(mod_spec).__name__,))
|
| 34 |
+
mod_spec = str(mod_spec)
|
| 35 |
+
try:
|
| 36 |
+
build_file_name, ffi_var_name = mod_spec.split(':')
|
| 37 |
+
except ValueError:
|
| 38 |
+
error("%r must be of the form 'path/build.py:ffi_variable'" %
|
| 39 |
+
(mod_spec,))
|
| 40 |
+
if not os.path.exists(build_file_name):
|
| 41 |
+
ext = ''
|
| 42 |
+
rewritten = build_file_name.replace('.', '/') + '.py'
|
| 43 |
+
if os.path.exists(rewritten):
|
| 44 |
+
ext = ' (rewrite cffi_modules to [%r])' % (
|
| 45 |
+
rewritten + ':' + ffi_var_name,)
|
| 46 |
+
error("%r does not name an existing file%s" % (build_file_name, ext))
|
| 47 |
+
|
| 48 |
+
mod_vars = {'__name__': '__cffi__', '__file__': build_file_name}
|
| 49 |
+
execfile(build_file_name, mod_vars)
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
ffi = mod_vars[ffi_var_name]
|
| 53 |
+
except KeyError:
|
| 54 |
+
error("%r: object %r not found in module" % (mod_spec,
|
| 55 |
+
ffi_var_name))
|
| 56 |
+
if not isinstance(ffi, FFI):
|
| 57 |
+
ffi = ffi() # maybe it's a function instead of directly an ffi
|
| 58 |
+
if not isinstance(ffi, FFI):
|
| 59 |
+
error("%r is not an FFI instance (got %r)" % (mod_spec,
|
| 60 |
+
type(ffi).__name__))
|
| 61 |
+
if not hasattr(ffi, '_assigned_source'):
|
| 62 |
+
error("%r: the set_source() method was not called" % (mod_spec,))
|
| 63 |
+
module_name, source, source_extension, kwds = ffi._assigned_source
|
| 64 |
+
if ffi._windows_unicode:
|
| 65 |
+
kwds = kwds.copy()
|
| 66 |
+
ffi._apply_windows_unicode(kwds)
|
| 67 |
+
|
| 68 |
+
if source is None:
|
| 69 |
+
_add_py_module(dist, ffi, module_name)
|
| 70 |
+
else:
|
| 71 |
+
_add_c_module(dist, ffi, module_name, source, source_extension, kwds)
|
| 72 |
+
|
| 73 |
+
def _set_py_limited_api(Extension, kwds):
|
| 74 |
+
"""
|
| 75 |
+
Add py_limited_api to kwds if setuptools >= 26 is in use.
|
| 76 |
+
Do not alter the setting if it already exists.
|
| 77 |
+
Setuptools takes care of ignoring the flag on Python 2 and PyPy.
|
| 78 |
+
|
| 79 |
+
CPython itself should ignore the flag in a debugging version
|
| 80 |
+
(by not listing .abi3.so in the extensions it supports), but
|
| 81 |
+
it doesn't so far, creating troubles. That's why we check
|
| 82 |
+
for "not hasattr(sys, 'gettotalrefcount')" (the 2.7 compatible equivalent
|
| 83 |
+
of 'd' not in sys.abiflags). (http://bugs.python.org/issue28401)
|
| 84 |
+
|
| 85 |
+
On Windows, with CPython <= 3.4, it's better not to use py_limited_api
|
| 86 |
+
because virtualenv *still* doesn't copy PYTHON3.DLL on these versions.
|
| 87 |
+
For now we'll skip py_limited_api on all Windows versions to avoid an
|
| 88 |
+
inconsistent mess.
|
| 89 |
+
"""
|
| 90 |
+
if ('py_limited_api' not in kwds and not hasattr(sys, 'gettotalrefcount')
|
| 91 |
+
and sys.platform != 'win32'):
|
| 92 |
+
import setuptools
|
| 93 |
+
try:
|
| 94 |
+
setuptools_major_version = int(setuptools.__version__.partition('.')[0])
|
| 95 |
+
if setuptools_major_version >= 26:
|
| 96 |
+
kwds['py_limited_api'] = True
|
| 97 |
+
except ValueError: # certain development versions of setuptools
|
| 98 |
+
# If we don't know the version number of setuptools, we
|
| 99 |
+
# try to set 'py_limited_api' anyway. At worst, we get a
|
| 100 |
+
# warning.
|
| 101 |
+
kwds['py_limited_api'] = True
|
| 102 |
+
return kwds
|
| 103 |
+
|
| 104 |
+
def _add_c_module(dist, ffi, module_name, source, source_extension, kwds):
|
| 105 |
+
from distutils.core import Extension
|
| 106 |
+
# We are a setuptools extension. Need this build_ext for py_limited_api.
|
| 107 |
+
from setuptools.command.build_ext import build_ext
|
| 108 |
+
from distutils.dir_util import mkpath
|
| 109 |
+
from distutils import log
|
| 110 |
+
from cffi import recompiler
|
| 111 |
+
|
| 112 |
+
allsources = ['$PLACEHOLDER']
|
| 113 |
+
allsources.extend(kwds.pop('sources', []))
|
| 114 |
+
kwds = _set_py_limited_api(Extension, kwds)
|
| 115 |
+
ext = Extension(name=module_name, sources=allsources, **kwds)
|
| 116 |
+
|
| 117 |
+
def make_mod(tmpdir, pre_run=None):
|
| 118 |
+
c_file = os.path.join(tmpdir, module_name + source_extension)
|
| 119 |
+
log.info("generating cffi module %r" % c_file)
|
| 120 |
+
mkpath(tmpdir)
|
| 121 |
+
# a setuptools-only, API-only hook: called with the "ext" and "ffi"
|
| 122 |
+
# arguments just before we turn the ffi into C code. To use it,
|
| 123 |
+
# subclass the 'distutils.command.build_ext.build_ext' class and
|
| 124 |
+
# add a method 'def pre_run(self, ext, ffi)'.
|
| 125 |
+
if pre_run is not None:
|
| 126 |
+
pre_run(ext, ffi)
|
| 127 |
+
updated = recompiler.make_c_source(ffi, module_name, source, c_file)
|
| 128 |
+
if not updated:
|
| 129 |
+
log.info("already up-to-date")
|
| 130 |
+
return c_file
|
| 131 |
+
|
| 132 |
+
if dist.ext_modules is None:
|
| 133 |
+
dist.ext_modules = []
|
| 134 |
+
dist.ext_modules.append(ext)
|
| 135 |
+
|
| 136 |
+
base_class = dist.cmdclass.get('build_ext', build_ext)
|
| 137 |
+
class build_ext_make_mod(base_class):
|
| 138 |
+
def run(self):
|
| 139 |
+
if ext.sources[0] == '$PLACEHOLDER':
|
| 140 |
+
pre_run = getattr(self, 'pre_run', None)
|
| 141 |
+
ext.sources[0] = make_mod(self.build_temp, pre_run)
|
| 142 |
+
base_class.run(self)
|
| 143 |
+
dist.cmdclass['build_ext'] = build_ext_make_mod
|
| 144 |
+
# NB. multiple runs here will create multiple 'build_ext_make_mod'
|
| 145 |
+
# classes. Even in this case the 'build_ext' command should be
|
| 146 |
+
# run once; but just in case, the logic above does nothing if
|
| 147 |
+
# called again.
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _add_py_module(dist, ffi, module_name):
|
| 151 |
+
from distutils.dir_util import mkpath
|
| 152 |
+
from setuptools.command.build_py import build_py
|
| 153 |
+
from setuptools.command.build_ext import build_ext
|
| 154 |
+
from distutils import log
|
| 155 |
+
from cffi import recompiler
|
| 156 |
+
|
| 157 |
+
def generate_mod(py_file):
|
| 158 |
+
log.info("generating cffi module %r" % py_file)
|
| 159 |
+
mkpath(os.path.dirname(py_file))
|
| 160 |
+
updated = recompiler.make_py_source(ffi, module_name, py_file)
|
| 161 |
+
if not updated:
|
| 162 |
+
log.info("already up-to-date")
|
| 163 |
+
|
| 164 |
+
base_class = dist.cmdclass.get('build_py', build_py)
|
| 165 |
+
class build_py_make_mod(base_class):
|
| 166 |
+
def run(self):
|
| 167 |
+
base_class.run(self)
|
| 168 |
+
module_path = module_name.split('.')
|
| 169 |
+
module_path[-1] += '.py'
|
| 170 |
+
generate_mod(os.path.join(self.build_lib, *module_path))
|
| 171 |
+
def get_source_files(self):
|
| 172 |
+
# This is called from 'setup.py sdist' only. Exclude
|
| 173 |
+
# the generate .py module in this case.
|
| 174 |
+
saved_py_modules = self.py_modules
|
| 175 |
+
try:
|
| 176 |
+
if saved_py_modules:
|
| 177 |
+
self.py_modules = [m for m in saved_py_modules
|
| 178 |
+
if m != module_name]
|
| 179 |
+
return base_class.get_source_files(self)
|
| 180 |
+
finally:
|
| 181 |
+
self.py_modules = saved_py_modules
|
| 182 |
+
dist.cmdclass['build_py'] = build_py_make_mod
|
| 183 |
+
|
| 184 |
+
# distutils and setuptools have no notion I could find of a
|
| 185 |
+
# generated python module. If we don't add module_name to
|
| 186 |
+
# dist.py_modules, then things mostly work but there are some
|
| 187 |
+
# combination of options (--root and --record) that will miss
|
| 188 |
+
# the module. So we add it here, which gives a few apparently
|
| 189 |
+
# harmless warnings about not finding the file outside the
|
| 190 |
+
# build directory.
|
| 191 |
+
# Then we need to hack more in get_source_files(); see above.
|
| 192 |
+
if dist.py_modules is None:
|
| 193 |
+
dist.py_modules = []
|
| 194 |
+
dist.py_modules.append(module_name)
|
| 195 |
+
|
| 196 |
+
# the following is only for "build_ext -i"
|
| 197 |
+
base_class_2 = dist.cmdclass.get('build_ext', build_ext)
|
| 198 |
+
class build_ext_make_mod(base_class_2):
|
| 199 |
+
def run(self):
|
| 200 |
+
base_class_2.run(self)
|
| 201 |
+
if self.inplace:
|
| 202 |
+
# from get_ext_fullpath() in distutils/command/build_ext.py
|
| 203 |
+
module_path = module_name.split('.')
|
| 204 |
+
package = '.'.join(module_path[:-1])
|
| 205 |
+
build_py = self.get_finalized_command('build_py')
|
| 206 |
+
package_dir = build_py.get_package_dir(package)
|
| 207 |
+
file_name = module_path[-1] + '.py'
|
| 208 |
+
generate_mod(os.path.join(package_dir, file_name))
|
| 209 |
+
dist.cmdclass['build_ext'] = build_ext_make_mod
|
| 210 |
+
|
| 211 |
+
def cffi_modules(dist, attr, value):
|
| 212 |
+
assert attr == 'cffi_modules'
|
| 213 |
+
if isinstance(value, basestring):
|
| 214 |
+
value = [value]
|
| 215 |
+
|
| 216 |
+
for cffi_module in value:
|
| 217 |
+
add_cffi_module(dist, cffi_module)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/vengine_cpy.py
ADDED
|
@@ -0,0 +1,1015 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# DEPRECATED: implementation for ffi.verify()
|
| 3 |
+
#
|
| 4 |
+
import sys, imp
|
| 5 |
+
from . import model
|
| 6 |
+
from .error import VerificationError
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class VCPythonEngine(object):
|
| 10 |
+
_class_key = 'x'
|
| 11 |
+
_gen_python_module = True
|
| 12 |
+
|
| 13 |
+
def __init__(self, verifier):
|
| 14 |
+
self.verifier = verifier
|
| 15 |
+
self.ffi = verifier.ffi
|
| 16 |
+
self._struct_pending_verification = {}
|
| 17 |
+
self._types_of_builtin_functions = {}
|
| 18 |
+
|
| 19 |
+
def patch_extension_kwds(self, kwds):
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
def find_module(self, module_name, path, so_suffixes):
|
| 23 |
+
try:
|
| 24 |
+
f, filename, descr = imp.find_module(module_name, path)
|
| 25 |
+
except ImportError:
|
| 26 |
+
return None
|
| 27 |
+
if f is not None:
|
| 28 |
+
f.close()
|
| 29 |
+
# Note that after a setuptools installation, there are both .py
|
| 30 |
+
# and .so files with the same basename. The code here relies on
|
| 31 |
+
# imp.find_module() locating the .so in priority.
|
| 32 |
+
if descr[0] not in so_suffixes:
|
| 33 |
+
return None
|
| 34 |
+
return filename
|
| 35 |
+
|
| 36 |
+
def collect_types(self):
|
| 37 |
+
self._typesdict = {}
|
| 38 |
+
self._generate("collecttype")
|
| 39 |
+
|
| 40 |
+
def _prnt(self, what=''):
|
| 41 |
+
self._f.write(what + '\n')
|
| 42 |
+
|
| 43 |
+
def _gettypenum(self, type):
|
| 44 |
+
# a KeyError here is a bug. please report it! :-)
|
| 45 |
+
return self._typesdict[type]
|
| 46 |
+
|
| 47 |
+
def _do_collect_type(self, tp):
|
| 48 |
+
if ((not isinstance(tp, model.PrimitiveType)
|
| 49 |
+
or tp.name == 'long double')
|
| 50 |
+
and tp not in self._typesdict):
|
| 51 |
+
num = len(self._typesdict)
|
| 52 |
+
self._typesdict[tp] = num
|
| 53 |
+
|
| 54 |
+
def write_source_to_f(self):
|
| 55 |
+
self.collect_types()
|
| 56 |
+
#
|
| 57 |
+
# The new module will have a _cffi_setup() function that receives
|
| 58 |
+
# objects from the ffi world, and that calls some setup code in
|
| 59 |
+
# the module. This setup code is split in several independent
|
| 60 |
+
# functions, e.g. one per constant. The functions are "chained"
|
| 61 |
+
# by ending in a tail call to each other.
|
| 62 |
+
#
|
| 63 |
+
# This is further split in two chained lists, depending on if we
|
| 64 |
+
# can do it at import-time or if we must wait for _cffi_setup() to
|
| 65 |
+
# provide us with the <ctype> objects. This is needed because we
|
| 66 |
+
# need the values of the enum constants in order to build the
|
| 67 |
+
# <ctype 'enum'> that we may have to pass to _cffi_setup().
|
| 68 |
+
#
|
| 69 |
+
# The following two 'chained_list_constants' items contains
|
| 70 |
+
# the head of these two chained lists, as a string that gives the
|
| 71 |
+
# call to do, if any.
|
| 72 |
+
self._chained_list_constants = ['((void)lib,0)', '((void)lib,0)']
|
| 73 |
+
#
|
| 74 |
+
prnt = self._prnt
|
| 75 |
+
# first paste some standard set of lines that are mostly '#define'
|
| 76 |
+
prnt(cffimod_header)
|
| 77 |
+
prnt()
|
| 78 |
+
# then paste the C source given by the user, verbatim.
|
| 79 |
+
prnt(self.verifier.preamble)
|
| 80 |
+
prnt()
|
| 81 |
+
#
|
| 82 |
+
# call generate_cpy_xxx_decl(), for every xxx found from
|
| 83 |
+
# ffi._parser._declarations. This generates all the functions.
|
| 84 |
+
self._generate("decl")
|
| 85 |
+
#
|
| 86 |
+
# implement the function _cffi_setup_custom() as calling the
|
| 87 |
+
# head of the chained list.
|
| 88 |
+
self._generate_setup_custom()
|
| 89 |
+
prnt()
|
| 90 |
+
#
|
| 91 |
+
# produce the method table, including the entries for the
|
| 92 |
+
# generated Python->C function wrappers, which are done
|
| 93 |
+
# by generate_cpy_function_method().
|
| 94 |
+
prnt('static PyMethodDef _cffi_methods[] = {')
|
| 95 |
+
self._generate("method")
|
| 96 |
+
prnt(' {"_cffi_setup", _cffi_setup, METH_VARARGS, NULL},')
|
| 97 |
+
prnt(' {NULL, NULL, 0, NULL} /* Sentinel */')
|
| 98 |
+
prnt('};')
|
| 99 |
+
prnt()
|
| 100 |
+
#
|
| 101 |
+
# standard init.
|
| 102 |
+
modname = self.verifier.get_module_name()
|
| 103 |
+
constants = self._chained_list_constants[False]
|
| 104 |
+
prnt('#if PY_MAJOR_VERSION >= 3')
|
| 105 |
+
prnt()
|
| 106 |
+
prnt('static struct PyModuleDef _cffi_module_def = {')
|
| 107 |
+
prnt(' PyModuleDef_HEAD_INIT,')
|
| 108 |
+
prnt(' "%s",' % modname)
|
| 109 |
+
prnt(' NULL,')
|
| 110 |
+
prnt(' -1,')
|
| 111 |
+
prnt(' _cffi_methods,')
|
| 112 |
+
prnt(' NULL, NULL, NULL, NULL')
|
| 113 |
+
prnt('};')
|
| 114 |
+
prnt()
|
| 115 |
+
prnt('PyMODINIT_FUNC')
|
| 116 |
+
prnt('PyInit_%s(void)' % modname)
|
| 117 |
+
prnt('{')
|
| 118 |
+
prnt(' PyObject *lib;')
|
| 119 |
+
prnt(' lib = PyModule_Create(&_cffi_module_def);')
|
| 120 |
+
prnt(' if (lib == NULL)')
|
| 121 |
+
prnt(' return NULL;')
|
| 122 |
+
prnt(' if (%s < 0 || _cffi_init() < 0) {' % (constants,))
|
| 123 |
+
prnt(' Py_DECREF(lib);')
|
| 124 |
+
prnt(' return NULL;')
|
| 125 |
+
prnt(' }')
|
| 126 |
+
prnt(' return lib;')
|
| 127 |
+
prnt('}')
|
| 128 |
+
prnt()
|
| 129 |
+
prnt('#else')
|
| 130 |
+
prnt()
|
| 131 |
+
prnt('PyMODINIT_FUNC')
|
| 132 |
+
prnt('init%s(void)' % modname)
|
| 133 |
+
prnt('{')
|
| 134 |
+
prnt(' PyObject *lib;')
|
| 135 |
+
prnt(' lib = Py_InitModule("%s", _cffi_methods);' % modname)
|
| 136 |
+
prnt(' if (lib == NULL)')
|
| 137 |
+
prnt(' return;')
|
| 138 |
+
prnt(' if (%s < 0 || _cffi_init() < 0)' % (constants,))
|
| 139 |
+
prnt(' return;')
|
| 140 |
+
prnt(' return;')
|
| 141 |
+
prnt('}')
|
| 142 |
+
prnt()
|
| 143 |
+
prnt('#endif')
|
| 144 |
+
|
| 145 |
+
def load_library(self, flags=None):
|
| 146 |
+
# XXX review all usages of 'self' here!
|
| 147 |
+
# import it as a new extension module
|
| 148 |
+
imp.acquire_lock()
|
| 149 |
+
try:
|
| 150 |
+
if hasattr(sys, "getdlopenflags"):
|
| 151 |
+
previous_flags = sys.getdlopenflags()
|
| 152 |
+
try:
|
| 153 |
+
if hasattr(sys, "setdlopenflags") and flags is not None:
|
| 154 |
+
sys.setdlopenflags(flags)
|
| 155 |
+
module = imp.load_dynamic(self.verifier.get_module_name(),
|
| 156 |
+
self.verifier.modulefilename)
|
| 157 |
+
except ImportError as e:
|
| 158 |
+
error = "importing %r: %s" % (self.verifier.modulefilename, e)
|
| 159 |
+
raise VerificationError(error)
|
| 160 |
+
finally:
|
| 161 |
+
if hasattr(sys, "setdlopenflags"):
|
| 162 |
+
sys.setdlopenflags(previous_flags)
|
| 163 |
+
finally:
|
| 164 |
+
imp.release_lock()
|
| 165 |
+
#
|
| 166 |
+
# call loading_cpy_struct() to get the struct layout inferred by
|
| 167 |
+
# the C compiler
|
| 168 |
+
self._load(module, 'loading')
|
| 169 |
+
#
|
| 170 |
+
# the C code will need the <ctype> objects. Collect them in
|
| 171 |
+
# order in a list.
|
| 172 |
+
revmapping = dict([(value, key)
|
| 173 |
+
for (key, value) in self._typesdict.items()])
|
| 174 |
+
lst = [revmapping[i] for i in range(len(revmapping))]
|
| 175 |
+
lst = list(map(self.ffi._get_cached_btype, lst))
|
| 176 |
+
#
|
| 177 |
+
# build the FFILibrary class and instance and call _cffi_setup().
|
| 178 |
+
# this will set up some fields like '_cffi_types', and only then
|
| 179 |
+
# it will invoke the chained list of functions that will really
|
| 180 |
+
# build (notably) the constant objects, as <cdata> if they are
|
| 181 |
+
# pointers, and store them as attributes on the 'library' object.
|
| 182 |
+
class FFILibrary(object):
|
| 183 |
+
_cffi_python_module = module
|
| 184 |
+
_cffi_ffi = self.ffi
|
| 185 |
+
_cffi_dir = []
|
| 186 |
+
def __dir__(self):
|
| 187 |
+
return FFILibrary._cffi_dir + list(self.__dict__)
|
| 188 |
+
library = FFILibrary()
|
| 189 |
+
if module._cffi_setup(lst, VerificationError, library):
|
| 190 |
+
import warnings
|
| 191 |
+
warnings.warn("reimporting %r might overwrite older definitions"
|
| 192 |
+
% (self.verifier.get_module_name()))
|
| 193 |
+
#
|
| 194 |
+
# finally, call the loaded_cpy_xxx() functions. This will perform
|
| 195 |
+
# the final adjustments, like copying the Python->C wrapper
|
| 196 |
+
# functions from the module to the 'library' object, and setting
|
| 197 |
+
# up the FFILibrary class with properties for the global C variables.
|
| 198 |
+
self._load(module, 'loaded', library=library)
|
| 199 |
+
module._cffi_original_ffi = self.ffi
|
| 200 |
+
module._cffi_types_of_builtin_funcs = self._types_of_builtin_functions
|
| 201 |
+
return library
|
| 202 |
+
|
| 203 |
+
def _get_declarations(self):
|
| 204 |
+
lst = [(key, tp) for (key, (tp, qual)) in
|
| 205 |
+
self.ffi._parser._declarations.items()]
|
| 206 |
+
lst.sort()
|
| 207 |
+
return lst
|
| 208 |
+
|
| 209 |
+
def _generate(self, step_name):
|
| 210 |
+
for name, tp in self._get_declarations():
|
| 211 |
+
kind, realname = name.split(' ', 1)
|
| 212 |
+
try:
|
| 213 |
+
method = getattr(self, '_generate_cpy_%s_%s' % (kind,
|
| 214 |
+
step_name))
|
| 215 |
+
except AttributeError:
|
| 216 |
+
raise VerificationError(
|
| 217 |
+
"not implemented in verify(): %r" % name)
|
| 218 |
+
try:
|
| 219 |
+
method(tp, realname)
|
| 220 |
+
except Exception as e:
|
| 221 |
+
model.attach_exception_info(e, name)
|
| 222 |
+
raise
|
| 223 |
+
|
| 224 |
+
def _load(self, module, step_name, **kwds):
|
| 225 |
+
for name, tp in self._get_declarations():
|
| 226 |
+
kind, realname = name.split(' ', 1)
|
| 227 |
+
method = getattr(self, '_%s_cpy_%s' % (step_name, kind))
|
| 228 |
+
try:
|
| 229 |
+
method(tp, realname, module, **kwds)
|
| 230 |
+
except Exception as e:
|
| 231 |
+
model.attach_exception_info(e, name)
|
| 232 |
+
raise
|
| 233 |
+
|
| 234 |
+
def _generate_nothing(self, tp, name):
|
| 235 |
+
pass
|
| 236 |
+
|
| 237 |
+
def _loaded_noop(self, tp, name, module, **kwds):
|
| 238 |
+
pass
|
| 239 |
+
|
| 240 |
+
# ----------
|
| 241 |
+
|
| 242 |
+
def _convert_funcarg_to_c(self, tp, fromvar, tovar, errcode):
|
| 243 |
+
extraarg = ''
|
| 244 |
+
if isinstance(tp, model.PrimitiveType):
|
| 245 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
| 246 |
+
converter = '_cffi_to_c_int'
|
| 247 |
+
extraarg = ', %s' % tp.name
|
| 248 |
+
else:
|
| 249 |
+
converter = '(%s)_cffi_to_c_%s' % (tp.get_c_name(''),
|
| 250 |
+
tp.name.replace(' ', '_'))
|
| 251 |
+
errvalue = '-1'
|
| 252 |
+
#
|
| 253 |
+
elif isinstance(tp, model.PointerType):
|
| 254 |
+
self._convert_funcarg_to_c_ptr_or_array(tp, fromvar,
|
| 255 |
+
tovar, errcode)
|
| 256 |
+
return
|
| 257 |
+
#
|
| 258 |
+
elif isinstance(tp, (model.StructOrUnion, model.EnumType)):
|
| 259 |
+
# a struct (not a struct pointer) as a function argument
|
| 260 |
+
self._prnt(' if (_cffi_to_c((char *)&%s, _cffi_type(%d), %s) < 0)'
|
| 261 |
+
% (tovar, self._gettypenum(tp), fromvar))
|
| 262 |
+
self._prnt(' %s;' % errcode)
|
| 263 |
+
return
|
| 264 |
+
#
|
| 265 |
+
elif isinstance(tp, model.FunctionPtrType):
|
| 266 |
+
converter = '(%s)_cffi_to_c_pointer' % tp.get_c_name('')
|
| 267 |
+
extraarg = ', _cffi_type(%d)' % self._gettypenum(tp)
|
| 268 |
+
errvalue = 'NULL'
|
| 269 |
+
#
|
| 270 |
+
else:
|
| 271 |
+
raise NotImplementedError(tp)
|
| 272 |
+
#
|
| 273 |
+
self._prnt(' %s = %s(%s%s);' % (tovar, converter, fromvar, extraarg))
|
| 274 |
+
self._prnt(' if (%s == (%s)%s && PyErr_Occurred())' % (
|
| 275 |
+
tovar, tp.get_c_name(''), errvalue))
|
| 276 |
+
self._prnt(' %s;' % errcode)
|
| 277 |
+
|
| 278 |
+
def _extra_local_variables(self, tp, localvars):
|
| 279 |
+
if isinstance(tp, model.PointerType):
|
| 280 |
+
localvars.add('Py_ssize_t datasize')
|
| 281 |
+
|
| 282 |
+
def _convert_funcarg_to_c_ptr_or_array(self, tp, fromvar, tovar, errcode):
|
| 283 |
+
self._prnt(' datasize = _cffi_prepare_pointer_call_argument(')
|
| 284 |
+
self._prnt(' _cffi_type(%d), %s, (char **)&%s);' % (
|
| 285 |
+
self._gettypenum(tp), fromvar, tovar))
|
| 286 |
+
self._prnt(' if (datasize != 0) {')
|
| 287 |
+
self._prnt(' if (datasize < 0)')
|
| 288 |
+
self._prnt(' %s;' % errcode)
|
| 289 |
+
self._prnt(' %s = alloca((size_t)datasize);' % (tovar,))
|
| 290 |
+
self._prnt(' memset((void *)%s, 0, (size_t)datasize);' % (tovar,))
|
| 291 |
+
self._prnt(' if (_cffi_convert_array_from_object('
|
| 292 |
+
'(char *)%s, _cffi_type(%d), %s) < 0)' % (
|
| 293 |
+
tovar, self._gettypenum(tp), fromvar))
|
| 294 |
+
self._prnt(' %s;' % errcode)
|
| 295 |
+
self._prnt(' }')
|
| 296 |
+
|
| 297 |
+
def _convert_expr_from_c(self, tp, var, context):
|
| 298 |
+
if isinstance(tp, model.PrimitiveType):
|
| 299 |
+
if tp.is_integer_type() and tp.name != '_Bool':
|
| 300 |
+
return '_cffi_from_c_int(%s, %s)' % (var, tp.name)
|
| 301 |
+
elif tp.name != 'long double':
|
| 302 |
+
return '_cffi_from_c_%s(%s)' % (tp.name.replace(' ', '_'), var)
|
| 303 |
+
else:
|
| 304 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
| 305 |
+
var, self._gettypenum(tp))
|
| 306 |
+
elif isinstance(tp, (model.PointerType, model.FunctionPtrType)):
|
| 307 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
| 308 |
+
var, self._gettypenum(tp))
|
| 309 |
+
elif isinstance(tp, model.ArrayType):
|
| 310 |
+
return '_cffi_from_c_pointer((char *)%s, _cffi_type(%d))' % (
|
| 311 |
+
var, self._gettypenum(model.PointerType(tp.item)))
|
| 312 |
+
elif isinstance(tp, model.StructOrUnion):
|
| 313 |
+
if tp.fldnames is None:
|
| 314 |
+
raise TypeError("'%s' is used as %s, but is opaque" % (
|
| 315 |
+
tp._get_c_name(), context))
|
| 316 |
+
return '_cffi_from_c_struct((char *)&%s, _cffi_type(%d))' % (
|
| 317 |
+
var, self._gettypenum(tp))
|
| 318 |
+
elif isinstance(tp, model.EnumType):
|
| 319 |
+
return '_cffi_from_c_deref((char *)&%s, _cffi_type(%d))' % (
|
| 320 |
+
var, self._gettypenum(tp))
|
| 321 |
+
else:
|
| 322 |
+
raise NotImplementedError(tp)
|
| 323 |
+
|
| 324 |
+
# ----------
|
| 325 |
+
# typedefs: generates no code so far
|
| 326 |
+
|
| 327 |
+
_generate_cpy_typedef_collecttype = _generate_nothing
|
| 328 |
+
_generate_cpy_typedef_decl = _generate_nothing
|
| 329 |
+
_generate_cpy_typedef_method = _generate_nothing
|
| 330 |
+
_loading_cpy_typedef = _loaded_noop
|
| 331 |
+
_loaded_cpy_typedef = _loaded_noop
|
| 332 |
+
|
| 333 |
+
# ----------
|
| 334 |
+
# function declarations
|
| 335 |
+
|
| 336 |
+
def _generate_cpy_function_collecttype(self, tp, name):
|
| 337 |
+
assert isinstance(tp, model.FunctionPtrType)
|
| 338 |
+
if tp.ellipsis:
|
| 339 |
+
self._do_collect_type(tp)
|
| 340 |
+
else:
|
| 341 |
+
# don't call _do_collect_type(tp) in this common case,
|
| 342 |
+
# otherwise test_autofilled_struct_as_argument fails
|
| 343 |
+
for type in tp.args:
|
| 344 |
+
self._do_collect_type(type)
|
| 345 |
+
self._do_collect_type(tp.result)
|
| 346 |
+
|
| 347 |
+
def _generate_cpy_function_decl(self, tp, name):
|
| 348 |
+
assert isinstance(tp, model.FunctionPtrType)
|
| 349 |
+
if tp.ellipsis:
|
| 350 |
+
# cannot support vararg functions better than this: check for its
|
| 351 |
+
# exact type (including the fixed arguments), and build it as a
|
| 352 |
+
# constant function pointer (no CPython wrapper)
|
| 353 |
+
self._generate_cpy_const(False, name, tp)
|
| 354 |
+
return
|
| 355 |
+
prnt = self._prnt
|
| 356 |
+
numargs = len(tp.args)
|
| 357 |
+
if numargs == 0:
|
| 358 |
+
argname = 'noarg'
|
| 359 |
+
elif numargs == 1:
|
| 360 |
+
argname = 'arg0'
|
| 361 |
+
else:
|
| 362 |
+
argname = 'args'
|
| 363 |
+
prnt('static PyObject *')
|
| 364 |
+
prnt('_cffi_f_%s(PyObject *self, PyObject *%s)' % (name, argname))
|
| 365 |
+
prnt('{')
|
| 366 |
+
#
|
| 367 |
+
context = 'argument of %s' % name
|
| 368 |
+
for i, type in enumerate(tp.args):
|
| 369 |
+
prnt(' %s;' % type.get_c_name(' x%d' % i, context))
|
| 370 |
+
#
|
| 371 |
+
localvars = set()
|
| 372 |
+
for type in tp.args:
|
| 373 |
+
self._extra_local_variables(type, localvars)
|
| 374 |
+
for decl in localvars:
|
| 375 |
+
prnt(' %s;' % (decl,))
|
| 376 |
+
#
|
| 377 |
+
if not isinstance(tp.result, model.VoidType):
|
| 378 |
+
result_code = 'result = '
|
| 379 |
+
context = 'result of %s' % name
|
| 380 |
+
prnt(' %s;' % tp.result.get_c_name(' result', context))
|
| 381 |
+
else:
|
| 382 |
+
result_code = ''
|
| 383 |
+
#
|
| 384 |
+
if len(tp.args) > 1:
|
| 385 |
+
rng = range(len(tp.args))
|
| 386 |
+
for i in rng:
|
| 387 |
+
prnt(' PyObject *arg%d;' % i)
|
| 388 |
+
prnt()
|
| 389 |
+
prnt(' if (!PyArg_ParseTuple(args, "%s:%s", %s))' % (
|
| 390 |
+
'O' * numargs, name, ', '.join(['&arg%d' % i for i in rng])))
|
| 391 |
+
prnt(' return NULL;')
|
| 392 |
+
prnt()
|
| 393 |
+
#
|
| 394 |
+
for i, type in enumerate(tp.args):
|
| 395 |
+
self._convert_funcarg_to_c(type, 'arg%d' % i, 'x%d' % i,
|
| 396 |
+
'return NULL')
|
| 397 |
+
prnt()
|
| 398 |
+
#
|
| 399 |
+
prnt(' Py_BEGIN_ALLOW_THREADS')
|
| 400 |
+
prnt(' _cffi_restore_errno();')
|
| 401 |
+
prnt(' { %s%s(%s); }' % (
|
| 402 |
+
result_code, name,
|
| 403 |
+
', '.join(['x%d' % i for i in range(len(tp.args))])))
|
| 404 |
+
prnt(' _cffi_save_errno();')
|
| 405 |
+
prnt(' Py_END_ALLOW_THREADS')
|
| 406 |
+
prnt()
|
| 407 |
+
#
|
| 408 |
+
prnt(' (void)self; /* unused */')
|
| 409 |
+
if numargs == 0:
|
| 410 |
+
prnt(' (void)noarg; /* unused */')
|
| 411 |
+
if result_code:
|
| 412 |
+
prnt(' return %s;' %
|
| 413 |
+
self._convert_expr_from_c(tp.result, 'result', 'result type'))
|
| 414 |
+
else:
|
| 415 |
+
prnt(' Py_INCREF(Py_None);')
|
| 416 |
+
prnt(' return Py_None;')
|
| 417 |
+
prnt('}')
|
| 418 |
+
prnt()
|
| 419 |
+
|
| 420 |
+
def _generate_cpy_function_method(self, tp, name):
|
| 421 |
+
if tp.ellipsis:
|
| 422 |
+
return
|
| 423 |
+
numargs = len(tp.args)
|
| 424 |
+
if numargs == 0:
|
| 425 |
+
meth = 'METH_NOARGS'
|
| 426 |
+
elif numargs == 1:
|
| 427 |
+
meth = 'METH_O'
|
| 428 |
+
else:
|
| 429 |
+
meth = 'METH_VARARGS'
|
| 430 |
+
self._prnt(' {"%s", _cffi_f_%s, %s, NULL},' % (name, name, meth))
|
| 431 |
+
|
| 432 |
+
_loading_cpy_function = _loaded_noop
|
| 433 |
+
|
| 434 |
+
def _loaded_cpy_function(self, tp, name, module, library):
|
| 435 |
+
if tp.ellipsis:
|
| 436 |
+
return
|
| 437 |
+
func = getattr(module, name)
|
| 438 |
+
setattr(library, name, func)
|
| 439 |
+
self._types_of_builtin_functions[func] = tp
|
| 440 |
+
|
| 441 |
+
# ----------
|
| 442 |
+
# named structs
|
| 443 |
+
|
| 444 |
+
_generate_cpy_struct_collecttype = _generate_nothing
|
| 445 |
+
def _generate_cpy_struct_decl(self, tp, name):
|
| 446 |
+
assert name == tp.name
|
| 447 |
+
self._generate_struct_or_union_decl(tp, 'struct', name)
|
| 448 |
+
def _generate_cpy_struct_method(self, tp, name):
|
| 449 |
+
self._generate_struct_or_union_method(tp, 'struct', name)
|
| 450 |
+
def _loading_cpy_struct(self, tp, name, module):
|
| 451 |
+
self._loading_struct_or_union(tp, 'struct', name, module)
|
| 452 |
+
def _loaded_cpy_struct(self, tp, name, module, **kwds):
|
| 453 |
+
self._loaded_struct_or_union(tp)
|
| 454 |
+
|
| 455 |
+
_generate_cpy_union_collecttype = _generate_nothing
|
| 456 |
+
def _generate_cpy_union_decl(self, tp, name):
|
| 457 |
+
assert name == tp.name
|
| 458 |
+
self._generate_struct_or_union_decl(tp, 'union', name)
|
| 459 |
+
def _generate_cpy_union_method(self, tp, name):
|
| 460 |
+
self._generate_struct_or_union_method(tp, 'union', name)
|
| 461 |
+
def _loading_cpy_union(self, tp, name, module):
|
| 462 |
+
self._loading_struct_or_union(tp, 'union', name, module)
|
| 463 |
+
def _loaded_cpy_union(self, tp, name, module, **kwds):
|
| 464 |
+
self._loaded_struct_or_union(tp)
|
| 465 |
+
|
| 466 |
+
def _generate_struct_or_union_decl(self, tp, prefix, name):
|
| 467 |
+
if tp.fldnames is None:
|
| 468 |
+
return # nothing to do with opaque structs
|
| 469 |
+
checkfuncname = '_cffi_check_%s_%s' % (prefix, name)
|
| 470 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
| 471 |
+
cname = ('%s %s' % (prefix, name)).strip()
|
| 472 |
+
#
|
| 473 |
+
prnt = self._prnt
|
| 474 |
+
prnt('static void %s(%s *p)' % (checkfuncname, cname))
|
| 475 |
+
prnt('{')
|
| 476 |
+
prnt(' /* only to generate compile-time warnings or errors */')
|
| 477 |
+
prnt(' (void)p;')
|
| 478 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
| 479 |
+
if (isinstance(ftype, model.PrimitiveType)
|
| 480 |
+
and ftype.is_integer_type()) or fbitsize >= 0:
|
| 481 |
+
# accept all integers, but complain on float or double
|
| 482 |
+
prnt(' (void)((p->%s) << 1);' % fname)
|
| 483 |
+
else:
|
| 484 |
+
# only accept exactly the type declared.
|
| 485 |
+
try:
|
| 486 |
+
prnt(' { %s = &p->%s; (void)tmp; }' % (
|
| 487 |
+
ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),
|
| 488 |
+
fname))
|
| 489 |
+
except VerificationError as e:
|
| 490 |
+
prnt(' /* %s */' % str(e)) # cannot verify it, ignore
|
| 491 |
+
prnt('}')
|
| 492 |
+
prnt('static PyObject *')
|
| 493 |
+
prnt('%s(PyObject *self, PyObject *noarg)' % (layoutfuncname,))
|
| 494 |
+
prnt('{')
|
| 495 |
+
prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname)
|
| 496 |
+
prnt(' static Py_ssize_t nums[] = {')
|
| 497 |
+
prnt(' sizeof(%s),' % cname)
|
| 498 |
+
prnt(' offsetof(struct _cffi_aligncheck, y),')
|
| 499 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
| 500 |
+
if fbitsize >= 0:
|
| 501 |
+
continue # xxx ignore fbitsize for now
|
| 502 |
+
prnt(' offsetof(%s, %s),' % (cname, fname))
|
| 503 |
+
if isinstance(ftype, model.ArrayType) and ftype.length is None:
|
| 504 |
+
prnt(' 0, /* %s */' % ftype._get_c_name())
|
| 505 |
+
else:
|
| 506 |
+
prnt(' sizeof(((%s *)0)->%s),' % (cname, fname))
|
| 507 |
+
prnt(' -1')
|
| 508 |
+
prnt(' };')
|
| 509 |
+
prnt(' (void)self; /* unused */')
|
| 510 |
+
prnt(' (void)noarg; /* unused */')
|
| 511 |
+
prnt(' return _cffi_get_struct_layout(nums);')
|
| 512 |
+
prnt(' /* the next line is not executed, but compiled */')
|
| 513 |
+
prnt(' %s(0);' % (checkfuncname,))
|
| 514 |
+
prnt('}')
|
| 515 |
+
prnt()
|
| 516 |
+
|
| 517 |
+
def _generate_struct_or_union_method(self, tp, prefix, name):
|
| 518 |
+
if tp.fldnames is None:
|
| 519 |
+
return # nothing to do with opaque structs
|
| 520 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
| 521 |
+
self._prnt(' {"%s", %s, METH_NOARGS, NULL},' % (layoutfuncname,
|
| 522 |
+
layoutfuncname))
|
| 523 |
+
|
| 524 |
+
def _loading_struct_or_union(self, tp, prefix, name, module):
|
| 525 |
+
if tp.fldnames is None:
|
| 526 |
+
return # nothing to do with opaque structs
|
| 527 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
| 528 |
+
#
|
| 529 |
+
function = getattr(module, layoutfuncname)
|
| 530 |
+
layout = function()
|
| 531 |
+
if isinstance(tp, model.StructOrUnion) and tp.partial:
|
| 532 |
+
# use the function()'s sizes and offsets to guide the
|
| 533 |
+
# layout of the struct
|
| 534 |
+
totalsize = layout[0]
|
| 535 |
+
totalalignment = layout[1]
|
| 536 |
+
fieldofs = layout[2::2]
|
| 537 |
+
fieldsize = layout[3::2]
|
| 538 |
+
tp.force_flatten()
|
| 539 |
+
assert len(fieldofs) == len(fieldsize) == len(tp.fldnames)
|
| 540 |
+
tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment
|
| 541 |
+
else:
|
| 542 |
+
cname = ('%s %s' % (prefix, name)).strip()
|
| 543 |
+
self._struct_pending_verification[tp] = layout, cname
|
| 544 |
+
|
| 545 |
+
def _loaded_struct_or_union(self, tp):
|
| 546 |
+
if tp.fldnames is None:
|
| 547 |
+
return # nothing to do with opaque structs
|
| 548 |
+
self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered
|
| 549 |
+
|
| 550 |
+
if tp in self._struct_pending_verification:
|
| 551 |
+
# check that the layout sizes and offsets match the real ones
|
| 552 |
+
def check(realvalue, expectedvalue, msg):
|
| 553 |
+
if realvalue != expectedvalue:
|
| 554 |
+
raise VerificationError(
|
| 555 |
+
"%s (we have %d, but C compiler says %d)"
|
| 556 |
+
% (msg, expectedvalue, realvalue))
|
| 557 |
+
ffi = self.ffi
|
| 558 |
+
BStruct = ffi._get_cached_btype(tp)
|
| 559 |
+
layout, cname = self._struct_pending_verification.pop(tp)
|
| 560 |
+
check(layout[0], ffi.sizeof(BStruct), "wrong total size")
|
| 561 |
+
check(layout[1], ffi.alignof(BStruct), "wrong total alignment")
|
| 562 |
+
i = 2
|
| 563 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
| 564 |
+
if fbitsize >= 0:
|
| 565 |
+
continue # xxx ignore fbitsize for now
|
| 566 |
+
check(layout[i], ffi.offsetof(BStruct, fname),
|
| 567 |
+
"wrong offset for field %r" % (fname,))
|
| 568 |
+
if layout[i+1] != 0:
|
| 569 |
+
BField = ffi._get_cached_btype(ftype)
|
| 570 |
+
check(layout[i+1], ffi.sizeof(BField),
|
| 571 |
+
"wrong size for field %r" % (fname,))
|
| 572 |
+
i += 2
|
| 573 |
+
assert i == len(layout)
|
| 574 |
+
|
| 575 |
+
# ----------
|
| 576 |
+
# 'anonymous' declarations. These are produced for anonymous structs
|
| 577 |
+
# or unions; the 'name' is obtained by a typedef.
|
| 578 |
+
|
| 579 |
+
_generate_cpy_anonymous_collecttype = _generate_nothing
|
| 580 |
+
|
| 581 |
+
def _generate_cpy_anonymous_decl(self, tp, name):
|
| 582 |
+
if isinstance(tp, model.EnumType):
|
| 583 |
+
self._generate_cpy_enum_decl(tp, name, '')
|
| 584 |
+
else:
|
| 585 |
+
self._generate_struct_or_union_decl(tp, '', name)
|
| 586 |
+
|
| 587 |
+
def _generate_cpy_anonymous_method(self, tp, name):
|
| 588 |
+
if not isinstance(tp, model.EnumType):
|
| 589 |
+
self._generate_struct_or_union_method(tp, '', name)
|
| 590 |
+
|
| 591 |
+
def _loading_cpy_anonymous(self, tp, name, module):
|
| 592 |
+
if isinstance(tp, model.EnumType):
|
| 593 |
+
self._loading_cpy_enum(tp, name, module)
|
| 594 |
+
else:
|
| 595 |
+
self._loading_struct_or_union(tp, '', name, module)
|
| 596 |
+
|
| 597 |
+
def _loaded_cpy_anonymous(self, tp, name, module, **kwds):
|
| 598 |
+
if isinstance(tp, model.EnumType):
|
| 599 |
+
self._loaded_cpy_enum(tp, name, module, **kwds)
|
| 600 |
+
else:
|
| 601 |
+
self._loaded_struct_or_union(tp)
|
| 602 |
+
|
| 603 |
+
# ----------
|
| 604 |
+
# constants, likely declared with '#define'
|
| 605 |
+
|
| 606 |
+
def _generate_cpy_const(self, is_int, name, tp=None, category='const',
|
| 607 |
+
vartp=None, delayed=True, size_too=False,
|
| 608 |
+
check_value=None):
|
| 609 |
+
prnt = self._prnt
|
| 610 |
+
funcname = '_cffi_%s_%s' % (category, name)
|
| 611 |
+
prnt('static int %s(PyObject *lib)' % funcname)
|
| 612 |
+
prnt('{')
|
| 613 |
+
prnt(' PyObject *o;')
|
| 614 |
+
prnt(' int res;')
|
| 615 |
+
if not is_int:
|
| 616 |
+
prnt(' %s;' % (vartp or tp).get_c_name(' i', name))
|
| 617 |
+
else:
|
| 618 |
+
assert category == 'const'
|
| 619 |
+
#
|
| 620 |
+
if check_value is not None:
|
| 621 |
+
self._check_int_constant_value(name, check_value)
|
| 622 |
+
#
|
| 623 |
+
if not is_int:
|
| 624 |
+
if category == 'var':
|
| 625 |
+
realexpr = '&' + name
|
| 626 |
+
else:
|
| 627 |
+
realexpr = name
|
| 628 |
+
prnt(' i = (%s);' % (realexpr,))
|
| 629 |
+
prnt(' o = %s;' % (self._convert_expr_from_c(tp, 'i',
|
| 630 |
+
'variable type'),))
|
| 631 |
+
assert delayed
|
| 632 |
+
else:
|
| 633 |
+
prnt(' o = _cffi_from_c_int_const(%s);' % name)
|
| 634 |
+
prnt(' if (o == NULL)')
|
| 635 |
+
prnt(' return -1;')
|
| 636 |
+
if size_too:
|
| 637 |
+
prnt(' {')
|
| 638 |
+
prnt(' PyObject *o1 = o;')
|
| 639 |
+
prnt(' o = Py_BuildValue("On", o1, (Py_ssize_t)sizeof(%s));'
|
| 640 |
+
% (name,))
|
| 641 |
+
prnt(' Py_DECREF(o1);')
|
| 642 |
+
prnt(' if (o == NULL)')
|
| 643 |
+
prnt(' return -1;')
|
| 644 |
+
prnt(' }')
|
| 645 |
+
prnt(' res = PyObject_SetAttrString(lib, "%s", o);' % name)
|
| 646 |
+
prnt(' Py_DECREF(o);')
|
| 647 |
+
prnt(' if (res < 0)')
|
| 648 |
+
prnt(' return -1;')
|
| 649 |
+
prnt(' return %s;' % self._chained_list_constants[delayed])
|
| 650 |
+
self._chained_list_constants[delayed] = funcname + '(lib)'
|
| 651 |
+
prnt('}')
|
| 652 |
+
prnt()
|
| 653 |
+
|
| 654 |
+
def _generate_cpy_constant_collecttype(self, tp, name):
|
| 655 |
+
is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
|
| 656 |
+
if not is_int:
|
| 657 |
+
self._do_collect_type(tp)
|
| 658 |
+
|
| 659 |
+
def _generate_cpy_constant_decl(self, tp, name):
|
| 660 |
+
is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
|
| 661 |
+
self._generate_cpy_const(is_int, name, tp)
|
| 662 |
+
|
| 663 |
+
_generate_cpy_constant_method = _generate_nothing
|
| 664 |
+
_loading_cpy_constant = _loaded_noop
|
| 665 |
+
_loaded_cpy_constant = _loaded_noop
|
| 666 |
+
|
| 667 |
+
# ----------
|
| 668 |
+
# enums
|
| 669 |
+
|
| 670 |
+
def _check_int_constant_value(self, name, value, err_prefix=''):
|
| 671 |
+
prnt = self._prnt
|
| 672 |
+
if value <= 0:
|
| 673 |
+
prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % (
|
| 674 |
+
name, name, value))
|
| 675 |
+
else:
|
| 676 |
+
prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % (
|
| 677 |
+
name, name, value))
|
| 678 |
+
prnt(' char buf[64];')
|
| 679 |
+
prnt(' if ((%s) <= 0)' % name)
|
| 680 |
+
prnt(' snprintf(buf, 63, "%%ld", (long)(%s));' % name)
|
| 681 |
+
prnt(' else')
|
| 682 |
+
prnt(' snprintf(buf, 63, "%%lu", (unsigned long)(%s));' %
|
| 683 |
+
name)
|
| 684 |
+
prnt(' PyErr_Format(_cffi_VerificationError,')
|
| 685 |
+
prnt(' "%s%s has the real value %s, not %s",')
|
| 686 |
+
prnt(' "%s", "%s", buf, "%d");' % (
|
| 687 |
+
err_prefix, name, value))
|
| 688 |
+
prnt(' return -1;')
|
| 689 |
+
prnt(' }')
|
| 690 |
+
|
| 691 |
+
def _enum_funcname(self, prefix, name):
|
| 692 |
+
# "$enum_$1" => "___D_enum____D_1"
|
| 693 |
+
name = name.replace('$', '___D_')
|
| 694 |
+
return '_cffi_e_%s_%s' % (prefix, name)
|
| 695 |
+
|
| 696 |
+
def _generate_cpy_enum_decl(self, tp, name, prefix='enum'):
|
| 697 |
+
if tp.partial:
|
| 698 |
+
for enumerator in tp.enumerators:
|
| 699 |
+
self._generate_cpy_const(True, enumerator, delayed=False)
|
| 700 |
+
return
|
| 701 |
+
#
|
| 702 |
+
funcname = self._enum_funcname(prefix, name)
|
| 703 |
+
prnt = self._prnt
|
| 704 |
+
prnt('static int %s(PyObject *lib)' % funcname)
|
| 705 |
+
prnt('{')
|
| 706 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
| 707 |
+
self._check_int_constant_value(enumerator, enumvalue,
|
| 708 |
+
"enum %s: " % name)
|
| 709 |
+
prnt(' return %s;' % self._chained_list_constants[True])
|
| 710 |
+
self._chained_list_constants[True] = funcname + '(lib)'
|
| 711 |
+
prnt('}')
|
| 712 |
+
prnt()
|
| 713 |
+
|
| 714 |
+
_generate_cpy_enum_collecttype = _generate_nothing
|
| 715 |
+
_generate_cpy_enum_method = _generate_nothing
|
| 716 |
+
|
| 717 |
+
def _loading_cpy_enum(self, tp, name, module):
|
| 718 |
+
if tp.partial:
|
| 719 |
+
enumvalues = [getattr(module, enumerator)
|
| 720 |
+
for enumerator in tp.enumerators]
|
| 721 |
+
tp.enumvalues = tuple(enumvalues)
|
| 722 |
+
tp.partial_resolved = True
|
| 723 |
+
|
| 724 |
+
def _loaded_cpy_enum(self, tp, name, module, library):
|
| 725 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
| 726 |
+
setattr(library, enumerator, enumvalue)
|
| 727 |
+
|
| 728 |
+
# ----------
|
| 729 |
+
# macros: for now only for integers
|
| 730 |
+
|
| 731 |
+
def _generate_cpy_macro_decl(self, tp, name):
|
| 732 |
+
if tp == '...':
|
| 733 |
+
check_value = None
|
| 734 |
+
else:
|
| 735 |
+
check_value = tp # an integer
|
| 736 |
+
self._generate_cpy_const(True, name, check_value=check_value)
|
| 737 |
+
|
| 738 |
+
_generate_cpy_macro_collecttype = _generate_nothing
|
| 739 |
+
_generate_cpy_macro_method = _generate_nothing
|
| 740 |
+
_loading_cpy_macro = _loaded_noop
|
| 741 |
+
_loaded_cpy_macro = _loaded_noop
|
| 742 |
+
|
| 743 |
+
# ----------
|
| 744 |
+
# global variables
|
| 745 |
+
|
| 746 |
+
def _generate_cpy_variable_collecttype(self, tp, name):
|
| 747 |
+
if isinstance(tp, model.ArrayType):
|
| 748 |
+
tp_ptr = model.PointerType(tp.item)
|
| 749 |
+
else:
|
| 750 |
+
tp_ptr = model.PointerType(tp)
|
| 751 |
+
self._do_collect_type(tp_ptr)
|
| 752 |
+
|
| 753 |
+
def _generate_cpy_variable_decl(self, tp, name):
|
| 754 |
+
if isinstance(tp, model.ArrayType):
|
| 755 |
+
tp_ptr = model.PointerType(tp.item)
|
| 756 |
+
self._generate_cpy_const(False, name, tp, vartp=tp_ptr,
|
| 757 |
+
size_too = (tp.length == '...'))
|
| 758 |
+
else:
|
| 759 |
+
tp_ptr = model.PointerType(tp)
|
| 760 |
+
self._generate_cpy_const(False, name, tp_ptr, category='var')
|
| 761 |
+
|
| 762 |
+
_generate_cpy_variable_method = _generate_nothing
|
| 763 |
+
_loading_cpy_variable = _loaded_noop
|
| 764 |
+
|
| 765 |
+
def _loaded_cpy_variable(self, tp, name, module, library):
|
| 766 |
+
value = getattr(library, name)
|
| 767 |
+
if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the
|
| 768 |
+
# sense that "a=..." is forbidden
|
| 769 |
+
if tp.length == '...':
|
| 770 |
+
assert isinstance(value, tuple)
|
| 771 |
+
(value, size) = value
|
| 772 |
+
BItemType = self.ffi._get_cached_btype(tp.item)
|
| 773 |
+
length, rest = divmod(size, self.ffi.sizeof(BItemType))
|
| 774 |
+
if rest != 0:
|
| 775 |
+
raise VerificationError(
|
| 776 |
+
"bad size: %r does not seem to be an array of %s" %
|
| 777 |
+
(name, tp.item))
|
| 778 |
+
tp = tp.resolve_length(length)
|
| 779 |
+
# 'value' is a <cdata 'type *'> which we have to replace with
|
| 780 |
+
# a <cdata 'type[N]'> if the N is actually known
|
| 781 |
+
if tp.length is not None:
|
| 782 |
+
BArray = self.ffi._get_cached_btype(tp)
|
| 783 |
+
value = self.ffi.cast(BArray, value)
|
| 784 |
+
setattr(library, name, value)
|
| 785 |
+
return
|
| 786 |
+
# remove ptr=<cdata 'int *'> from the library instance, and replace
|
| 787 |
+
# it by a property on the class, which reads/writes into ptr[0].
|
| 788 |
+
ptr = value
|
| 789 |
+
delattr(library, name)
|
| 790 |
+
def getter(library):
|
| 791 |
+
return ptr[0]
|
| 792 |
+
def setter(library, value):
|
| 793 |
+
ptr[0] = value
|
| 794 |
+
setattr(type(library), name, property(getter, setter))
|
| 795 |
+
type(library)._cffi_dir.append(name)
|
| 796 |
+
|
| 797 |
+
# ----------
|
| 798 |
+
|
| 799 |
+
def _generate_setup_custom(self):
|
| 800 |
+
prnt = self._prnt
|
| 801 |
+
prnt('static int _cffi_setup_custom(PyObject *lib)')
|
| 802 |
+
prnt('{')
|
| 803 |
+
prnt(' return %s;' % self._chained_list_constants[True])
|
| 804 |
+
prnt('}')
|
| 805 |
+
|
| 806 |
+
cffimod_header = r'''
|
| 807 |
+
#include <Python.h>
|
| 808 |
+
#include <stddef.h>
|
| 809 |
+
|
| 810 |
+
/* this block of #ifs should be kept exactly identical between
|
| 811 |
+
c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py
|
| 812 |
+
and cffi/_cffi_include.h */
|
| 813 |
+
#if defined(_MSC_VER)
|
| 814 |
+
# include <malloc.h> /* for alloca() */
|
| 815 |
+
# if _MSC_VER < 1600 /* MSVC < 2010 */
|
| 816 |
+
typedef __int8 int8_t;
|
| 817 |
+
typedef __int16 int16_t;
|
| 818 |
+
typedef __int32 int32_t;
|
| 819 |
+
typedef __int64 int64_t;
|
| 820 |
+
typedef unsigned __int8 uint8_t;
|
| 821 |
+
typedef unsigned __int16 uint16_t;
|
| 822 |
+
typedef unsigned __int32 uint32_t;
|
| 823 |
+
typedef unsigned __int64 uint64_t;
|
| 824 |
+
typedef __int8 int_least8_t;
|
| 825 |
+
typedef __int16 int_least16_t;
|
| 826 |
+
typedef __int32 int_least32_t;
|
| 827 |
+
typedef __int64 int_least64_t;
|
| 828 |
+
typedef unsigned __int8 uint_least8_t;
|
| 829 |
+
typedef unsigned __int16 uint_least16_t;
|
| 830 |
+
typedef unsigned __int32 uint_least32_t;
|
| 831 |
+
typedef unsigned __int64 uint_least64_t;
|
| 832 |
+
typedef __int8 int_fast8_t;
|
| 833 |
+
typedef __int16 int_fast16_t;
|
| 834 |
+
typedef __int32 int_fast32_t;
|
| 835 |
+
typedef __int64 int_fast64_t;
|
| 836 |
+
typedef unsigned __int8 uint_fast8_t;
|
| 837 |
+
typedef unsigned __int16 uint_fast16_t;
|
| 838 |
+
typedef unsigned __int32 uint_fast32_t;
|
| 839 |
+
typedef unsigned __int64 uint_fast64_t;
|
| 840 |
+
typedef __int64 intmax_t;
|
| 841 |
+
typedef unsigned __int64 uintmax_t;
|
| 842 |
+
# else
|
| 843 |
+
# include <stdint.h>
|
| 844 |
+
# endif
|
| 845 |
+
# if _MSC_VER < 1800 /* MSVC < 2013 */
|
| 846 |
+
# ifndef __cplusplus
|
| 847 |
+
typedef unsigned char _Bool;
|
| 848 |
+
# endif
|
| 849 |
+
# endif
|
| 850 |
+
#else
|
| 851 |
+
# include <stdint.h>
|
| 852 |
+
# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
|
| 853 |
+
# include <alloca.h>
|
| 854 |
+
# endif
|
| 855 |
+
#endif
|
| 856 |
+
|
| 857 |
+
#if PY_MAJOR_VERSION < 3
|
| 858 |
+
# undef PyCapsule_CheckExact
|
| 859 |
+
# undef PyCapsule_GetPointer
|
| 860 |
+
# define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
|
| 861 |
+
# define PyCapsule_GetPointer(capsule, name) \
|
| 862 |
+
(PyCObject_AsVoidPtr(capsule))
|
| 863 |
+
#endif
|
| 864 |
+
|
| 865 |
+
#if PY_MAJOR_VERSION >= 3
|
| 866 |
+
# define PyInt_FromLong PyLong_FromLong
|
| 867 |
+
#endif
|
| 868 |
+
|
| 869 |
+
#define _cffi_from_c_double PyFloat_FromDouble
|
| 870 |
+
#define _cffi_from_c_float PyFloat_FromDouble
|
| 871 |
+
#define _cffi_from_c_long PyInt_FromLong
|
| 872 |
+
#define _cffi_from_c_ulong PyLong_FromUnsignedLong
|
| 873 |
+
#define _cffi_from_c_longlong PyLong_FromLongLong
|
| 874 |
+
#define _cffi_from_c_ulonglong PyLong_FromUnsignedLongLong
|
| 875 |
+
#define _cffi_from_c__Bool PyBool_FromLong
|
| 876 |
+
|
| 877 |
+
#define _cffi_to_c_double PyFloat_AsDouble
|
| 878 |
+
#define _cffi_to_c_float PyFloat_AsDouble
|
| 879 |
+
|
| 880 |
+
#define _cffi_from_c_int_const(x) \
|
| 881 |
+
(((x) > 0) ? \
|
| 882 |
+
((unsigned long long)(x) <= (unsigned long long)LONG_MAX) ? \
|
| 883 |
+
PyInt_FromLong((long)(x)) : \
|
| 884 |
+
PyLong_FromUnsignedLongLong((unsigned long long)(x)) : \
|
| 885 |
+
((long long)(x) >= (long long)LONG_MIN) ? \
|
| 886 |
+
PyInt_FromLong((long)(x)) : \
|
| 887 |
+
PyLong_FromLongLong((long long)(x)))
|
| 888 |
+
|
| 889 |
+
#define _cffi_from_c_int(x, type) \
|
| 890 |
+
(((type)-1) > 0 ? /* unsigned */ \
|
| 891 |
+
(sizeof(type) < sizeof(long) ? \
|
| 892 |
+
PyInt_FromLong((long)x) : \
|
| 893 |
+
sizeof(type) == sizeof(long) ? \
|
| 894 |
+
PyLong_FromUnsignedLong((unsigned long)x) : \
|
| 895 |
+
PyLong_FromUnsignedLongLong((unsigned long long)x)) : \
|
| 896 |
+
(sizeof(type) <= sizeof(long) ? \
|
| 897 |
+
PyInt_FromLong((long)x) : \
|
| 898 |
+
PyLong_FromLongLong((long long)x)))
|
| 899 |
+
|
| 900 |
+
#define _cffi_to_c_int(o, type) \
|
| 901 |
+
((type)( \
|
| 902 |
+
sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \
|
| 903 |
+
: (type)_cffi_to_c_i8(o)) : \
|
| 904 |
+
sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \
|
| 905 |
+
: (type)_cffi_to_c_i16(o)) : \
|
| 906 |
+
sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \
|
| 907 |
+
: (type)_cffi_to_c_i32(o)) : \
|
| 908 |
+
sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \
|
| 909 |
+
: (type)_cffi_to_c_i64(o)) : \
|
| 910 |
+
(Py_FatalError("unsupported size for type " #type), (type)0)))
|
| 911 |
+
|
| 912 |
+
#define _cffi_to_c_i8 \
|
| 913 |
+
((int(*)(PyObject *))_cffi_exports[1])
|
| 914 |
+
#define _cffi_to_c_u8 \
|
| 915 |
+
((int(*)(PyObject *))_cffi_exports[2])
|
| 916 |
+
#define _cffi_to_c_i16 \
|
| 917 |
+
((int(*)(PyObject *))_cffi_exports[3])
|
| 918 |
+
#define _cffi_to_c_u16 \
|
| 919 |
+
((int(*)(PyObject *))_cffi_exports[4])
|
| 920 |
+
#define _cffi_to_c_i32 \
|
| 921 |
+
((int(*)(PyObject *))_cffi_exports[5])
|
| 922 |
+
#define _cffi_to_c_u32 \
|
| 923 |
+
((unsigned int(*)(PyObject *))_cffi_exports[6])
|
| 924 |
+
#define _cffi_to_c_i64 \
|
| 925 |
+
((long long(*)(PyObject *))_cffi_exports[7])
|
| 926 |
+
#define _cffi_to_c_u64 \
|
| 927 |
+
((unsigned long long(*)(PyObject *))_cffi_exports[8])
|
| 928 |
+
#define _cffi_to_c_char \
|
| 929 |
+
((int(*)(PyObject *))_cffi_exports[9])
|
| 930 |
+
#define _cffi_from_c_pointer \
|
| 931 |
+
((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[10])
|
| 932 |
+
#define _cffi_to_c_pointer \
|
| 933 |
+
((char *(*)(PyObject *, CTypeDescrObject *))_cffi_exports[11])
|
| 934 |
+
#define _cffi_get_struct_layout \
|
| 935 |
+
((PyObject *(*)(Py_ssize_t[]))_cffi_exports[12])
|
| 936 |
+
#define _cffi_restore_errno \
|
| 937 |
+
((void(*)(void))_cffi_exports[13])
|
| 938 |
+
#define _cffi_save_errno \
|
| 939 |
+
((void(*)(void))_cffi_exports[14])
|
| 940 |
+
#define _cffi_from_c_char \
|
| 941 |
+
((PyObject *(*)(char))_cffi_exports[15])
|
| 942 |
+
#define _cffi_from_c_deref \
|
| 943 |
+
((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[16])
|
| 944 |
+
#define _cffi_to_c \
|
| 945 |
+
((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[17])
|
| 946 |
+
#define _cffi_from_c_struct \
|
| 947 |
+
((PyObject *(*)(char *, CTypeDescrObject *))_cffi_exports[18])
|
| 948 |
+
#define _cffi_to_c_wchar_t \
|
| 949 |
+
((wchar_t(*)(PyObject *))_cffi_exports[19])
|
| 950 |
+
#define _cffi_from_c_wchar_t \
|
| 951 |
+
((PyObject *(*)(wchar_t))_cffi_exports[20])
|
| 952 |
+
#define _cffi_to_c_long_double \
|
| 953 |
+
((long double(*)(PyObject *))_cffi_exports[21])
|
| 954 |
+
#define _cffi_to_c__Bool \
|
| 955 |
+
((_Bool(*)(PyObject *))_cffi_exports[22])
|
| 956 |
+
#define _cffi_prepare_pointer_call_argument \
|
| 957 |
+
((Py_ssize_t(*)(CTypeDescrObject *, PyObject *, char **))_cffi_exports[23])
|
| 958 |
+
#define _cffi_convert_array_from_object \
|
| 959 |
+
((int(*)(char *, CTypeDescrObject *, PyObject *))_cffi_exports[24])
|
| 960 |
+
#define _CFFI_NUM_EXPORTS 25
|
| 961 |
+
|
| 962 |
+
typedef struct _ctypedescr CTypeDescrObject;
|
| 963 |
+
|
| 964 |
+
static void *_cffi_exports[_CFFI_NUM_EXPORTS];
|
| 965 |
+
static PyObject *_cffi_types, *_cffi_VerificationError;
|
| 966 |
+
|
| 967 |
+
static int _cffi_setup_custom(PyObject *lib); /* forward */
|
| 968 |
+
|
| 969 |
+
static PyObject *_cffi_setup(PyObject *self, PyObject *args)
|
| 970 |
+
{
|
| 971 |
+
PyObject *library;
|
| 972 |
+
int was_alive = (_cffi_types != NULL);
|
| 973 |
+
(void)self; /* unused */
|
| 974 |
+
if (!PyArg_ParseTuple(args, "OOO", &_cffi_types, &_cffi_VerificationError,
|
| 975 |
+
&library))
|
| 976 |
+
return NULL;
|
| 977 |
+
Py_INCREF(_cffi_types);
|
| 978 |
+
Py_INCREF(_cffi_VerificationError);
|
| 979 |
+
if (_cffi_setup_custom(library) < 0)
|
| 980 |
+
return NULL;
|
| 981 |
+
return PyBool_FromLong(was_alive);
|
| 982 |
+
}
|
| 983 |
+
|
| 984 |
+
static int _cffi_init(void)
|
| 985 |
+
{
|
| 986 |
+
PyObject *module, *c_api_object = NULL;
|
| 987 |
+
|
| 988 |
+
module = PyImport_ImportModule("_cffi_backend");
|
| 989 |
+
if (module == NULL)
|
| 990 |
+
goto failure;
|
| 991 |
+
|
| 992 |
+
c_api_object = PyObject_GetAttrString(module, "_C_API");
|
| 993 |
+
if (c_api_object == NULL)
|
| 994 |
+
goto failure;
|
| 995 |
+
if (!PyCapsule_CheckExact(c_api_object)) {
|
| 996 |
+
PyErr_SetNone(PyExc_ImportError);
|
| 997 |
+
goto failure;
|
| 998 |
+
}
|
| 999 |
+
memcpy(_cffi_exports, PyCapsule_GetPointer(c_api_object, "cffi"),
|
| 1000 |
+
_CFFI_NUM_EXPORTS * sizeof(void *));
|
| 1001 |
+
|
| 1002 |
+
Py_DECREF(module);
|
| 1003 |
+
Py_DECREF(c_api_object);
|
| 1004 |
+
return 0;
|
| 1005 |
+
|
| 1006 |
+
failure:
|
| 1007 |
+
Py_XDECREF(module);
|
| 1008 |
+
Py_XDECREF(c_api_object);
|
| 1009 |
+
return -1;
|
| 1010 |
+
}
|
| 1011 |
+
|
| 1012 |
+
#define _cffi_type(num) ((CTypeDescrObject *)PyList_GET_ITEM(_cffi_types, num))
|
| 1013 |
+
|
| 1014 |
+
/**********/
|
| 1015 |
+
'''
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/vengine_gen.py
ADDED
|
@@ -0,0 +1,675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# DEPRECATED: implementation for ffi.verify()
|
| 3 |
+
#
|
| 4 |
+
import sys, os
|
| 5 |
+
import types
|
| 6 |
+
|
| 7 |
+
from . import model
|
| 8 |
+
from .error import VerificationError
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class VGenericEngine(object):
|
| 12 |
+
_class_key = 'g'
|
| 13 |
+
_gen_python_module = False
|
| 14 |
+
|
| 15 |
+
def __init__(self, verifier):
|
| 16 |
+
self.verifier = verifier
|
| 17 |
+
self.ffi = verifier.ffi
|
| 18 |
+
self.export_symbols = []
|
| 19 |
+
self._struct_pending_verification = {}
|
| 20 |
+
|
| 21 |
+
def patch_extension_kwds(self, kwds):
|
| 22 |
+
# add 'export_symbols' to the dictionary. Note that we add the
|
| 23 |
+
# list before filling it. When we fill it, it will thus also show
|
| 24 |
+
# up in kwds['export_symbols'].
|
| 25 |
+
kwds.setdefault('export_symbols', self.export_symbols)
|
| 26 |
+
|
| 27 |
+
def find_module(self, module_name, path, so_suffixes):
|
| 28 |
+
for so_suffix in so_suffixes:
|
| 29 |
+
basename = module_name + so_suffix
|
| 30 |
+
if path is None:
|
| 31 |
+
path = sys.path
|
| 32 |
+
for dirname in path:
|
| 33 |
+
filename = os.path.join(dirname, basename)
|
| 34 |
+
if os.path.isfile(filename):
|
| 35 |
+
return filename
|
| 36 |
+
|
| 37 |
+
def collect_types(self):
|
| 38 |
+
pass # not needed in the generic engine
|
| 39 |
+
|
| 40 |
+
def _prnt(self, what=''):
|
| 41 |
+
self._f.write(what + '\n')
|
| 42 |
+
|
| 43 |
+
def write_source_to_f(self):
|
| 44 |
+
prnt = self._prnt
|
| 45 |
+
# first paste some standard set of lines that are mostly '#include'
|
| 46 |
+
prnt(cffimod_header)
|
| 47 |
+
# then paste the C source given by the user, verbatim.
|
| 48 |
+
prnt(self.verifier.preamble)
|
| 49 |
+
#
|
| 50 |
+
# call generate_gen_xxx_decl(), for every xxx found from
|
| 51 |
+
# ffi._parser._declarations. This generates all the functions.
|
| 52 |
+
self._generate('decl')
|
| 53 |
+
#
|
| 54 |
+
# on Windows, distutils insists on putting init_cffi_xyz in
|
| 55 |
+
# 'export_symbols', so instead of fighting it, just give up and
|
| 56 |
+
# give it one
|
| 57 |
+
if sys.platform == 'win32':
|
| 58 |
+
if sys.version_info >= (3,):
|
| 59 |
+
prefix = 'PyInit_'
|
| 60 |
+
else:
|
| 61 |
+
prefix = 'init'
|
| 62 |
+
modname = self.verifier.get_module_name()
|
| 63 |
+
prnt("void %s%s(void) { }\n" % (prefix, modname))
|
| 64 |
+
|
| 65 |
+
def load_library(self, flags=0):
|
| 66 |
+
# import it with the CFFI backend
|
| 67 |
+
backend = self.ffi._backend
|
| 68 |
+
# needs to make a path that contains '/', on Posix
|
| 69 |
+
filename = os.path.join(os.curdir, self.verifier.modulefilename)
|
| 70 |
+
module = backend.load_library(filename, flags)
|
| 71 |
+
#
|
| 72 |
+
# call loading_gen_struct() to get the struct layout inferred by
|
| 73 |
+
# the C compiler
|
| 74 |
+
self._load(module, 'loading')
|
| 75 |
+
|
| 76 |
+
# build the FFILibrary class and instance, this is a module subclass
|
| 77 |
+
# because modules are expected to have usually-constant-attributes and
|
| 78 |
+
# in PyPy this means the JIT is able to treat attributes as constant,
|
| 79 |
+
# which we want.
|
| 80 |
+
class FFILibrary(types.ModuleType):
|
| 81 |
+
_cffi_generic_module = module
|
| 82 |
+
_cffi_ffi = self.ffi
|
| 83 |
+
_cffi_dir = []
|
| 84 |
+
def __dir__(self):
|
| 85 |
+
return FFILibrary._cffi_dir
|
| 86 |
+
library = FFILibrary("")
|
| 87 |
+
#
|
| 88 |
+
# finally, call the loaded_gen_xxx() functions. This will set
|
| 89 |
+
# up the 'library' object.
|
| 90 |
+
self._load(module, 'loaded', library=library)
|
| 91 |
+
return library
|
| 92 |
+
|
| 93 |
+
def _get_declarations(self):
|
| 94 |
+
lst = [(key, tp) for (key, (tp, qual)) in
|
| 95 |
+
self.ffi._parser._declarations.items()]
|
| 96 |
+
lst.sort()
|
| 97 |
+
return lst
|
| 98 |
+
|
| 99 |
+
def _generate(self, step_name):
|
| 100 |
+
for name, tp in self._get_declarations():
|
| 101 |
+
kind, realname = name.split(' ', 1)
|
| 102 |
+
try:
|
| 103 |
+
method = getattr(self, '_generate_gen_%s_%s' % (kind,
|
| 104 |
+
step_name))
|
| 105 |
+
except AttributeError:
|
| 106 |
+
raise VerificationError(
|
| 107 |
+
"not implemented in verify(): %r" % name)
|
| 108 |
+
try:
|
| 109 |
+
method(tp, realname)
|
| 110 |
+
except Exception as e:
|
| 111 |
+
model.attach_exception_info(e, name)
|
| 112 |
+
raise
|
| 113 |
+
|
| 114 |
+
def _load(self, module, step_name, **kwds):
|
| 115 |
+
for name, tp in self._get_declarations():
|
| 116 |
+
kind, realname = name.split(' ', 1)
|
| 117 |
+
method = getattr(self, '_%s_gen_%s' % (step_name, kind))
|
| 118 |
+
try:
|
| 119 |
+
method(tp, realname, module, **kwds)
|
| 120 |
+
except Exception as e:
|
| 121 |
+
model.attach_exception_info(e, name)
|
| 122 |
+
raise
|
| 123 |
+
|
| 124 |
+
def _generate_nothing(self, tp, name):
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
def _loaded_noop(self, tp, name, module, **kwds):
|
| 128 |
+
pass
|
| 129 |
+
|
| 130 |
+
# ----------
|
| 131 |
+
# typedefs: generates no code so far
|
| 132 |
+
|
| 133 |
+
_generate_gen_typedef_decl = _generate_nothing
|
| 134 |
+
_loading_gen_typedef = _loaded_noop
|
| 135 |
+
_loaded_gen_typedef = _loaded_noop
|
| 136 |
+
|
| 137 |
+
# ----------
|
| 138 |
+
# function declarations
|
| 139 |
+
|
| 140 |
+
def _generate_gen_function_decl(self, tp, name):
|
| 141 |
+
assert isinstance(tp, model.FunctionPtrType)
|
| 142 |
+
if tp.ellipsis:
|
| 143 |
+
# cannot support vararg functions better than this: check for its
|
| 144 |
+
# exact type (including the fixed arguments), and build it as a
|
| 145 |
+
# constant function pointer (no _cffi_f_%s wrapper)
|
| 146 |
+
self._generate_gen_const(False, name, tp)
|
| 147 |
+
return
|
| 148 |
+
prnt = self._prnt
|
| 149 |
+
numargs = len(tp.args)
|
| 150 |
+
argnames = []
|
| 151 |
+
for i, type in enumerate(tp.args):
|
| 152 |
+
indirection = ''
|
| 153 |
+
if isinstance(type, model.StructOrUnion):
|
| 154 |
+
indirection = '*'
|
| 155 |
+
argnames.append('%sx%d' % (indirection, i))
|
| 156 |
+
context = 'argument of %s' % name
|
| 157 |
+
arglist = [type.get_c_name(' %s' % arg, context)
|
| 158 |
+
for type, arg in zip(tp.args, argnames)]
|
| 159 |
+
tpresult = tp.result
|
| 160 |
+
if isinstance(tpresult, model.StructOrUnion):
|
| 161 |
+
arglist.insert(0, tpresult.get_c_name(' *r', context))
|
| 162 |
+
tpresult = model.void_type
|
| 163 |
+
arglist = ', '.join(arglist) or 'void'
|
| 164 |
+
wrappername = '_cffi_f_%s' % name
|
| 165 |
+
self.export_symbols.append(wrappername)
|
| 166 |
+
if tp.abi:
|
| 167 |
+
abi = tp.abi + ' '
|
| 168 |
+
else:
|
| 169 |
+
abi = ''
|
| 170 |
+
funcdecl = ' %s%s(%s)' % (abi, wrappername, arglist)
|
| 171 |
+
context = 'result of %s' % name
|
| 172 |
+
prnt(tpresult.get_c_name(funcdecl, context))
|
| 173 |
+
prnt('{')
|
| 174 |
+
#
|
| 175 |
+
if isinstance(tp.result, model.StructOrUnion):
|
| 176 |
+
result_code = '*r = '
|
| 177 |
+
elif not isinstance(tp.result, model.VoidType):
|
| 178 |
+
result_code = 'return '
|
| 179 |
+
else:
|
| 180 |
+
result_code = ''
|
| 181 |
+
prnt(' %s%s(%s);' % (result_code, name, ', '.join(argnames)))
|
| 182 |
+
prnt('}')
|
| 183 |
+
prnt()
|
| 184 |
+
|
| 185 |
+
_loading_gen_function = _loaded_noop
|
| 186 |
+
|
| 187 |
+
def _loaded_gen_function(self, tp, name, module, library):
|
| 188 |
+
assert isinstance(tp, model.FunctionPtrType)
|
| 189 |
+
if tp.ellipsis:
|
| 190 |
+
newfunction = self._load_constant(False, tp, name, module)
|
| 191 |
+
else:
|
| 192 |
+
indirections = []
|
| 193 |
+
base_tp = tp
|
| 194 |
+
if (any(isinstance(typ, model.StructOrUnion) for typ in tp.args)
|
| 195 |
+
or isinstance(tp.result, model.StructOrUnion)):
|
| 196 |
+
indirect_args = []
|
| 197 |
+
for i, typ in enumerate(tp.args):
|
| 198 |
+
if isinstance(typ, model.StructOrUnion):
|
| 199 |
+
typ = model.PointerType(typ)
|
| 200 |
+
indirections.append((i, typ))
|
| 201 |
+
indirect_args.append(typ)
|
| 202 |
+
indirect_result = tp.result
|
| 203 |
+
if isinstance(indirect_result, model.StructOrUnion):
|
| 204 |
+
if indirect_result.fldtypes is None:
|
| 205 |
+
raise TypeError("'%s' is used as result type, "
|
| 206 |
+
"but is opaque" % (
|
| 207 |
+
indirect_result._get_c_name(),))
|
| 208 |
+
indirect_result = model.PointerType(indirect_result)
|
| 209 |
+
indirect_args.insert(0, indirect_result)
|
| 210 |
+
indirections.insert(0, ("result", indirect_result))
|
| 211 |
+
indirect_result = model.void_type
|
| 212 |
+
tp = model.FunctionPtrType(tuple(indirect_args),
|
| 213 |
+
indirect_result, tp.ellipsis)
|
| 214 |
+
BFunc = self.ffi._get_cached_btype(tp)
|
| 215 |
+
wrappername = '_cffi_f_%s' % name
|
| 216 |
+
newfunction = module.load_function(BFunc, wrappername)
|
| 217 |
+
for i, typ in indirections:
|
| 218 |
+
newfunction = self._make_struct_wrapper(newfunction, i, typ,
|
| 219 |
+
base_tp)
|
| 220 |
+
setattr(library, name, newfunction)
|
| 221 |
+
type(library)._cffi_dir.append(name)
|
| 222 |
+
|
| 223 |
+
def _make_struct_wrapper(self, oldfunc, i, tp, base_tp):
|
| 224 |
+
backend = self.ffi._backend
|
| 225 |
+
BType = self.ffi._get_cached_btype(tp)
|
| 226 |
+
if i == "result":
|
| 227 |
+
ffi = self.ffi
|
| 228 |
+
def newfunc(*args):
|
| 229 |
+
res = ffi.new(BType)
|
| 230 |
+
oldfunc(res, *args)
|
| 231 |
+
return res[0]
|
| 232 |
+
else:
|
| 233 |
+
def newfunc(*args):
|
| 234 |
+
args = args[:i] + (backend.newp(BType, args[i]),) + args[i+1:]
|
| 235 |
+
return oldfunc(*args)
|
| 236 |
+
newfunc._cffi_base_type = base_tp
|
| 237 |
+
return newfunc
|
| 238 |
+
|
| 239 |
+
# ----------
|
| 240 |
+
# named structs
|
| 241 |
+
|
| 242 |
+
def _generate_gen_struct_decl(self, tp, name):
|
| 243 |
+
assert name == tp.name
|
| 244 |
+
self._generate_struct_or_union_decl(tp, 'struct', name)
|
| 245 |
+
|
| 246 |
+
def _loading_gen_struct(self, tp, name, module):
|
| 247 |
+
self._loading_struct_or_union(tp, 'struct', name, module)
|
| 248 |
+
|
| 249 |
+
def _loaded_gen_struct(self, tp, name, module, **kwds):
|
| 250 |
+
self._loaded_struct_or_union(tp)
|
| 251 |
+
|
| 252 |
+
def _generate_gen_union_decl(self, tp, name):
|
| 253 |
+
assert name == tp.name
|
| 254 |
+
self._generate_struct_or_union_decl(tp, 'union', name)
|
| 255 |
+
|
| 256 |
+
def _loading_gen_union(self, tp, name, module):
|
| 257 |
+
self._loading_struct_or_union(tp, 'union', name, module)
|
| 258 |
+
|
| 259 |
+
def _loaded_gen_union(self, tp, name, module, **kwds):
|
| 260 |
+
self._loaded_struct_or_union(tp)
|
| 261 |
+
|
| 262 |
+
def _generate_struct_or_union_decl(self, tp, prefix, name):
|
| 263 |
+
if tp.fldnames is None:
|
| 264 |
+
return # nothing to do with opaque structs
|
| 265 |
+
checkfuncname = '_cffi_check_%s_%s' % (prefix, name)
|
| 266 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
| 267 |
+
cname = ('%s %s' % (prefix, name)).strip()
|
| 268 |
+
#
|
| 269 |
+
prnt = self._prnt
|
| 270 |
+
prnt('static void %s(%s *p)' % (checkfuncname, cname))
|
| 271 |
+
prnt('{')
|
| 272 |
+
prnt(' /* only to generate compile-time warnings or errors */')
|
| 273 |
+
prnt(' (void)p;')
|
| 274 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
| 275 |
+
if (isinstance(ftype, model.PrimitiveType)
|
| 276 |
+
and ftype.is_integer_type()) or fbitsize >= 0:
|
| 277 |
+
# accept all integers, but complain on float or double
|
| 278 |
+
prnt(' (void)((p->%s) << 1);' % fname)
|
| 279 |
+
else:
|
| 280 |
+
# only accept exactly the type declared.
|
| 281 |
+
try:
|
| 282 |
+
prnt(' { %s = &p->%s; (void)tmp; }' % (
|
| 283 |
+
ftype.get_c_name('*tmp', 'field %r'%fname, quals=fqual),
|
| 284 |
+
fname))
|
| 285 |
+
except VerificationError as e:
|
| 286 |
+
prnt(' /* %s */' % str(e)) # cannot verify it, ignore
|
| 287 |
+
prnt('}')
|
| 288 |
+
self.export_symbols.append(layoutfuncname)
|
| 289 |
+
prnt('intptr_t %s(intptr_t i)' % (layoutfuncname,))
|
| 290 |
+
prnt('{')
|
| 291 |
+
prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname)
|
| 292 |
+
prnt(' static intptr_t nums[] = {')
|
| 293 |
+
prnt(' sizeof(%s),' % cname)
|
| 294 |
+
prnt(' offsetof(struct _cffi_aligncheck, y),')
|
| 295 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
| 296 |
+
if fbitsize >= 0:
|
| 297 |
+
continue # xxx ignore fbitsize for now
|
| 298 |
+
prnt(' offsetof(%s, %s),' % (cname, fname))
|
| 299 |
+
if isinstance(ftype, model.ArrayType) and ftype.length is None:
|
| 300 |
+
prnt(' 0, /* %s */' % ftype._get_c_name())
|
| 301 |
+
else:
|
| 302 |
+
prnt(' sizeof(((%s *)0)->%s),' % (cname, fname))
|
| 303 |
+
prnt(' -1')
|
| 304 |
+
prnt(' };')
|
| 305 |
+
prnt(' return nums[i];')
|
| 306 |
+
prnt(' /* the next line is not executed, but compiled */')
|
| 307 |
+
prnt(' %s(0);' % (checkfuncname,))
|
| 308 |
+
prnt('}')
|
| 309 |
+
prnt()
|
| 310 |
+
|
| 311 |
+
def _loading_struct_or_union(self, tp, prefix, name, module):
|
| 312 |
+
if tp.fldnames is None:
|
| 313 |
+
return # nothing to do with opaque structs
|
| 314 |
+
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
|
| 315 |
+
#
|
| 316 |
+
BFunc = self.ffi._typeof_locked("intptr_t(*)(intptr_t)")[0]
|
| 317 |
+
function = module.load_function(BFunc, layoutfuncname)
|
| 318 |
+
layout = []
|
| 319 |
+
num = 0
|
| 320 |
+
while True:
|
| 321 |
+
x = function(num)
|
| 322 |
+
if x < 0: break
|
| 323 |
+
layout.append(x)
|
| 324 |
+
num += 1
|
| 325 |
+
if isinstance(tp, model.StructOrUnion) and tp.partial:
|
| 326 |
+
# use the function()'s sizes and offsets to guide the
|
| 327 |
+
# layout of the struct
|
| 328 |
+
totalsize = layout[0]
|
| 329 |
+
totalalignment = layout[1]
|
| 330 |
+
fieldofs = layout[2::2]
|
| 331 |
+
fieldsize = layout[3::2]
|
| 332 |
+
tp.force_flatten()
|
| 333 |
+
assert len(fieldofs) == len(fieldsize) == len(tp.fldnames)
|
| 334 |
+
tp.fixedlayout = fieldofs, fieldsize, totalsize, totalalignment
|
| 335 |
+
else:
|
| 336 |
+
cname = ('%s %s' % (prefix, name)).strip()
|
| 337 |
+
self._struct_pending_verification[tp] = layout, cname
|
| 338 |
+
|
| 339 |
+
def _loaded_struct_or_union(self, tp):
|
| 340 |
+
if tp.fldnames is None:
|
| 341 |
+
return # nothing to do with opaque structs
|
| 342 |
+
self.ffi._get_cached_btype(tp) # force 'fixedlayout' to be considered
|
| 343 |
+
|
| 344 |
+
if tp in self._struct_pending_verification:
|
| 345 |
+
# check that the layout sizes and offsets match the real ones
|
| 346 |
+
def check(realvalue, expectedvalue, msg):
|
| 347 |
+
if realvalue != expectedvalue:
|
| 348 |
+
raise VerificationError(
|
| 349 |
+
"%s (we have %d, but C compiler says %d)"
|
| 350 |
+
% (msg, expectedvalue, realvalue))
|
| 351 |
+
ffi = self.ffi
|
| 352 |
+
BStruct = ffi._get_cached_btype(tp)
|
| 353 |
+
layout, cname = self._struct_pending_verification.pop(tp)
|
| 354 |
+
check(layout[0], ffi.sizeof(BStruct), "wrong total size")
|
| 355 |
+
check(layout[1], ffi.alignof(BStruct), "wrong total alignment")
|
| 356 |
+
i = 2
|
| 357 |
+
for fname, ftype, fbitsize, fqual in tp.enumfields():
|
| 358 |
+
if fbitsize >= 0:
|
| 359 |
+
continue # xxx ignore fbitsize for now
|
| 360 |
+
check(layout[i], ffi.offsetof(BStruct, fname),
|
| 361 |
+
"wrong offset for field %r" % (fname,))
|
| 362 |
+
if layout[i+1] != 0:
|
| 363 |
+
BField = ffi._get_cached_btype(ftype)
|
| 364 |
+
check(layout[i+1], ffi.sizeof(BField),
|
| 365 |
+
"wrong size for field %r" % (fname,))
|
| 366 |
+
i += 2
|
| 367 |
+
assert i == len(layout)
|
| 368 |
+
|
| 369 |
+
# ----------
|
| 370 |
+
# 'anonymous' declarations. These are produced for anonymous structs
|
| 371 |
+
# or unions; the 'name' is obtained by a typedef.
|
| 372 |
+
|
| 373 |
+
def _generate_gen_anonymous_decl(self, tp, name):
|
| 374 |
+
if isinstance(tp, model.EnumType):
|
| 375 |
+
self._generate_gen_enum_decl(tp, name, '')
|
| 376 |
+
else:
|
| 377 |
+
self._generate_struct_or_union_decl(tp, '', name)
|
| 378 |
+
|
| 379 |
+
def _loading_gen_anonymous(self, tp, name, module):
|
| 380 |
+
if isinstance(tp, model.EnumType):
|
| 381 |
+
self._loading_gen_enum(tp, name, module, '')
|
| 382 |
+
else:
|
| 383 |
+
self._loading_struct_or_union(tp, '', name, module)
|
| 384 |
+
|
| 385 |
+
def _loaded_gen_anonymous(self, tp, name, module, **kwds):
|
| 386 |
+
if isinstance(tp, model.EnumType):
|
| 387 |
+
self._loaded_gen_enum(tp, name, module, **kwds)
|
| 388 |
+
else:
|
| 389 |
+
self._loaded_struct_or_union(tp)
|
| 390 |
+
|
| 391 |
+
# ----------
|
| 392 |
+
# constants, likely declared with '#define'
|
| 393 |
+
|
| 394 |
+
def _generate_gen_const(self, is_int, name, tp=None, category='const',
|
| 395 |
+
check_value=None):
|
| 396 |
+
prnt = self._prnt
|
| 397 |
+
funcname = '_cffi_%s_%s' % (category, name)
|
| 398 |
+
self.export_symbols.append(funcname)
|
| 399 |
+
if check_value is not None:
|
| 400 |
+
assert is_int
|
| 401 |
+
assert category == 'const'
|
| 402 |
+
prnt('int %s(char *out_error)' % funcname)
|
| 403 |
+
prnt('{')
|
| 404 |
+
self._check_int_constant_value(name, check_value)
|
| 405 |
+
prnt(' return 0;')
|
| 406 |
+
prnt('}')
|
| 407 |
+
elif is_int:
|
| 408 |
+
assert category == 'const'
|
| 409 |
+
prnt('int %s(long long *out_value)' % funcname)
|
| 410 |
+
prnt('{')
|
| 411 |
+
prnt(' *out_value = (long long)(%s);' % (name,))
|
| 412 |
+
prnt(' return (%s) <= 0;' % (name,))
|
| 413 |
+
prnt('}')
|
| 414 |
+
else:
|
| 415 |
+
assert tp is not None
|
| 416 |
+
assert check_value is None
|
| 417 |
+
if category == 'var':
|
| 418 |
+
ampersand = '&'
|
| 419 |
+
else:
|
| 420 |
+
ampersand = ''
|
| 421 |
+
extra = ''
|
| 422 |
+
if category == 'const' and isinstance(tp, model.StructOrUnion):
|
| 423 |
+
extra = 'const *'
|
| 424 |
+
ampersand = '&'
|
| 425 |
+
prnt(tp.get_c_name(' %s%s(void)' % (extra, funcname), name))
|
| 426 |
+
prnt('{')
|
| 427 |
+
prnt(' return (%s%s);' % (ampersand, name))
|
| 428 |
+
prnt('}')
|
| 429 |
+
prnt()
|
| 430 |
+
|
| 431 |
+
def _generate_gen_constant_decl(self, tp, name):
|
| 432 |
+
is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
|
| 433 |
+
self._generate_gen_const(is_int, name, tp)
|
| 434 |
+
|
| 435 |
+
_loading_gen_constant = _loaded_noop
|
| 436 |
+
|
| 437 |
+
def _load_constant(self, is_int, tp, name, module, check_value=None):
|
| 438 |
+
funcname = '_cffi_const_%s' % name
|
| 439 |
+
if check_value is not None:
|
| 440 |
+
assert is_int
|
| 441 |
+
self._load_known_int_constant(module, funcname)
|
| 442 |
+
value = check_value
|
| 443 |
+
elif is_int:
|
| 444 |
+
BType = self.ffi._typeof_locked("long long*")[0]
|
| 445 |
+
BFunc = self.ffi._typeof_locked("int(*)(long long*)")[0]
|
| 446 |
+
function = module.load_function(BFunc, funcname)
|
| 447 |
+
p = self.ffi.new(BType)
|
| 448 |
+
negative = function(p)
|
| 449 |
+
value = int(p[0])
|
| 450 |
+
if value < 0 and not negative:
|
| 451 |
+
BLongLong = self.ffi._typeof_locked("long long")[0]
|
| 452 |
+
value += (1 << (8*self.ffi.sizeof(BLongLong)))
|
| 453 |
+
else:
|
| 454 |
+
assert check_value is None
|
| 455 |
+
fntypeextra = '(*)(void)'
|
| 456 |
+
if isinstance(tp, model.StructOrUnion):
|
| 457 |
+
fntypeextra = '*' + fntypeextra
|
| 458 |
+
BFunc = self.ffi._typeof_locked(tp.get_c_name(fntypeextra, name))[0]
|
| 459 |
+
function = module.load_function(BFunc, funcname)
|
| 460 |
+
value = function()
|
| 461 |
+
if isinstance(tp, model.StructOrUnion):
|
| 462 |
+
value = value[0]
|
| 463 |
+
return value
|
| 464 |
+
|
| 465 |
+
def _loaded_gen_constant(self, tp, name, module, library):
|
| 466 |
+
is_int = isinstance(tp, model.PrimitiveType) and tp.is_integer_type()
|
| 467 |
+
value = self._load_constant(is_int, tp, name, module)
|
| 468 |
+
setattr(library, name, value)
|
| 469 |
+
type(library)._cffi_dir.append(name)
|
| 470 |
+
|
| 471 |
+
# ----------
|
| 472 |
+
# enums
|
| 473 |
+
|
| 474 |
+
def _check_int_constant_value(self, name, value):
|
| 475 |
+
prnt = self._prnt
|
| 476 |
+
if value <= 0:
|
| 477 |
+
prnt(' if ((%s) > 0 || (long)(%s) != %dL) {' % (
|
| 478 |
+
name, name, value))
|
| 479 |
+
else:
|
| 480 |
+
prnt(' if ((%s) <= 0 || (unsigned long)(%s) != %dUL) {' % (
|
| 481 |
+
name, name, value))
|
| 482 |
+
prnt(' char buf[64];')
|
| 483 |
+
prnt(' if ((%s) <= 0)' % name)
|
| 484 |
+
prnt(' sprintf(buf, "%%ld", (long)(%s));' % name)
|
| 485 |
+
prnt(' else')
|
| 486 |
+
prnt(' sprintf(buf, "%%lu", (unsigned long)(%s));' %
|
| 487 |
+
name)
|
| 488 |
+
prnt(' sprintf(out_error, "%s has the real value %s, not %s",')
|
| 489 |
+
prnt(' "%s", buf, "%d");' % (name[:100], value))
|
| 490 |
+
prnt(' return -1;')
|
| 491 |
+
prnt(' }')
|
| 492 |
+
|
| 493 |
+
def _load_known_int_constant(self, module, funcname):
|
| 494 |
+
BType = self.ffi._typeof_locked("char[]")[0]
|
| 495 |
+
BFunc = self.ffi._typeof_locked("int(*)(char*)")[0]
|
| 496 |
+
function = module.load_function(BFunc, funcname)
|
| 497 |
+
p = self.ffi.new(BType, 256)
|
| 498 |
+
if function(p) < 0:
|
| 499 |
+
error = self.ffi.string(p)
|
| 500 |
+
if sys.version_info >= (3,):
|
| 501 |
+
error = str(error, 'utf-8')
|
| 502 |
+
raise VerificationError(error)
|
| 503 |
+
|
| 504 |
+
def _enum_funcname(self, prefix, name):
|
| 505 |
+
# "$enum_$1" => "___D_enum____D_1"
|
| 506 |
+
name = name.replace('$', '___D_')
|
| 507 |
+
return '_cffi_e_%s_%s' % (prefix, name)
|
| 508 |
+
|
| 509 |
+
def _generate_gen_enum_decl(self, tp, name, prefix='enum'):
|
| 510 |
+
if tp.partial:
|
| 511 |
+
for enumerator in tp.enumerators:
|
| 512 |
+
self._generate_gen_const(True, enumerator)
|
| 513 |
+
return
|
| 514 |
+
#
|
| 515 |
+
funcname = self._enum_funcname(prefix, name)
|
| 516 |
+
self.export_symbols.append(funcname)
|
| 517 |
+
prnt = self._prnt
|
| 518 |
+
prnt('int %s(char *out_error)' % funcname)
|
| 519 |
+
prnt('{')
|
| 520 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
| 521 |
+
self._check_int_constant_value(enumerator, enumvalue)
|
| 522 |
+
prnt(' return 0;')
|
| 523 |
+
prnt('}')
|
| 524 |
+
prnt()
|
| 525 |
+
|
| 526 |
+
def _loading_gen_enum(self, tp, name, module, prefix='enum'):
|
| 527 |
+
if tp.partial:
|
| 528 |
+
enumvalues = [self._load_constant(True, tp, enumerator, module)
|
| 529 |
+
for enumerator in tp.enumerators]
|
| 530 |
+
tp.enumvalues = tuple(enumvalues)
|
| 531 |
+
tp.partial_resolved = True
|
| 532 |
+
else:
|
| 533 |
+
funcname = self._enum_funcname(prefix, name)
|
| 534 |
+
self._load_known_int_constant(module, funcname)
|
| 535 |
+
|
| 536 |
+
def _loaded_gen_enum(self, tp, name, module, library):
|
| 537 |
+
for enumerator, enumvalue in zip(tp.enumerators, tp.enumvalues):
|
| 538 |
+
setattr(library, enumerator, enumvalue)
|
| 539 |
+
type(library)._cffi_dir.append(enumerator)
|
| 540 |
+
|
| 541 |
+
# ----------
|
| 542 |
+
# macros: for now only for integers
|
| 543 |
+
|
| 544 |
+
def _generate_gen_macro_decl(self, tp, name):
|
| 545 |
+
if tp == '...':
|
| 546 |
+
check_value = None
|
| 547 |
+
else:
|
| 548 |
+
check_value = tp # an integer
|
| 549 |
+
self._generate_gen_const(True, name, check_value=check_value)
|
| 550 |
+
|
| 551 |
+
_loading_gen_macro = _loaded_noop
|
| 552 |
+
|
| 553 |
+
def _loaded_gen_macro(self, tp, name, module, library):
|
| 554 |
+
if tp == '...':
|
| 555 |
+
check_value = None
|
| 556 |
+
else:
|
| 557 |
+
check_value = tp # an integer
|
| 558 |
+
value = self._load_constant(True, tp, name, module,
|
| 559 |
+
check_value=check_value)
|
| 560 |
+
setattr(library, name, value)
|
| 561 |
+
type(library)._cffi_dir.append(name)
|
| 562 |
+
|
| 563 |
+
# ----------
|
| 564 |
+
# global variables
|
| 565 |
+
|
| 566 |
+
def _generate_gen_variable_decl(self, tp, name):
|
| 567 |
+
if isinstance(tp, model.ArrayType):
|
| 568 |
+
if tp.length == '...':
|
| 569 |
+
prnt = self._prnt
|
| 570 |
+
funcname = '_cffi_sizeof_%s' % (name,)
|
| 571 |
+
self.export_symbols.append(funcname)
|
| 572 |
+
prnt("size_t %s(void)" % funcname)
|
| 573 |
+
prnt("{")
|
| 574 |
+
prnt(" return sizeof(%s);" % (name,))
|
| 575 |
+
prnt("}")
|
| 576 |
+
tp_ptr = model.PointerType(tp.item)
|
| 577 |
+
self._generate_gen_const(False, name, tp_ptr)
|
| 578 |
+
else:
|
| 579 |
+
tp_ptr = model.PointerType(tp)
|
| 580 |
+
self._generate_gen_const(False, name, tp_ptr, category='var')
|
| 581 |
+
|
| 582 |
+
_loading_gen_variable = _loaded_noop
|
| 583 |
+
|
| 584 |
+
def _loaded_gen_variable(self, tp, name, module, library):
|
| 585 |
+
if isinstance(tp, model.ArrayType): # int a[5] is "constant" in the
|
| 586 |
+
# sense that "a=..." is forbidden
|
| 587 |
+
if tp.length == '...':
|
| 588 |
+
funcname = '_cffi_sizeof_%s' % (name,)
|
| 589 |
+
BFunc = self.ffi._typeof_locked('size_t(*)(void)')[0]
|
| 590 |
+
function = module.load_function(BFunc, funcname)
|
| 591 |
+
size = function()
|
| 592 |
+
BItemType = self.ffi._get_cached_btype(tp.item)
|
| 593 |
+
length, rest = divmod(size, self.ffi.sizeof(BItemType))
|
| 594 |
+
if rest != 0:
|
| 595 |
+
raise VerificationError(
|
| 596 |
+
"bad size: %r does not seem to be an array of %s" %
|
| 597 |
+
(name, tp.item))
|
| 598 |
+
tp = tp.resolve_length(length)
|
| 599 |
+
tp_ptr = model.PointerType(tp.item)
|
| 600 |
+
value = self._load_constant(False, tp_ptr, name, module)
|
| 601 |
+
# 'value' is a <cdata 'type *'> which we have to replace with
|
| 602 |
+
# a <cdata 'type[N]'> if the N is actually known
|
| 603 |
+
if tp.length is not None:
|
| 604 |
+
BArray = self.ffi._get_cached_btype(tp)
|
| 605 |
+
value = self.ffi.cast(BArray, value)
|
| 606 |
+
setattr(library, name, value)
|
| 607 |
+
type(library)._cffi_dir.append(name)
|
| 608 |
+
return
|
| 609 |
+
# remove ptr=<cdata 'int *'> from the library instance, and replace
|
| 610 |
+
# it by a property on the class, which reads/writes into ptr[0].
|
| 611 |
+
funcname = '_cffi_var_%s' % name
|
| 612 |
+
BFunc = self.ffi._typeof_locked(tp.get_c_name('*(*)(void)', name))[0]
|
| 613 |
+
function = module.load_function(BFunc, funcname)
|
| 614 |
+
ptr = function()
|
| 615 |
+
def getter(library):
|
| 616 |
+
return ptr[0]
|
| 617 |
+
def setter(library, value):
|
| 618 |
+
ptr[0] = value
|
| 619 |
+
setattr(type(library), name, property(getter, setter))
|
| 620 |
+
type(library)._cffi_dir.append(name)
|
| 621 |
+
|
| 622 |
+
cffimod_header = r'''
|
| 623 |
+
#include <stdio.h>
|
| 624 |
+
#include <stddef.h>
|
| 625 |
+
#include <stdarg.h>
|
| 626 |
+
#include <errno.h>
|
| 627 |
+
#include <sys/types.h> /* XXX for ssize_t on some platforms */
|
| 628 |
+
|
| 629 |
+
/* this block of #ifs should be kept exactly identical between
|
| 630 |
+
c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py
|
| 631 |
+
and cffi/_cffi_include.h */
|
| 632 |
+
#if defined(_MSC_VER)
|
| 633 |
+
# include <malloc.h> /* for alloca() */
|
| 634 |
+
# if _MSC_VER < 1600 /* MSVC < 2010 */
|
| 635 |
+
typedef __int8 int8_t;
|
| 636 |
+
typedef __int16 int16_t;
|
| 637 |
+
typedef __int32 int32_t;
|
| 638 |
+
typedef __int64 int64_t;
|
| 639 |
+
typedef unsigned __int8 uint8_t;
|
| 640 |
+
typedef unsigned __int16 uint16_t;
|
| 641 |
+
typedef unsigned __int32 uint32_t;
|
| 642 |
+
typedef unsigned __int64 uint64_t;
|
| 643 |
+
typedef __int8 int_least8_t;
|
| 644 |
+
typedef __int16 int_least16_t;
|
| 645 |
+
typedef __int32 int_least32_t;
|
| 646 |
+
typedef __int64 int_least64_t;
|
| 647 |
+
typedef unsigned __int8 uint_least8_t;
|
| 648 |
+
typedef unsigned __int16 uint_least16_t;
|
| 649 |
+
typedef unsigned __int32 uint_least32_t;
|
| 650 |
+
typedef unsigned __int64 uint_least64_t;
|
| 651 |
+
typedef __int8 int_fast8_t;
|
| 652 |
+
typedef __int16 int_fast16_t;
|
| 653 |
+
typedef __int32 int_fast32_t;
|
| 654 |
+
typedef __int64 int_fast64_t;
|
| 655 |
+
typedef unsigned __int8 uint_fast8_t;
|
| 656 |
+
typedef unsigned __int16 uint_fast16_t;
|
| 657 |
+
typedef unsigned __int32 uint_fast32_t;
|
| 658 |
+
typedef unsigned __int64 uint_fast64_t;
|
| 659 |
+
typedef __int64 intmax_t;
|
| 660 |
+
typedef unsigned __int64 uintmax_t;
|
| 661 |
+
# else
|
| 662 |
+
# include <stdint.h>
|
| 663 |
+
# endif
|
| 664 |
+
# if _MSC_VER < 1800 /* MSVC < 2013 */
|
| 665 |
+
# ifndef __cplusplus
|
| 666 |
+
typedef unsigned char _Bool;
|
| 667 |
+
# endif
|
| 668 |
+
# endif
|
| 669 |
+
#else
|
| 670 |
+
# include <stdint.h>
|
| 671 |
+
# if (defined (__SVR4) && defined (__sun)) || defined(_AIX) || defined(__hpux)
|
| 672 |
+
# include <alloca.h>
|
| 673 |
+
# endif
|
| 674 |
+
#endif
|
| 675 |
+
'''
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/cffi/verifier.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# DEPRECATED: implementation for ffi.verify()
|
| 3 |
+
#
|
| 4 |
+
import sys, os, binascii, shutil, io
|
| 5 |
+
from . import __version_verifier_modules__
|
| 6 |
+
from . import ffiplatform
|
| 7 |
+
from .error import VerificationError
|
| 8 |
+
|
| 9 |
+
if sys.version_info >= (3, 3):
|
| 10 |
+
import importlib.machinery
|
| 11 |
+
def _extension_suffixes():
|
| 12 |
+
return importlib.machinery.EXTENSION_SUFFIXES[:]
|
| 13 |
+
else:
|
| 14 |
+
import imp
|
| 15 |
+
def _extension_suffixes():
|
| 16 |
+
return [suffix for suffix, _, type in imp.get_suffixes()
|
| 17 |
+
if type == imp.C_EXTENSION]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
if sys.version_info >= (3,):
|
| 21 |
+
NativeIO = io.StringIO
|
| 22 |
+
else:
|
| 23 |
+
class NativeIO(io.BytesIO):
|
| 24 |
+
def write(self, s):
|
| 25 |
+
if isinstance(s, unicode):
|
| 26 |
+
s = s.encode('ascii')
|
| 27 |
+
super(NativeIO, self).write(s)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Verifier(object):
|
| 31 |
+
|
| 32 |
+
def __init__(self, ffi, preamble, tmpdir=None, modulename=None,
|
| 33 |
+
ext_package=None, tag='', force_generic_engine=False,
|
| 34 |
+
source_extension='.c', flags=None, relative_to=None, **kwds):
|
| 35 |
+
if ffi._parser._uses_new_feature:
|
| 36 |
+
raise VerificationError(
|
| 37 |
+
"feature not supported with ffi.verify(), but only "
|
| 38 |
+
"with ffi.set_source(): %s" % (ffi._parser._uses_new_feature,))
|
| 39 |
+
self.ffi = ffi
|
| 40 |
+
self.preamble = preamble
|
| 41 |
+
if not modulename:
|
| 42 |
+
flattened_kwds = ffiplatform.flatten(kwds)
|
| 43 |
+
vengine_class = _locate_engine_class(ffi, force_generic_engine)
|
| 44 |
+
self._vengine = vengine_class(self)
|
| 45 |
+
self._vengine.patch_extension_kwds(kwds)
|
| 46 |
+
self.flags = flags
|
| 47 |
+
self.kwds = self.make_relative_to(kwds, relative_to)
|
| 48 |
+
#
|
| 49 |
+
if modulename:
|
| 50 |
+
if tag:
|
| 51 |
+
raise TypeError("can't specify both 'modulename' and 'tag'")
|
| 52 |
+
else:
|
| 53 |
+
key = '\x00'.join([sys.version[:3], __version_verifier_modules__,
|
| 54 |
+
preamble, flattened_kwds] +
|
| 55 |
+
ffi._cdefsources)
|
| 56 |
+
if sys.version_info >= (3,):
|
| 57 |
+
key = key.encode('utf-8')
|
| 58 |
+
k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff)
|
| 59 |
+
k1 = k1.lstrip('0x').rstrip('L')
|
| 60 |
+
k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff)
|
| 61 |
+
k2 = k2.lstrip('0').rstrip('L')
|
| 62 |
+
modulename = '_cffi_%s_%s%s%s' % (tag, self._vengine._class_key,
|
| 63 |
+
k1, k2)
|
| 64 |
+
suffix = _get_so_suffixes()[0]
|
| 65 |
+
self.tmpdir = tmpdir or _caller_dir_pycache()
|
| 66 |
+
self.sourcefilename = os.path.join(self.tmpdir, modulename + source_extension)
|
| 67 |
+
self.modulefilename = os.path.join(self.tmpdir, modulename + suffix)
|
| 68 |
+
self.ext_package = ext_package
|
| 69 |
+
self._has_source = False
|
| 70 |
+
self._has_module = False
|
| 71 |
+
|
| 72 |
+
def write_source(self, file=None):
|
| 73 |
+
"""Write the C source code. It is produced in 'self.sourcefilename',
|
| 74 |
+
which can be tweaked beforehand."""
|
| 75 |
+
with self.ffi._lock:
|
| 76 |
+
if self._has_source and file is None:
|
| 77 |
+
raise VerificationError(
|
| 78 |
+
"source code already written")
|
| 79 |
+
self._write_source(file)
|
| 80 |
+
|
| 81 |
+
def compile_module(self):
|
| 82 |
+
"""Write the C source code (if not done already) and compile it.
|
| 83 |
+
This produces a dynamic link library in 'self.modulefilename'."""
|
| 84 |
+
with self.ffi._lock:
|
| 85 |
+
if self._has_module:
|
| 86 |
+
raise VerificationError("module already compiled")
|
| 87 |
+
if not self._has_source:
|
| 88 |
+
self._write_source()
|
| 89 |
+
self._compile_module()
|
| 90 |
+
|
| 91 |
+
def load_library(self):
|
| 92 |
+
"""Get a C module from this Verifier instance.
|
| 93 |
+
Returns an instance of a FFILibrary class that behaves like the
|
| 94 |
+
objects returned by ffi.dlopen(), but that delegates all
|
| 95 |
+
operations to the C module. If necessary, the C code is written
|
| 96 |
+
and compiled first.
|
| 97 |
+
"""
|
| 98 |
+
with self.ffi._lock:
|
| 99 |
+
if not self._has_module:
|
| 100 |
+
self._locate_module()
|
| 101 |
+
if not self._has_module:
|
| 102 |
+
if not self._has_source:
|
| 103 |
+
self._write_source()
|
| 104 |
+
self._compile_module()
|
| 105 |
+
return self._load_library()
|
| 106 |
+
|
| 107 |
+
def get_module_name(self):
|
| 108 |
+
basename = os.path.basename(self.modulefilename)
|
| 109 |
+
# kill both the .so extension and the other .'s, as introduced
|
| 110 |
+
# by Python 3: 'basename.cpython-33m.so'
|
| 111 |
+
basename = basename.split('.', 1)[0]
|
| 112 |
+
# and the _d added in Python 2 debug builds --- but try to be
|
| 113 |
+
# conservative and not kill a legitimate _d
|
| 114 |
+
if basename.endswith('_d') and hasattr(sys, 'gettotalrefcount'):
|
| 115 |
+
basename = basename[:-2]
|
| 116 |
+
return basename
|
| 117 |
+
|
| 118 |
+
def get_extension(self):
|
| 119 |
+
ffiplatform._hack_at_distutils() # backward compatibility hack
|
| 120 |
+
if not self._has_source:
|
| 121 |
+
with self.ffi._lock:
|
| 122 |
+
if not self._has_source:
|
| 123 |
+
self._write_source()
|
| 124 |
+
sourcename = ffiplatform.maybe_relative_path(self.sourcefilename)
|
| 125 |
+
modname = self.get_module_name()
|
| 126 |
+
return ffiplatform.get_extension(sourcename, modname, **self.kwds)
|
| 127 |
+
|
| 128 |
+
def generates_python_module(self):
|
| 129 |
+
return self._vengine._gen_python_module
|
| 130 |
+
|
| 131 |
+
def make_relative_to(self, kwds, relative_to):
|
| 132 |
+
if relative_to and os.path.dirname(relative_to):
|
| 133 |
+
dirname = os.path.dirname(relative_to)
|
| 134 |
+
kwds = kwds.copy()
|
| 135 |
+
for key in ffiplatform.LIST_OF_FILE_NAMES:
|
| 136 |
+
if key in kwds:
|
| 137 |
+
lst = kwds[key]
|
| 138 |
+
if not isinstance(lst, (list, tuple)):
|
| 139 |
+
raise TypeError("keyword '%s' should be a list or tuple"
|
| 140 |
+
% (key,))
|
| 141 |
+
lst = [os.path.join(dirname, fn) for fn in lst]
|
| 142 |
+
kwds[key] = lst
|
| 143 |
+
return kwds
|
| 144 |
+
|
| 145 |
+
# ----------
|
| 146 |
+
|
| 147 |
+
def _locate_module(self):
|
| 148 |
+
if not os.path.isfile(self.modulefilename):
|
| 149 |
+
if self.ext_package:
|
| 150 |
+
try:
|
| 151 |
+
pkg = __import__(self.ext_package, None, None, ['__doc__'])
|
| 152 |
+
except ImportError:
|
| 153 |
+
return # cannot import the package itself, give up
|
| 154 |
+
# (e.g. it might be called differently before installation)
|
| 155 |
+
path = pkg.__path__
|
| 156 |
+
else:
|
| 157 |
+
path = None
|
| 158 |
+
filename = self._vengine.find_module(self.get_module_name(), path,
|
| 159 |
+
_get_so_suffixes())
|
| 160 |
+
if filename is None:
|
| 161 |
+
return
|
| 162 |
+
self.modulefilename = filename
|
| 163 |
+
self._vengine.collect_types()
|
| 164 |
+
self._has_module = True
|
| 165 |
+
|
| 166 |
+
def _write_source_to(self, file):
|
| 167 |
+
self._vengine._f = file
|
| 168 |
+
try:
|
| 169 |
+
self._vengine.write_source_to_f()
|
| 170 |
+
finally:
|
| 171 |
+
del self._vengine._f
|
| 172 |
+
|
| 173 |
+
def _write_source(self, file=None):
|
| 174 |
+
if file is not None:
|
| 175 |
+
self._write_source_to(file)
|
| 176 |
+
else:
|
| 177 |
+
# Write our source file to an in memory file.
|
| 178 |
+
f = NativeIO()
|
| 179 |
+
self._write_source_to(f)
|
| 180 |
+
source_data = f.getvalue()
|
| 181 |
+
|
| 182 |
+
# Determine if this matches the current file
|
| 183 |
+
if os.path.exists(self.sourcefilename):
|
| 184 |
+
with open(self.sourcefilename, "r") as fp:
|
| 185 |
+
needs_written = not (fp.read() == source_data)
|
| 186 |
+
else:
|
| 187 |
+
needs_written = True
|
| 188 |
+
|
| 189 |
+
# Actually write the file out if it doesn't match
|
| 190 |
+
if needs_written:
|
| 191 |
+
_ensure_dir(self.sourcefilename)
|
| 192 |
+
with open(self.sourcefilename, "w") as fp:
|
| 193 |
+
fp.write(source_data)
|
| 194 |
+
|
| 195 |
+
# Set this flag
|
| 196 |
+
self._has_source = True
|
| 197 |
+
|
| 198 |
+
def _compile_module(self):
|
| 199 |
+
# compile this C source
|
| 200 |
+
tmpdir = os.path.dirname(self.sourcefilename)
|
| 201 |
+
outputfilename = ffiplatform.compile(tmpdir, self.get_extension())
|
| 202 |
+
try:
|
| 203 |
+
same = ffiplatform.samefile(outputfilename, self.modulefilename)
|
| 204 |
+
except OSError:
|
| 205 |
+
same = False
|
| 206 |
+
if not same:
|
| 207 |
+
_ensure_dir(self.modulefilename)
|
| 208 |
+
shutil.move(outputfilename, self.modulefilename)
|
| 209 |
+
self._has_module = True
|
| 210 |
+
|
| 211 |
+
def _load_library(self):
|
| 212 |
+
assert self._has_module
|
| 213 |
+
if self.flags is not None:
|
| 214 |
+
return self._vengine.load_library(self.flags)
|
| 215 |
+
else:
|
| 216 |
+
return self._vengine.load_library()
|
| 217 |
+
|
| 218 |
+
# ____________________________________________________________
|
| 219 |
+
|
| 220 |
+
_FORCE_GENERIC_ENGINE = False # for tests
|
| 221 |
+
|
| 222 |
+
def _locate_engine_class(ffi, force_generic_engine):
|
| 223 |
+
if _FORCE_GENERIC_ENGINE:
|
| 224 |
+
force_generic_engine = True
|
| 225 |
+
if not force_generic_engine:
|
| 226 |
+
if '__pypy__' in sys.builtin_module_names:
|
| 227 |
+
force_generic_engine = True
|
| 228 |
+
else:
|
| 229 |
+
try:
|
| 230 |
+
import _cffi_backend
|
| 231 |
+
except ImportError:
|
| 232 |
+
_cffi_backend = '?'
|
| 233 |
+
if ffi._backend is not _cffi_backend:
|
| 234 |
+
force_generic_engine = True
|
| 235 |
+
if force_generic_engine:
|
| 236 |
+
from . import vengine_gen
|
| 237 |
+
return vengine_gen.VGenericEngine
|
| 238 |
+
else:
|
| 239 |
+
from . import vengine_cpy
|
| 240 |
+
return vengine_cpy.VCPythonEngine
|
| 241 |
+
|
| 242 |
+
# ____________________________________________________________
|
| 243 |
+
|
| 244 |
+
_TMPDIR = None
|
| 245 |
+
|
| 246 |
+
def _caller_dir_pycache():
|
| 247 |
+
if _TMPDIR:
|
| 248 |
+
return _TMPDIR
|
| 249 |
+
result = os.environ.get('CFFI_TMPDIR')
|
| 250 |
+
if result:
|
| 251 |
+
return result
|
| 252 |
+
filename = sys._getframe(2).f_code.co_filename
|
| 253 |
+
return os.path.abspath(os.path.join(os.path.dirname(filename),
|
| 254 |
+
'__pycache__'))
|
| 255 |
+
|
| 256 |
+
def set_tmpdir(dirname):
|
| 257 |
+
"""Set the temporary directory to use instead of __pycache__."""
|
| 258 |
+
global _TMPDIR
|
| 259 |
+
_TMPDIR = dirname
|
| 260 |
+
|
| 261 |
+
def cleanup_tmpdir(tmpdir=None, keep_so=False):
|
| 262 |
+
"""Clean up the temporary directory by removing all files in it
|
| 263 |
+
called `_cffi_*.{c,so}` as well as the `build` subdirectory."""
|
| 264 |
+
tmpdir = tmpdir or _caller_dir_pycache()
|
| 265 |
+
try:
|
| 266 |
+
filelist = os.listdir(tmpdir)
|
| 267 |
+
except OSError:
|
| 268 |
+
return
|
| 269 |
+
if keep_so:
|
| 270 |
+
suffix = '.c' # only remove .c files
|
| 271 |
+
else:
|
| 272 |
+
suffix = _get_so_suffixes()[0].lower()
|
| 273 |
+
for fn in filelist:
|
| 274 |
+
if fn.lower().startswith('_cffi_') and (
|
| 275 |
+
fn.lower().endswith(suffix) or fn.lower().endswith('.c')):
|
| 276 |
+
try:
|
| 277 |
+
os.unlink(os.path.join(tmpdir, fn))
|
| 278 |
+
except OSError:
|
| 279 |
+
pass
|
| 280 |
+
clean_dir = [os.path.join(tmpdir, 'build')]
|
| 281 |
+
for dir in clean_dir:
|
| 282 |
+
try:
|
| 283 |
+
for fn in os.listdir(dir):
|
| 284 |
+
fn = os.path.join(dir, fn)
|
| 285 |
+
if os.path.isdir(fn):
|
| 286 |
+
clean_dir.append(fn)
|
| 287 |
+
else:
|
| 288 |
+
os.unlink(fn)
|
| 289 |
+
except OSError:
|
| 290 |
+
pass
|
| 291 |
+
|
| 292 |
+
def _get_so_suffixes():
|
| 293 |
+
suffixes = _extension_suffixes()
|
| 294 |
+
if not suffixes:
|
| 295 |
+
# bah, no C_EXTENSION available. Occurs on pypy without cpyext
|
| 296 |
+
if sys.platform == 'win32':
|
| 297 |
+
suffixes = [".pyd"]
|
| 298 |
+
else:
|
| 299 |
+
suffixes = [".so"]
|
| 300 |
+
|
| 301 |
+
return suffixes
|
| 302 |
+
|
| 303 |
+
def _ensure_dir(filename):
|
| 304 |
+
dirname = os.path.dirname(filename)
|
| 305 |
+
if dirname and not os.path.isdir(dirname):
|
| 306 |
+
os.makedirs(dirname)
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/chardet/enums.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
All of the Enums that are used throughout the chardet package.
|
| 3 |
+
|
| 4 |
+
:author: Dan Blanchard (dan.blanchard@gmail.com)
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class InputState(object):
|
| 9 |
+
"""
|
| 10 |
+
This enum represents the different states a universal detector can be in.
|
| 11 |
+
"""
|
| 12 |
+
PURE_ASCII = 0
|
| 13 |
+
ESC_ASCII = 1
|
| 14 |
+
HIGH_BYTE = 2
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class LanguageFilter(object):
|
| 18 |
+
"""
|
| 19 |
+
This enum represents the different language filters we can apply to a
|
| 20 |
+
``UniversalDetector``.
|
| 21 |
+
"""
|
| 22 |
+
CHINESE_SIMPLIFIED = 0x01
|
| 23 |
+
CHINESE_TRADITIONAL = 0x02
|
| 24 |
+
JAPANESE = 0x04
|
| 25 |
+
KOREAN = 0x08
|
| 26 |
+
NON_CJK = 0x10
|
| 27 |
+
ALL = 0x1F
|
| 28 |
+
CHINESE = CHINESE_SIMPLIFIED | CHINESE_TRADITIONAL
|
| 29 |
+
CJK = CHINESE | JAPANESE | KOREAN
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ProbingState(object):
|
| 33 |
+
"""
|
| 34 |
+
This enum represents the different states a prober can be in.
|
| 35 |
+
"""
|
| 36 |
+
DETECTING = 0
|
| 37 |
+
FOUND_IT = 1
|
| 38 |
+
NOT_ME = 2
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class MachineState(object):
|
| 42 |
+
"""
|
| 43 |
+
This enum represents the different states a state machine can be in.
|
| 44 |
+
"""
|
| 45 |
+
START = 0
|
| 46 |
+
ERROR = 1
|
| 47 |
+
ITS_ME = 2
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class SequenceLikelihood(object):
|
| 51 |
+
"""
|
| 52 |
+
This enum represents the likelihood of a character following the previous one.
|
| 53 |
+
"""
|
| 54 |
+
NEGATIVE = 0
|
| 55 |
+
UNLIKELY = 1
|
| 56 |
+
LIKELY = 2
|
| 57 |
+
POSITIVE = 3
|
| 58 |
+
|
| 59 |
+
@classmethod
|
| 60 |
+
def get_num_categories(cls):
|
| 61 |
+
""":returns: The number of likelihood categories in the enum."""
|
| 62 |
+
return 4
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class CharacterCategory(object):
|
| 66 |
+
"""
|
| 67 |
+
This enum represents the different categories language models for
|
| 68 |
+
``SingleByteCharsetProber`` put characters into.
|
| 69 |
+
|
| 70 |
+
Anything less than CONTROL is considered a letter.
|
| 71 |
+
"""
|
| 72 |
+
UNDEFINED = 255
|
| 73 |
+
LINE_BREAK = 254
|
| 74 |
+
SYMBOL = 253
|
| 75 |
+
DIGIT = 252
|
| 76 |
+
CONTROL = 251
|
benchmark/NYU_CTF_Bench/test/2019/CSAW-Quals/crypto/brillouin/lib/python2.7/site-packages/chardet/escprober.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
######################## BEGIN LICENSE BLOCK ########################
|
| 2 |
+
# The Original Code is mozilla.org code.
|
| 3 |
+
#
|
| 4 |
+
# The Initial Developer of the Original Code is
|
| 5 |
+
# Netscape Communications Corporation.
|
| 6 |
+
# Portions created by the Initial Developer are Copyright (C) 1998
|
| 7 |
+
# the Initial Developer. All Rights Reserved.
|
| 8 |
+
#
|
| 9 |
+
# Contributor(s):
|
| 10 |
+
# Mark Pilgrim - port to Python
|
| 11 |
+
#
|
| 12 |
+
# This library is free software; you can redistribute it and/or
|
| 13 |
+
# modify it under the terms of the GNU Lesser General Public
|
| 14 |
+
# License as published by the Free Software Foundation; either
|
| 15 |
+
# version 2.1 of the License, or (at your option) any later version.
|
| 16 |
+
#
|
| 17 |
+
# This library is distributed in the hope that it will be useful,
|
| 18 |
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 19 |
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
| 20 |
+
# Lesser General Public License for more details.
|
| 21 |
+
#
|
| 22 |
+
# You should have received a copy of the GNU Lesser General Public
|
| 23 |
+
# License along with this library; if not, write to the Free Software
|
| 24 |
+
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
|
| 25 |
+
# 02110-1301 USA
|
| 26 |
+
######################### END LICENSE BLOCK #########################
|
| 27 |
+
|
| 28 |
+
from .charsetprober import CharSetProber
|
| 29 |
+
from .codingstatemachine import CodingStateMachine
|
| 30 |
+
from .enums import LanguageFilter, ProbingState, MachineState
|
| 31 |
+
from .escsm import (HZ_SM_MODEL, ISO2022CN_SM_MODEL, ISO2022JP_SM_MODEL,
|
| 32 |
+
ISO2022KR_SM_MODEL)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class EscCharSetProber(CharSetProber):
|
| 36 |
+
"""
|
| 37 |
+
This CharSetProber uses a "code scheme" approach for detecting encodings,
|
| 38 |
+
whereby easily recognizable escape or shift sequences are relied on to
|
| 39 |
+
identify these encodings.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def __init__(self, lang_filter=None):
|
| 43 |
+
super(EscCharSetProber, self).__init__(lang_filter=lang_filter)
|
| 44 |
+
self.coding_sm = []
|
| 45 |
+
if self.lang_filter & LanguageFilter.CHINESE_SIMPLIFIED:
|
| 46 |
+
self.coding_sm.append(CodingStateMachine(HZ_SM_MODEL))
|
| 47 |
+
self.coding_sm.append(CodingStateMachine(ISO2022CN_SM_MODEL))
|
| 48 |
+
if self.lang_filter & LanguageFilter.JAPANESE:
|
| 49 |
+
self.coding_sm.append(CodingStateMachine(ISO2022JP_SM_MODEL))
|
| 50 |
+
if self.lang_filter & LanguageFilter.KOREAN:
|
| 51 |
+
self.coding_sm.append(CodingStateMachine(ISO2022KR_SM_MODEL))
|
| 52 |
+
self.active_sm_count = None
|
| 53 |
+
self._detected_charset = None
|
| 54 |
+
self._detected_language = None
|
| 55 |
+
self._state = None
|
| 56 |
+
self.reset()
|
| 57 |
+
|
| 58 |
+
def reset(self):
|
| 59 |
+
super(EscCharSetProber, self).reset()
|
| 60 |
+
for coding_sm in self.coding_sm:
|
| 61 |
+
if not coding_sm:
|
| 62 |
+
continue
|
| 63 |
+
coding_sm.active = True
|
| 64 |
+
coding_sm.reset()
|
| 65 |
+
self.active_sm_count = len(self.coding_sm)
|
| 66 |
+
self._detected_charset = None
|
| 67 |
+
self._detected_language = None
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def charset_name(self):
|
| 71 |
+
return self._detected_charset
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def language(self):
|
| 75 |
+
return self._detected_language
|
| 76 |
+
|
| 77 |
+
def get_confidence(self):
|
| 78 |
+
if self._detected_charset:
|
| 79 |
+
return 0.99
|
| 80 |
+
else:
|
| 81 |
+
return 0.00
|
| 82 |
+
|
| 83 |
+
def feed(self, byte_str):
|
| 84 |
+
for c in byte_str:
|
| 85 |
+
for coding_sm in self.coding_sm:
|
| 86 |
+
if not coding_sm or not coding_sm.active:
|
| 87 |
+
continue
|
| 88 |
+
coding_state = coding_sm.next_state(c)
|
| 89 |
+
if coding_state == MachineState.ERROR:
|
| 90 |
+
coding_sm.active = False
|
| 91 |
+
self.active_sm_count -= 1
|
| 92 |
+
if self.active_sm_count <= 0:
|
| 93 |
+
self._state = ProbingState.NOT_ME
|
| 94 |
+
return self.state
|
| 95 |
+
elif coding_state == MachineState.ITS_ME:
|
| 96 |
+
self._state = ProbingState.FOUND_IT
|
| 97 |
+
self._detected_charset = coding_sm.get_coding_state_machine()
|
| 98 |
+
self._detected_language = coding_sm.language
|
| 99 |
+
return self.state
|
| 100 |
+
|
| 101 |
+
return self.state
|