Stubs.py 13.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# (C) Semantix Information Technologies.
#
# Semantix Information Technologies is licensing the code of the
# Data Modelling Tools (DMT) in the following dual-license mode:
#
# Commercial Developer License:
#       The DMT Commercial Developer License is the suggested version
# to use for the development of proprietary and/or commercial software.
# This version is for developers/companies who do not want to comply
# with the terms of the GNU Lesser General Public License version 2.1.
#
# GNU LGPL v. 2.1:
#       This version of DMT is the one to use for the development of
# applications, when you are willing to comply with the terms of the
# GNU Lesser General Public License version 2.1.
#
# Note that in both cases, there are no charges (royalties) for the
# generated code.
#
21
import os
22
23
24
25
import sys
import re
import copy
import traceback
26
import DV_Types  # pylint: disable=import-error
27
28
29
30
31
32
33
34
35
36
37
38
39
from ctypes import (
    cdll, c_void_p, c_ubyte, c_double, c_uint,
    c_longlong, c_bool, c_int, c_long
)

# load the *getset.so in this folder
script_path = os.path.dirname(os.path.realpath(__file__))
soFileNames = [
    filename
    for filename in os.listdir(script_path)
    if filename.endswith("_getset.so")
]
if len(soFileNames) != 1:
40
    print("Failed to locate a single _getset.so under", script_path)
41
42
    sys.exit(1)

43
JMP = cdll.LoadLibrary(os.path.join(script_path, soFileNames[0]))
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

# BitStream constructor
CreateStream = JMP.CreateStream
CreateStream.restype = c_void_p
# BitStream destructor
DestroyStream = JMP.DestroyStream
# BitStream reset
ResetStream = JMP.ResetStream
# Get number of bytes in encoded stream
GetStreamCurrentLength = JMP.GetStreamCurrentLength
GetStreamCurrentLength.restype = c_uint

# Access BitStream buffer
GetBitstreamBuffer = JMP.GetBitstreamBuffer
GetBitstreamBuffer.restype = c_void_p
# Read from buffer
GetBufferByte = JMP.GetBufferByte
GetBufferByte.restype = c_ubyte
# Write to buffer
SetBufferByte = JMP.SetBufferByte

# Create pErr space for Encoders - i.e. sizeof(int)
CreateInstanceOf_int = JMP.CreateInstanceOf_int
CreateInstanceOf_int.restype = c_void_p
# Release pErr space for Encoders
DestroyInstanceOf_int = JMP.DestroyInstanceOf_int
70
71
72
73


def panicWithCallStack(msg):
    """Print the panic msg in color, report the call stack, and die"""
74
75
    print("\n"+chr(27)+"[35m" + msg + chr(27) + "[0m\n", file=sys.stderr)
    print("\nCall stack was:\n%s\n" % ("".join(traceback.format_stack()[:-1])), file=sys.stderr)
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
    sys.exit(1)


def CleanNameAsPythonWants(name):
    """ASN.1 ids have minuses... turn non-ID chars to '_'"""
    return re.sub(r'[^a-zA-Z0-9_]', '_', name)
Clean = CleanNameAsPythonWants


def myassert(b):
    """assert that shows the call stack when it fails"""
    if not b:
        panicWithCallStack("Assertion failed...")


91
class DataStream(object):
92
93
94
95
    """ASN1SCC BitStream equivalent"""
    def __init__(self, bufferSize):
        """bufferSize: use the DV.TYPENAME_REQUIRED_BYTES_FOR_ENCODING"""
        myassert(isinstance(bufferSize, int))
96
        self._bs = c_void_p(CreateStream(bufferSize))
97
98
99
        self._bufferSize = bufferSize

    def __del__(self):
100
101
        """Releases the encoded data and the bitstream structure pointing to them"""
        DestroyStream(self._bs)
102
103
104

    def Reset(self):
        """Rewinds the currentByte and currentBit to the start"""
105
        ResetStream(self._bs)
106
107

    def GetPyString(self):
108
        # print "Reading",
109
        msg = ""
Maxime Perrotin's avatar
Maxime Perrotin committed
110
        pData = c_void_p(GetBitstreamBuffer(self._bs))
111
        for i in range(0, GetStreamCurrentLength(self._bs)):
112
            b = GetBufferByte(pData, i)
113
            msg += chr(b)
114
115
            # print b, ",",
        # print "EOF"
116
117
118
119
        return msg

    def SetFromPyString(self, data):
        strLength = len(data)
120
        assert self._bufferSize >= strLength
121
        self._bs.count = strLength
Maxime Perrotin's avatar
Maxime Perrotin committed
122
        pData = c_void_p(GetBitstreamBuffer(self._bs))
123
        # print "Writing",
124
        for i in range(0, strLength):
125
            b = ord(data[i])
126
127
128
            # print b, ",",
            SetBufferByte(pData, i, b)
        # print "EOF"
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184


class COMMON(object):
    """This class is used to implement ALL the Python "proxy" classes for
ASN1SCC types.

It uses the __getattr__ call to hook into all the accesses that Python
considers "unexpected". Therefore, when the script does this...

    a = T_SEQUENCE()
    print a.x.Get()
    a.x.Set(12)

... __getattr__ is called to ask us how to provide a ".x" member.
We do two things to cope:

(1) we form the equivalent path to the C getter/setter function
    (in self._Caccessor)
(2) we form a list of params, which is basically the indexes of
    whatever arrays we meet in the access path

So if the script does...

    a.x.y[0].z.k[2].w.Get()

then the params list carries [0,2], to pass it as an argument to the
C getter when it is called (in response to the "Get" method call).

Some key points:
    When the chain ends (in a .Get, .Set, .GetLength or .SetLength
call), we have to reset the "paths" we have formed, so that the
next chain will restart from the beginning. That's what the Reset
method does.
However, we also have some helper functions for OCTET STRINGs:
GetPyString and SetFromPyString. These have to do a per-byte loop,
and if they used the "Get" and "Set" as they originally were,
the path would be reset after accessing the [0] element...
So we added a keyword boolean param called "reset", which disables
this Reset when it is used from within GetPyString and
SetFromPyString.
    Another keyword param is postfix: it is simply used to allow
re-use of the Get and Set code for the GetLength and SetLength
members of SEQUENCEOF/SETOFs and OCTETSTRINGs:

An example for SetLength:

  T_SEQUENCE ::= SEQUENCE { y SEQUENCE (SIZE(4)) OF INTEGER }

    a = T_SEQUENCE()
    a.y.SetLength(4)
    a.y[0].Set(1)
    a.y[1].Set(4)
    a.y[2].Set(9)
    a.y[3].Set(16)
"""

185
186
    allowed = ["_nodeTypeName", "_ptr", "_pErr", "_Caccessor", "_accessPath",
               "_params", "_new_ptr"]
187
# , "Get", "GetLength", "Set", "SetLength", "Reset", "Encode", "Decode", "SetFromPyString", "GetPyString", "allowed"]
188

189
    def __init__(self, nodeTypeName, ptr=None):
190
191
        myassert(isinstance(nodeTypeName, str))
        self._nodeTypeName = nodeTypeName
192
        self._new_ptr = ptr is None
193
194
        constructor = getattr(JMP, "CreateInstanceOf_" + Clean(nodeTypeName))
        constructor.restype = c_void_p
195
        self._ptr = ptr or constructor()
Maxime Perrotin's avatar
Maxime Perrotin committed
196
197
        self._ptr = c_void_p(self._ptr)
        self._pErr = c_void_p(CreateInstanceOf_int())
198
199
200
        self._Caccessor = ""
        self._params = []
        self._accessPath = ""
201
202
203
204
205
206
207
208
209
210
211
212

    def Reset(self, state=None):
        if state is None:
            self._Caccessor = ""
            self._params = []
            self._accessPath = ""
        else:
            self._Caccessor, self._params, self._accessPath = state[0][:], copy.deepcopy(state[1]), state[2][:]

    def GetState(self):
        return self._Caccessor[:], copy.deepcopy(self._params), self._accessPath[:]

213
214
215
216
    def SetData(self, src):
        bridgeFct = getattr(JMP, "SetDataFor_" + Clean(self._nodeTypeName))
        bridgeFct(self._ptr, src)

217
    def __del__(self):
218
        ''' Destructor: free memory only if it was allocated at creation '''
219
        DestroyInstanceOf_int(self._pErr)
220
221
222
        if self._new_ptr:
            destructor = getattr(JMP, "DestroyInstanceOf_" + Clean(self._nodeTypeName))
            destructor(self._ptr)
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

    def __str__(self):
        return "Choose the information you want - whole-structure or sequence dump not supported."

    def __getattr__(self, x):
        self._Caccessor += "_"+Clean(x)
        self._accessPath += "."+x
        return self

    def __setattr__(self, name, value):
        if name not in COMMON.allowed:
            self.Reset()
            panicWithCallStack("You can only use .Set(XYZ) and .SetLength(XYZ) to assign values, don't use '='")
        object.__setattr__(self, name, value)

    def __getitem__(self, idx):
        self._Caccessor += "_iDx"
        self._params.append(idx)
        self._accessPath += "[" + str(idx) + "]"
        return self

    def Get(self, **args):  # postfix="", reset=True
        try:
246
247
            bridgeFuncName = Clean(self._nodeTypeName) + "_" + self._Caccessor + "_Get"+args.get("postfix", "")
            if bridgeFuncName not in DV_Types.funcTypeLookup:
248
                print("Function", bridgeFuncName, "not found in lookup - contact support.")
249
250
251
252
253
254
255
256
257
258
259
260
261
262
                raise Exception("")
            resType = DV_Types.funcTypeLookup[bridgeFuncName]
            if resType.endswith('*'):
                cTypesResultType = c_void_p
            else:
                cTypesResultType = {
                    'asn1SccSint': c_longlong,
                    'byte': c_ubyte,
                    'double': c_double,
                    'flag': c_bool,
                    'int': c_int,
                    'long': c_long
                }.get(resType, None)
                if cTypesResultType is None:
263
                    print("Result type of", resType, "is not yet supported in the Python mapper - contact support.")
264
265
266
                    raise Exception("")
            bridgeFunc = getattr(JMP, bridgeFuncName)
            bridgeFunc.restype = cTypesResultType
267
268
269
270
271
272
273
274
275
276
277
278
            retVal = bridgeFunc(self._ptr, *self._params)
        except:
            oldAP = self._accessPath
            if args.get("reset", True):
                self.Reset()
            panicWithCallStack("The access path you used (%s) is not valid." % oldAP)
        if args.get("reset", True):
            self.Reset()
        return retVal

    def Set(self, value, **args):  # postfix="", reset=True
        try:
279
280
281
282
            # print Clean(self._nodeTypeName) + "_" + self._Caccessor + "_Set"+postfix
            bridgeFunc = getattr(JMP, Clean(self._nodeTypeName) + "_" + self._Caccessor + "_Set"+args.get("postfix", ""))
            if isinstance(value, float):
                ctypesValue = c_double(value)
283
            elif isinstance(value, int):
284
285
286
287
                ctypesValue = c_longlong(value)
            else:
                ctypesValue = value
            self._params.append(ctypesValue)
288
289
            bridgeFunc(self._ptr, *self._params)
            self._params.pop()
290
        except Exception as e:
291
292
293
            oldAP = self._accessPath
            if args.get("reset", True):
                self.Reset()
294
            print(str(e))
295
296
297
298
299
300
301
302
303
304
305
306
            panicWithCallStack(
                "The access path you used (%s) or the value you tried to assign (%s) is not valid." %
                (oldAP, str(value)))
        if args.get("reset", True):
            self.Reset()

    def GetLength(self, reset=True):
        return self.Get(postfix="Length", reset=reset)

    def SetLength(self, value, reset=True):
        self.Set(value, postfix="Length", reset=reset)

307
308
309
    @staticmethod
    def getErrCode(pErr):
        errCode = 0
310
        for i in range(4):
311
312
313
            errCode = (errCode << 8) | GetBufferByte(pErr, (3-i))
        return errCode

314
315
316
317
    def Encode(self, bitstream, bACN=False):
        """Returns (booleanSuccess, ASN1SCC iErrorCode)
grep for the errorcode value inside ASN1SCC generated headers."""
        myassert(isinstance(bitstream, DataStream))
318
        bitstream.Reset()
319
        suffix = "_ACN_Encode" if bACN else "_Encode"
320
321
        EncodeFuncName = Clean(self._nodeTypeName) + suffix
        EncodeFunc = getattr(JMP, EncodeFuncName)
322
323
        success = EncodeFunc(self._ptr, bitstream._bs, self._pErr, True)
        if not success:
324
325
326
            panicWithCallStack(
                "Error in %s, code:%d" % (
                    EncodeFuncName, COMMON.getErrCode(self._pErr)))
327
328
329
330
331
332

    def Decode(self, bitstream, bACN=False):
        """Returns (booleanSuccess, ASN1SCC iErrorCode)
grep for the errorcode value inside ASN1SCC generated headers."""
        myassert(isinstance(bitstream, DataStream))
        suffix = "_ACN_Decode" if bACN else "_Decode"
333
        DecodeFunc = getattr(JMP, Clean(self._nodeTypeName) + suffix)
334
335
        success = DecodeFunc(self._ptr, bitstream._bs, self._pErr)
        if not success:
336
            panicWithCallStack("Error in Decode, code:%d" % COMMON.getErrCode(self._pErr))
337
338
339
340
341
342
343

    def EncodeACN(self, bitstream):
        self.Encode(bitstream, True)

    def DecodeACN(self, bitstream):
        self.Decode(bitstream, True)

344
345
    def IsConstraintValid(self):
        # Allocate temp space to store error code (avoid race condition that _pErr would cause)
Maxime Perrotin's avatar
Maxime Perrotin committed
346
        pErr = c_void_p(CreateInstanceOf_int())
347
348
349
350
351
352
        validatorFunc = getattr(JMP, Clean(self._nodeTypeName) + "_IsConstraintValid")
        isValid = validatorFunc(self._ptr, pErr)
        errorCode = COMMON.getErrCode(pErr)
        DestroyInstanceOf_int(pErr)
        return isValid, errorCode

353
354
355
356
357
358
359
360
361
# Type-specific helpers...

# OCTET STRING

    def SetFromPyString(self, src):
        strLength = len(src)
        self.SetLength(strLength, False)
        self._Caccessor += "_iDx"
        accessPath = self._accessPath
362
        for idx in range(0, strLength):
363
364
365
366
367
368
369
370
371
372
373
            self._params.append(idx)
            self._accessPath = accessPath + "[" + str(idx) + "]"
            self.Set(ord(src[idx]), reset=False)
            self._params.pop()
        self.Reset()

    def GetPyString(self):
        retval = ""
        strLength = self.GetLength(False)
        self._Caccessor += "_iDx"
        accessPath = self._accessPath
374
        for idx in range(0, strLength):
375
376
377
378
379
380
            self._params.append(idx)
            self._accessPath = accessPath + "[" + str(idx) + "]"
            retval += chr(self.Get(reset=False))
            self._params.pop()
        self.Reset()
        return retval