├── .gitignore
├── LICENSE.txt
├── NOTICE.txt
├── PyVM.sln
├── README.txt
├── src
├── BufferAccess.cpp
├── CodeDefinition.cpp
├── CodeDefinition.h
├── ObjPool.h
├── OpImp.h
├── PyCompile.cpp
├── PyCompile.h
├── PyVM.cpp
├── PyVM.h
├── VarArray.h
├── baseObject.h
├── bufferaccess.h
├── cfunc.h
├── defs.h
├── except.h
├── gen_string_method_names.h
├── instruction.cpp
├── libPyVM.vcxproj
├── libPyVM.vcxproj.filters
├── log.h
├── makeStringSwitch.py
├── objects.cpp
├── objects.h
├── opcodes.h
├── opcodes_def.h
├── pythonRoot.props
├── utils.cpp
└── utils.h
└── test
├── PyVMTest.cpp
├── VarArrayTest.cpp
├── imped_module.py
├── imped_module2.py
├── main.cpp
├── myTest.h
├── test_module.py
├── tester.vcxproj
└── tester.vcxproj.filters
/.gitignore:
--------------------------------------------------------------------------------
1 | /bin
2 | /obj
3 | *.sdf
4 | /.vs
5 | *.opensdf
6 | *.pyc
7 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/NOTICE.txt:
--------------------------------------------------------------------------------
1 | PyVM
2 | Copyright (C) 2015 by Intigua, Inc.
3 | This product includes software developed at
4 | Intigua, Inc. (http://www.intigua.com/).
--------------------------------------------------------------------------------
/PyVM.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.23107.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tester", "test\tester.vcxproj", "{F894A474-8167-46FF-86A3-ED249C8CAE82}"
7 | EndProject
8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libPyVM", "src\libPyVM.vcxproj", "{36027395-A85C-4DCE-A859-C23D1E3B9F87}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Win32 = Debug|Win32
13 | Debug|x64 = Debug|x64
14 | Release|Win32 = Release|Win32
15 | Release|x64 = Release|x64
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {F894A474-8167-46FF-86A3-ED249C8CAE82}.Debug|Win32.ActiveCfg = Debug|Win32
19 | {F894A474-8167-46FF-86A3-ED249C8CAE82}.Debug|Win32.Build.0 = Debug|Win32
20 | {F894A474-8167-46FF-86A3-ED249C8CAE82}.Debug|x64.ActiveCfg = Debug|x64
21 | {F894A474-8167-46FF-86A3-ED249C8CAE82}.Debug|x64.Build.0 = Debug|x64
22 | {F894A474-8167-46FF-86A3-ED249C8CAE82}.Release|Win32.ActiveCfg = Release|Win32
23 | {F894A474-8167-46FF-86A3-ED249C8CAE82}.Release|Win32.Build.0 = Release|Win32
24 | {F894A474-8167-46FF-86A3-ED249C8CAE82}.Release|x64.ActiveCfg = Release|x64
25 | {F894A474-8167-46FF-86A3-ED249C8CAE82}.Release|x64.Build.0 = Release|x64
26 | {36027395-A85C-4DCE-A859-C23D1E3B9F87}.Debug|Win32.ActiveCfg = Debug|Win32
27 | {36027395-A85C-4DCE-A859-C23D1E3B9F87}.Debug|Win32.Build.0 = Debug|Win32
28 | {36027395-A85C-4DCE-A859-C23D1E3B9F87}.Debug|x64.ActiveCfg = Debug|x64
29 | {36027395-A85C-4DCE-A859-C23D1E3B9F87}.Debug|x64.Build.0 = Debug|x64
30 | {36027395-A85C-4DCE-A859-C23D1E3B9F87}.Release|Win32.ActiveCfg = Release|Win32
31 | {36027395-A85C-4DCE-A859-C23D1E3B9F87}.Release|Win32.Build.0 = Release|Win32
32 | {36027395-A85C-4DCE-A859-C23D1E3B9F87}.Release|x64.ActiveCfg = Release|x64
33 | {36027395-A85C-4DCE-A859-C23D1E3B9F87}.Release|x64.Build.0 = Release|x64
34 | EndGlobalSection
35 | GlobalSection(SolutionProperties) = preSolution
36 | HideSolutionNode = FALSE
37 | EndGlobalSection
38 | EndGlobal
39 |
--------------------------------------------------------------------------------
/README.txt:
--------------------------------------------------------------------------------
1 | libPyVM is a compact Python 2.7 interpreter that can be used in various places where the standard CPython interpreter is not appropriate or cumbersome to use.
2 |
3 | - The entire interpreter is fully instantiatable. This means you can have multiple interpreters running in a single process. There is no global state or variables.
4 | - Very light weight. The entire interpreter is about 6000 lines of code, excluding tests and generated code.
5 | - All input and output interfaces are controllable. not dependency on environment variables or external files.
6 | - Predictable memory management - Save and restore memory snapshots instead of a garbage collector.
7 | - Runs compiled (byte-code) .pyc files produced by the standard CPython
8 | - Can be optionally linked to CPython for the purpose of compiling python code into bytecode and running an interactive interpreter.
9 | - Python code can easily interface with native C++ using an interface similar to boost::python
10 | - Written in standard C++11.
11 |
12 |
13 | Building
14 | ========
15 |
16 | - Open PyVM.sln using Visual Studio 2015 (Community edition can be downloaded for free)
17 |
18 | - To build with linking to CPython open src/pythonRoot.props with a text editor and changed
19 | C:\Python27
20 | to point to where your installation of Python 2.7 resides.
21 | From Visual Studio this can be reached from -
22 | VIEW -> Property Manager -> project libPyVM -> "Debug|Win32" -> double click "pythonRoot" -> User Macros
23 | (This changes the root for all configs, not just Debug|Win32)
24 |
25 | Note that if your python27.lib is compiled for 32 bit, only the "Win32" configurations are going to successfully link and if it is compiled for 64 bit, only the "x64" configurations will build. It depends on which version of python you downloaded.
26 |
27 | - To build without CPython change in src/pythonRoot.props the variable USE_CPYTHON to 0
28 | From Visual Studio -
29 | VIEW -> Property Manager -> project libPyVM -> "Debug|Win32" -> double click "pythonRoot" -> C/C++ -> Preprocessor
30 | in "Preprocessor Definitions" change USE_CPYTHON to 0
31 |
32 | - Build the solution
33 | - Run the tester
34 | in the tester main.cpp you can choose between different main() functions which demonstrate aspects the the interpreter
35 | to run them, change main() to _main() and one of the other functions to be main()
36 |
37 |
38 | To build in earlier versions of Visual studio (up to 2010), open the project properties window, under 'General', change 'Platform Toolset' to the version of Visual Studio that you have.
--------------------------------------------------------------------------------
/src/BufferAccess.cpp:
--------------------------------------------------------------------------------
1 | // Copyright 2015 by Intigua, Inc.
2 | // Licensed under the Apache License, Version 2.0 (the "License");
3 | // you may not use this file except in compliance with the License.
4 | // You may obtain a copy of the License at
5 | // http://www.apache.org/licenses/LICENSE-2.0
6 | // Unless required by applicable law or agreed to in writing, software
7 | // distributed under the License is distributed on an "AS IS" BASIS,
8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 | // See the License for the specific language governing permissions and
10 | // limitations under the License.
11 | #include "BufferAccess.h"
12 |
13 |
14 | #define CATCH_ACCESS_VIOLATION(func) catch(const exception&) { throw; }\
15 | catch(...) { THROW("Exception in " #func " " << (void*)m_p << "+" << m_offset); }
16 | // in case we didn't have ExceptionsTranslator
17 |
18 | template
19 | ObjRef AccessBuffer::readNum() {
20 | try {
21 | T v = 0;
22 | memcpy(&v, m_p + m_offset, sizeof(T));
23 | m_offset += sizeof(T);
24 | return m_vm->alloc(new IntObject(v));
25 | } CATCH_ACCESS_VIOLATION(readNum)
26 | }
27 | template
28 | void AccessBuffer::writeNum(const ObjRef& o) {
29 | try {
30 | T v = extract(o);
31 | memcpy(m_p + m_offset, &v, sizeof(v));
32 | m_offset += sizeof(v);
33 | } CATCH_ACCESS_VIOLATION(writeNum)
34 | }
35 |
36 | ObjRef AccessBuffer::readPtr() {
37 | return readNum();
38 | }
39 | ObjRef AccessBuffer::readInt(int numBytes) {
40 | switch (numBytes) {
41 | case 1: return readNum();
42 | case 2: return readNum();
43 | case 4: return readNum();
44 | case 8: return readNum();
45 | default: THROW("can't readInt " << numBytes);
46 | }
47 | }
48 | ObjRef AccessBuffer::readCStr() {
49 | try {
50 | int len = (int)strlen(m_p + m_offset);
51 | ObjRef r = readBuf(len);
52 | m_offset += 1; // consume nullptr termination
53 | return r;
54 | } CATCH_ACCESS_VIOLATION(readCStr)
55 | }
56 | ObjRef AccessBuffer::readBuf(int len) {
57 | try {
58 | string s(m_p + m_offset, len);
59 | m_offset += len;
60 | return m_vm->makeFromT(s);
61 | } CATCH_ACCESS_VIOLATION(readBuf)
62 | }
63 | ObjRef AccessBuffer::readWCStr(){
64 | try {
65 | int count = (int)wcslen((wchar_t*)(m_p + m_offset));
66 | wstring s;
67 | s.resize(count);
68 | memcpy((char*)s.data(), m_p + m_offset, count * sizeof(wchar_t));
69 | m_offset += (count + 1) * sizeof(wchar_t); // consume nullptr termination
70 | return m_vm->makeFromT(s);
71 | } CATCH_ACCESS_VIOLATION(readWCStr)
72 | }
73 |
74 | void AccessBuffer::writePtr(const ObjRef& v) {
75 | writeNum(v);
76 | }
77 | void AccessBuffer::writeInt(int numBytes, const ObjRef v) {
78 | switch (numBytes) {
79 | case 1: return writeNum(v);
80 | //case 2: return writeNum(v); # TODO - Fix, Not compiling
81 | case 4: return writeNum(v);
82 | case 8: return writeNum(v);
83 | default: THROW("can't writeInt " << numBytes);
84 | }
85 | }
86 |
87 | void AccessBuffer::writeCStr(const string& s) {
88 | try {
89 | int count = (int)s.length() + 1;
90 | memcpy(m_p + m_offset, (char*)s.c_str(), count); // c_str guarantees that it will be nullptr terminated
91 | m_offset += count;
92 | } CATCH_ACCESS_VIOLATION(writeCStr)
93 | }
94 |
95 | void AccessBuffer::seekBytes(int origin, int offset) {
96 | int res = 0;
97 | if (origin == ORIGIN_BEG)
98 | res = offset;
99 | else if (origin == ORIGIN_CUR)
100 | res = m_offset + offset;
101 | else
102 | THROW("AccessBuffer::seekBytes: unexpected origin value " << origin);
103 | CHECK(res >= 0, "AccessBuffer::seekBytes: seek result is negative " << res);
104 | m_offset = res;
105 | }
106 |
107 |
108 | ClassObjRef AccessBuffer::addToModule(const ModuleObjRef& mod) {
109 | auto cls = mod->class_("AccessBuffer", CtorDef());
110 |
111 | cls->def(&AccessBuffer::readPtr, "readPtr");
112 | cls->def(&AccessBuffer::readInt, "readInt");
113 | cls->def(&AccessBuffer::readCStr, "readCStr");
114 | cls->def(&AccessBuffer::readWCStr, "readWCStr");
115 | cls->def(&AccessBuffer::readBuf, "readBuf");
116 |
117 | cls->def(&AccessBuffer::writeCStr, "writeCStr");
118 | cls->def(&AccessBuffer::writePtr, "writePtr");
119 | cls->def(&AccessBuffer::writeInt, "writeInt");
120 |
121 | cls->def(&AccessBuffer::offset, "offset");
122 | cls->def(&AccessBuffer::setOffset, "setOffset");
123 | cls->def(&AccessBuffer::c_ptr, "c_ptr");
124 |
125 | cls->def(&AccessBuffer::seekBytes, "seekBytes");
126 | cls->addMember(mod->m_vm->makeFromT((int)ORIGIN_BEG), "ORIGIN_BEG");
127 | cls->addMember(mod->m_vm->makeFromT((int)ORIGIN_CUR), "ORIGIN_CUR");
128 | cls->addMember(mod->m_vm->makeFromT(sizeof(void*)), "SIZEOF_PTR");
129 |
130 | return cls;
131 | }
132 |
133 |
134 | //---------------------------------------------------------------------------------------------
135 |
136 | template
137 | void BufferBuilder::writeNum(const ObjRef& o) {
138 | if (m_offset + sizeof(T) > m_buf.size())
139 | m_buf.resize(m_offset + sizeof(T));
140 | T v = extract(o);
141 | memcpy((char*)m_buf.data() + m_offset, &v, sizeof(T));
142 | m_offset += sizeof(T);
143 | }
144 |
145 | void BufferBuilder::writePtr(const ObjRef& v) {
146 | writeNum(v);
147 | }
148 |
149 | void BufferBuilder::writeInt(int numBytes, const ObjRef v) {
150 | switch (numBytes) {
151 | case 1: return writeNum(v);
152 | case 2: return writeNum(v);
153 | case 4: return writeNum(v);
154 | case 8: return writeNum(v);
155 | default: THROW("can't writeInt " << numBytes);
156 | }
157 | }
158 |
159 | void BufferBuilder::writeCStr(const string& s) {
160 | if (m_offset + s.length() + 1 > m_buf.size())
161 | m_buf.resize(m_offset + s.length() + 1);
162 | memcpy((char*)m_buf.data() + m_offset, s.c_str(), s.length() + 1);
163 | m_offset += (int)s.length() + 1;
164 | }
165 |
166 | ClassObjRef BufferBuilder::addToModule(const ModuleObjRef& mod) {
167 | auto cls = mod->class_("BufferBuilder", CtorDef());
168 |
169 | cls->def(&BufferBuilder::writePtr, "writePtr");
170 | cls->def(&BufferBuilder::writeInt, "writeInt");
171 | cls->def(&BufferBuilder::writeCStr, "writeCStr");
172 |
173 | cls->def(&BufferBuilder::resize, "resize");
174 | cls->def(&BufferBuilder::size, "size");
175 | cls->def(&BufferBuilder::c_ptr, "c_ptr");
176 | cls->def(&BufferBuilder::str, "str");
177 | return cls;
178 | }
179 |
180 |
181 |
182 |
--------------------------------------------------------------------------------
/src/CodeDefinition.cpp:
--------------------------------------------------------------------------------
1 | // Copyright 2015 by Intigua, Inc.
2 | // Licensed under the Apache License, Version 2.0 (the "License");
3 | // you may not use this file except in compliance with the License.
4 | // You may obtain a copy of the License at
5 | // http://www.apache.org/licenses/LICENSE-2.0
6 | // Unless required by applicable law or agreed to in writing, software
7 | // distributed under the License is distributed on an "AS IS" BASIS,
8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 | // See the License for the specific language governing permissions and
10 | // limitations under the License.
11 | #include "objects.h"
12 | #include "CodeDefinition.h"
13 |
14 | class Deserialize
15 | {
16 | public:
17 | Deserialize(istream& ins) : m_in(ins)
18 | {}
19 | template
20 | T read() {
21 | T v;
22 | m_in.read((char*)&v, sizeof(T));
23 | return v;
24 | }
25 | string readStr(uint count) {
26 | string s;
27 | s.resize(count);
28 | m_in.read((char*)s.data(), count);
29 | return s;
30 | }
31 |
32 | vector m_internedStr;
33 | int offset() const {
34 | return (int)m_in.tellg();
35 | }
36 |
37 | private:
38 | istream& m_in;
39 | };
40 |
41 | ObjRef parseNext(Deserialize& s, PyVM* vm);
42 |
43 |
44 | // http://daeken.com/2010-02-20_Python_Marshal_Format.html
45 | void CodeDefinition::parseCode(Deserialize& s, PyVM* vm)
46 | {
47 | co_argcount = s.read();
48 | co_nlocals = s.read();
49 | co_stacksize = s.read();
50 | co_flags = s.read();
51 | co_code = extract(parseNext(s, vm));
52 | co_consts = extract>(parseNext(s, vm));
53 |
54 | co_names = extract>(parseNext(s, vm));
55 | co_varnames = extract>(parseNext(s, vm));
56 | co_freevars = extract>(parseNext(s, vm));
57 | co_cellvars = extract>(parseNext(s, vm));
58 | co_filename = extract(parseNext(s, vm));
59 | co_name = extract(parseNext(s, vm));
60 |
61 | co_firstlineno = s.read();
62 | co_lnotab = extract(parseNext(s, vm));
63 | }
64 |
65 | ObjRef parseNext(Deserialize& s, PyVM* vm)
66 | {
67 | uchar t = s.read();
68 | int o = s.offset();
69 | switch (t) {
70 | case '0': return ObjRef(); // should not happen
71 | case 'N': return vm->makeNone();
72 | case 'F': return vm->makeFromT(false);
73 | case 'T': return vm->makeFromT(true);
74 | case 'i': return vm->makeFromT(s.read());
75 | case 'I': return vm->makeFromT(s.read());
76 | case 'g': return vm->makeFromT(s.read());
77 | case 's': {
78 | uint sz = s.read();
79 | return vm->makeFromT(s.readStr(sz));
80 | }
81 | case '(':
82 | case '[': {
83 | uint sz = s.read();
84 | ListObject* obj = (t == '(') ? new TupleObject : new ListObject;
85 | obj->v.resize(sz);
86 | for(uint i = 0; i < sz; ++i)
87 | obj->v[i] = parseNext(s, vm);
88 | return vm->alloc(obj);
89 | }
90 | case 'c': {
91 | auto* co = new CodeObject;
92 | co->m_co.parseCode(s, vm);
93 | return vm->alloc(co);
94 | }
95 | case 't': { // interned str
96 | uint sz = s.read();
97 | ObjRef obj = vm->makeFromT(s.readStr(sz));
98 | s.m_internedStr.push_back(obj);
99 | return obj;
100 | }
101 | case 'R': return s.m_internedStr[s.read()];
102 | case 'l': { // long, encoded as digits in base 2^15
103 | int h = s.read(); // number of digits, sign is the sign of the number
104 | int sz = std::abs(h);
105 | int pos = 0;
106 | int64 res = 0;
107 | for(int i = 0; i < sz; ++i) {
108 | auto b = s.read();
109 | res |= (int64)b << pos;
110 | pos += 15;
111 | }
112 | return vm->makeFromT(h < 0 ? -res : res);
113 | }
114 | case 'u': { // utf8 unicode
115 | uint sz = s.read();
116 | wstring us;
117 | CHECK(wstrFromUtf8(s.readStr(sz), &us), "Failed reading UTF8");
118 | return vm->makeFromT(us);
119 | }
120 | case '{':
121 | case '>':
122 | case 'y': // binary complex
123 | case 'x': // old complex
124 | case 'f': // old float
125 | case 'S': // stop iter
126 | case '.': // ellipsis
127 | default:
128 | THROW("Unsupported marshal type `" << t << "`");
129 | }
130 |
131 | }
132 |
133 |
134 | ObjRef CodeDefinition::parsePyc(istream& iss, PyVM* vm, bool hasHeadr)
135 | {
136 | Deserialize d(iss);
137 | if (hasHeadr) {
138 | uint magic = d.read();
139 | CHECK(magic == 0x0a0df303, "Unexpected magic number in marshal format " << hex << magic);
140 | uint timestamp = d.read();
141 | }
142 | return parseNext(d, vm);
143 | }
--------------------------------------------------------------------------------
/src/CodeDefinition.h:
--------------------------------------------------------------------------------
1 | // Copyright 2015 by Intigua, Inc.
2 | // Licensed under the Apache License, Version 2.0 (the "License");
3 | // you may not use this file except in compliance with the License.
4 | // You may obtain a copy of the License at
5 | // http://www.apache.org/licenses/LICENSE-2.0
6 | // Unless required by applicable law or agreed to in writing, software
7 | // distributed under the License is distributed on an "AS IS" BASIS,
8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 | // See the License for the specific language governing permissions and
10 | // limitations under the License.
11 | #pragma once
12 | #include
13 | #include
14 |
15 | class Deserialize;
16 |
17 | class CodeDefinition
18 | {
19 | public:
20 | static ObjRef parsePyc(istream& iss, PyVM* vm, bool hasHeader);
21 |
22 | void parseCode(Deserialize& s, PyVM* vm);
23 | public:
24 | string co_name;
25 | uint co_argcount;
26 | uint co_nlocals;
27 | vector co_varnames;
28 | vector co_cellvars;
29 | vector co_freevars;
30 | string co_code;
31 | vector co_consts;
32 | vector co_names;
33 | string co_filename;
34 | uint co_firstlineno;
35 | string co_lnotab;
36 | uint co_stacksize;
37 | uint co_flags;
38 | };
--------------------------------------------------------------------------------
/src/ObjPool.h:
--------------------------------------------------------------------------------
1 | // Copyright 2015 by Intigua, Inc.
2 | // Licensed under the Apache License, Version 2.0 (the "License");
3 | // you may not use this file except in compliance with the License.
4 | // You may obtain a copy of the License at
5 | // http://www.apache.org/licenses/LICENSE-2.0
6 | // Unless required by applicable law or agreed to in writing, software
7 | // distributed under the License is distributed on an "AS IS" BASIS,
8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 | // See the License for the specific language governing permissions and
10 | // limitations under the License.
11 | #pragma once
12 | #include "except.h"
13 | #include "defs.h"
14 | #include "log.h"
15 |
16 |
17 | template
18 | class ObjPool;
19 |
20 | template
21 | class PoolPtr
22 | {
23 | public:
24 | PoolPtr() : m_p(nullptr) {}
25 | PoolPtr(const PoolPtr& o) : m_p(o.m_p) {
26 | if (m_p != nullptr) {
27 | ++m_p->count.count;
28 | }
29 | }
30 | PoolPtr(PoolPtr&& o) {
31 | m_p = o.m_p;
32 | o.m_p = nullptr;
33 | }
34 | explicit PoolPtr(T* p) :m_p(p) {
35 | if (m_p != nullptr)
36 | ++m_p->count.count;
37 | }
38 | template
39 | explicit PoolPtr(const PoolPtr& o) : m_p(nullptr) {
40 | if (o.get() == nullptr)
41 | return;
42 | m_p = dynamic_cast(o.get());
43 | CHECK(m_p != nullptr, "Incompatible conversion");
44 | ++m_p->count.count;
45 | }
46 |
47 | ~PoolPtr() {
48 | reset();
49 | }
50 | PoolPtr& operator=(const PoolPtr& o) {
51 | if (&o == this)
52 | return *this;
53 | reset();
54 | m_p = o.m_p;
55 | if (m_p != nullptr) {
56 | ++m_p->count.count;
57 | }
58 | return *this;
59 | }
60 | void reset() {
61 | if (m_p == nullptr)
62 | return;
63 | if (--m_p->count.count == 0) {
64 | m_p->count.pool->remove(m_p);
65 | }
66 | m_p = nullptr;
67 | }
68 | T* get() const {
69 | return m_p;
70 | }
71 | T* operator->() const {
72 | return m_p;
73 | }
74 | const T& operator*() const {
75 | return *m_p;
76 | }
77 | T& operator*() {
78 | return *m_p;
79 | }
80 | bool isNull() const {
81 | return m_p == nullptr;
82 | }
83 | int use_count() const {
84 | if (m_p == nullptr)
85 | return 0;
86 | return m_p->count.count;
87 | }
88 |
89 | private:
90 | T* m_p;
91 |
92 | friend class ObjPool;
93 | };
94 |
95 | template
96 | PoolPtr static_pcast(const PoolPtr& o) {
97 | return PoolPtr(static_cast(o.get()));
98 | }
99 | template
100 | PoolPtr dynamic_pcast(const PoolPtr& o) {
101 | return PoolPtr(dynamic_cast(o.get()));
102 | }
103 |
104 |
105 | // doubly linked list that hold objects of type T. T objects should have public data member count of type RefCount
106 | template
107 | class DList {
108 | private:
109 | T *m_head, *m_tail;
110 | int m_size;
111 |
112 | public:
113 | struct Entry {
114 | Entry() : next(nullptr), prev(nullptr) {}
115 | T *next, *prev;
116 | };
117 |
118 | struct iterator {
119 | iterator(T* p) : ptr(p) {}
120 | T* get() { return ptr; }
121 | bool operator!=(iterator rhs) { return ptr != rhs.ptr; }
122 | bool operator==(iterator rhs) { return ptr == rhs.ptr; }
123 | iterator& operator++() {// prefix
124 | CHECK(ptr != nullptr, "unexpected nullptrptr");
125 | ptr = ptr->count.ent.next;
126 | return *this;
127 | }
128 | T* ptr;
129 | };
130 |
131 | DList() : m_head(nullptr), m_tail(nullptr), m_size(0) {
132 | // two dummy nodes that are always there.
133 | m_head = new T();
134 | m_tail = new T();
135 | m_head->count.ent.next = m_tail;
136 | m_tail->count.ent.prev = m_head;
137 | }
138 | ~DList() {
139 | if (m_size != 0) {
140 | LOG_ERROR("Object pool not empty. size=", m_size, " global objects?");
141 | }
142 | delete m_head;
143 | delete m_tail;
144 | }
145 | // push at head
146 | void push_front(T* v) {
147 | Entry* n = &v->count.ent;// new Entry(m_head, v, m_head->next);
148 | n->prev = m_head;
149 | n->next = m_head->count.ent.next;
150 | m_head->count.ent.next->count.ent.prev = v;
151 | m_head->count.ent.next = v;
152 | ++m_size;
153 | }
154 | iterator begin() {
155 | return iterator(m_head->count.ent.next);
156 | }
157 | iterator end() {
158 | return iterator(m_tail); // one after last
159 | }
160 | void erase(T* v) {
161 | if (v == nullptr)
162 | return;
163 | CHECK(v != m_head && v != m_tail, "Unexpected state DList");
164 | Entry* e = &v->count.ent;
165 | e->next->count.ent.prev = e->prev;
166 | e->prev->count.ent.next = e->next;
167 | --m_size;
168 | }
169 | int size() const {
170 | return m_size;
171 | }
172 | };
173 |
174 | template
175 | struct RefCount {
176 | RefCount() : count(0), pool(nullptr)
177 | {}
178 | ~RefCount() {
179 | // delete remover;
180 | }
181 | int count;
182 | ObjPool *pool;
183 | typename DList::Entry ent;
184 | private:
185 | DISALLOW_COPY_AND_ASSIGN(RefCount);
186 | };
187 |
188 |
189 | //#define OBJ_CNT_PRINT_DELTA_MS 10*60*1000 //10 mins
190 |
191 | /** A pool of reference counter objects of type T
192 | * T should have a public data member named 'count' of type RefCount
193 | * The pool can hold objects that inherit from T
194 | * it holds a doubly linked list of T objects. the next and prev pointes are inside RefCount::ent
195 | */
196 | template
197 | class ObjPool
198 | {
199 | public:
200 | ObjPool() :m_hadRemove(false) //, m_lastTimePrintedObjCount(0)
201 | {}
202 | // takes ownership of p
203 | PoolPtr add(T* p) {
204 | PoolPtr ret(p);
205 | m_objs.push_front(p);
206 | p->count.pool = this;
207 | return ret;
208 | }
209 |
210 | void remove(T* v) {
211 | //printObjCntIfNeeded(); disabled since it garbages the log. instead, print the count before destruction of the pool in PyVM::clear()
212 | m_objs.erase(v);
213 | delete v;
214 | m_hadRemove = true;
215 | }
216 |
217 | /* void printObjCntIfNeeded(){
218 | uint64 currentMsec = os::OSUtils::msecTimeFast();
219 | if ((currentMsec - m_lastTimePrintedObjCount) > OBJ_CNT_PRINT_DELTA_MS){
220 | LOG_DEBUG("There are ", m_objs.size(), " objects in pyvm object pool");
221 | m_lastTimePrintedObjCount = currentMsec;
222 | }
223 | }*/
224 |
225 | template
226 | bool foreach(const F& f) {
227 | PoolPtr p(m_objs.begin().ptr);
228 | typename DList::iterator it(p.get());
229 | while( it != m_objs.end()) {
230 | // need to get the reference to the next one before it is possibly destroyed (delay its destruction)
231 | ++it;
232 | PoolPtr nextp( (it != m_objs.end()) ? (it.ptr) : nullptr );
233 | if (!f(p))
234 | return false;
235 | p = nextp;
236 | }
237 | return true;
238 | }
239 |
240 | int size() const {
241 | return m_objs.size();
242 | }
243 | T* listHead() {
244 | return m_objs.begin().get();
245 | }
246 |
247 | // the problem this avoids is that if the object we're on is just freed
248 | // since it was part of a circle, we can't get to the next one
249 | template
250 | void gradForeach(const F& f) {
251 | while (true) {
252 | m_hadRemove = false;
253 | auto it = m_objs.begin();
254 | for(; it != m_objs.end(); ++it) {
255 | f(PoolPtr(it.get()));
256 | if (m_hadRemove) // maybe someone removed the iterator.
257 | break;
258 | }
259 | if (it == m_objs.end())
260 | break;
261 | }
262 | }
263 |
264 | int countRefs() {
265 | int sum = 0;
266 | foreach([&](const PoolPtr& p)->bool {
267 | sum += p->count.count - 1;
268 | return true;
269 | });
270 | return sum;
271 | }
272 |
273 | private:
274 | DList m_objs;
275 | bool m_hadRemove; // used in gradForeach
276 | //uint64 m_lastTimePrintedObjCount;
277 |
278 | };
279 |
280 |
--------------------------------------------------------------------------------
/src/OpImp.h:
--------------------------------------------------------------------------------
1 | // Copyright 2015 by Intigua, Inc.
2 | // Licensed under the Apache License, Version 2.0 (the "License");
3 | // you may not use this file except in compliance with the License.
4 | // You may obtain a copy of the License at
5 | // http://www.apache.org/licenses/LICENSE-2.0
6 | // Unless required by applicable law or agreed to in writing, software
7 | // distributed under the License is distributed on an "AS IS" BASIS,
8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 | // See the License for the specific language governing permissions and
10 | // limitations under the License.
11 | #pragma once
12 | #include "PyVM.h"
13 |
14 |
15 | class OpImp {
16 | public:
17 | OpImp(PyVM *_vm) :vm(_vm) {}
18 |
19 | template
20 | ObjRef addType(Object *lhs, Object *rhs);
21 | ObjRef add(const ObjRef& lhsref, const ObjRef& rhsref);
22 |
23 | template
24 | ObjRef multType(Object *lhs, Object *rhs);
25 | template
26 | ObjRef multStr(Object *str, Object *num);
27 | ObjRef mult(const ObjRef& lhsref, const ObjRef& rhsref);
28 |
29 | template
30 | ObjRef subType(Object *lhs, Object *rhs);
31 | ObjRef sub(const ObjRef& lhsref, const ObjRef& rhsref);
32 |
33 | template
34 | ObjRef divType(Object *lhs, Object *rhs);
35 | ObjRef div(const ObjRef& lhsref, const ObjRef& rhsref);
36 |
37 | template
38 | ObjRef minusType(Object *arg);
39 | ObjRef uminus(const ObjRef& argref);
40 |
41 | ObjRef uplus(const ObjRef& argref);
42 | ObjRef unot(const ObjRef& argref);
43 |
44 | template
45 | ObjRef makeListFromStack(Frame& frame, int count);
46 | void print(const ObjRef& vref, ostream& out);
47 |
48 | ObjRef len(const ObjRef& arg);
49 |
50 | ObjRef hash(const ObjRef& arg) {
51 | return vm->alloc(new IntObject(hashNum(arg)));
52 | }
53 | ObjRef str(const ObjRef& arg) {
54 | return vm->alloc(new StrObject(stdstr(arg, false)));
55 | }
56 | ObjRef repr(const ObjRef& arg) {
57 | return vm->alloc(new StrObject(stdstr(arg, true)));
58 | }
59 | ObjRef hex(const ObjRef& n) {
60 | int64 num = checked_cast(n)->v;
61 | stringstream ss; ss << "0x" << std::hex << num;
62 | return vm->alloc(new StrObject(ss.str()));
63 | }
64 | ObjRef int_(const ObjRef& arg);
65 | ObjRef bool_(const ObjRef& arg);
66 |
67 | bool compare(const ObjRef& lhsref, const ObjRef& rhsref, int op);
68 | bool compareList(const ListObject* lhs, const ListObject* rhs, int op);
69 | bool operIn(const ObjRef& lhs, const ObjRef& rhs, bool isPositive);
70 |
71 | ObjRef runtime_import(const ObjRef& filenameObj);
72 |
73 | ObjRef apply_slice(const ObjRef& o, int* startp, int* endp);
74 |
75 | private:
76 | PyVM* vm;
77 | };
78 |
79 |
--------------------------------------------------------------------------------
/src/PyCompile.cpp:
--------------------------------------------------------------------------------
1 | // Copyright 2015 by Intigua, Inc.
2 | // Licensed under the Apache License, Version 2.0 (the "License");
3 | // you may not use this file except in compliance with the License.
4 | // You may obtain a copy of the License at
5 | // http://www.apache.org/licenses/LICENSE-2.0
6 | // Unless required by applicable law or agreed to in writing, software
7 | // distributed under the License is distributed on an "AS IS" BASIS,
8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 | // See the License for the specific language governing permissions and
10 | // limitations under the License.
11 | #include "PyCompile.h"
12 | #include "log.h"
13 |
14 | #if USE_CPYTHON
15 |
16 | #define HAVE_ROUND // newer VS has this, uncomment in older VS
17 | #undef _DEBUG // don't get the debug lib
18 | #include
19 | #include
20 | #include
21 |
22 | bool initPython()
23 | {
24 | if (Py_IsInitialized())
25 | return true;
26 |
27 | Py_Initialize();
28 | if (Py_IsInitialized())
29 | return true;
30 |
31 | return false;
32 | }
33 |
34 | // if the GIL needs to be locked, do that before calling this function
35 | bool compileTextToPycBuf(const std::string& text, const std::string& filename, std::string* outpyc)
36 | {
37 | if (!initPython())
38 | return false;
39 |
40 | PyObject *pco = Py_CompileString(text.c_str(), filename.c_str(), Py_file_input);
41 | if (pco == nullptr) {
42 | LOG_ERROR("Error compiling python code");
43 | PyErr_Print();
44 | return false;
45 | }
46 |
47 | PyObject* pycstr = PyMarshal_WriteObjectToString(pco, 2);
48 | *outpyc = std::string(PyString_AsString(pycstr), PyString_Size(pycstr));
49 |
50 | Py_DECREF(pycstr);
51 | Py_DECREF(pco);
52 |
53 | return true;
54 | }
55 |
56 |
57 | std::string getInteractiveLine()
58 | {
59 | bool inited = false;
60 | if (!inited) {
61 | if (!initPython())
62 | return std::string();
63 | inited = true;
64 | }
65 |
66 | int errcode = 0;
67 | PyArena *arena = PyArena_New();
68 | mod_ty mod = PyParser_ASTFromFile(stdin, "blafilename", Py_single_input, ">>> ", "... ", nullptr, &errcode, arena);
69 | if (mod == nullptr) {
70 | PyArena_Free(arena);
71 | return std::string();
72 | }
73 |
74 | PyCodeObject *pco = PyAST_Compile(mod, "blafilename", nullptr, arena);
75 | PyArena_Free(arena);
76 |
77 | PyObject* pycstr = PyMarshal_WriteObjectToString((PyObject*)pco, 2);
78 | std::string pycline = std::string(PyString_AsString(pycstr), PyString_Size(pycstr));
79 |
80 | Py_DECREF(pycstr);
81 | Py_DECREF(pco);
82 |
83 | return pycline;
84 | }
85 |
86 | #endif // HAS_CPYTHON
--------------------------------------------------------------------------------
/src/PyCompile.h:
--------------------------------------------------------------------------------
1 | // Copyright 2015 by Intigua, Inc.
2 | // Licensed under the Apache License, Version 2.0 (the "License");
3 | // you may not use this file except in compliance with the License.
4 | // You may obtain a copy of the License at
5 | // http://www.apache.org/licenses/LICENSE-2.0
6 | // Unless required by applicable law or agreed to in writing, software
7 | // distributed under the License is distributed on an "AS IS" BASIS,
8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 | // See the License for the specific language governing permissions and
10 | // limitations under the License.
11 | #include
12 |
13 | #if USE_CPYTHON
14 |
15 | bool compileTextToPycBuf(const std::string& text, const std::string& filename, std::string* outpyc);
16 | std::string getInteractiveLine();
17 |
18 | #endif
19 |
--------------------------------------------------------------------------------
/src/PyVM.cpp:
--------------------------------------------------------------------------------
1 | // Copyright 2015 by Intigua, Inc.
2 | // Licensed under the Apache License, Version 2.0 (the "License");
3 | // you may not use this file except in compliance with the License.
4 | // You may obtain a copy of the License at
5 | // http://www.apache.org/licenses/LICENSE-2.0
6 | // Unless required by applicable law or agreed to in writing, software
7 | // distributed under the License is distributed on an "AS IS" BASIS,
8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 | // See the License for the specific language governing permissions and
10 | // limitations under the License.
11 | #include "objects.h"
12 | #include "PyVM.h"
13 | #include "log.h"
14 | #include "utils.h"
15 | #include "PyCompile.h"
16 |
17 | #include
18 | #include
19 |
20 |
21 | // int g_maxStackSize;
22 |
23 | //map g_lookups;
24 |
25 | template ObjRef PyVM::makeFromT(const PoolPtr