summaryrefslogtreecommitdiffstats
path: root/src/3rdparty/webkit/JavaScriptCore/runtime/JSGlobalObjectFunctions.cpp
blob: ecdddcf3393bfd3c8b36ed3720cec25d4872f6f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*
 *  Copyright (C) 1999-2002 Harri Porten (porten@kde.org)
 *  Copyright (C) 2001 Peter Kelly (pmk@post.com)
 *  Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
 *  Copyright (C) 2007 Cameron Zwarich (cwzwarich@uwaterloo.ca)
 *  Copyright (C) 2007 Maks Orlovich
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 *
 */

#include "config.h"
#include "JSGlobalObjectFunctions.h"

#include "CallFrame.h"
#include "GlobalEvalFunction.h"
#include "JSGlobalObject.h"
#include "JSString.h"
#include "Interpreter.h"
#include "Parser.h"
#include "dtoa.h"
#include "Lexer.h"
#include "Nodes.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wtf/ASCIICType.h>
#include <wtf/Assertions.h>
#include <wtf/MathExtras.h>
#include <wtf/unicode/UTF8.h>

using namespace WTF;
using namespace Unicode;

namespace JSC {

static JSValuePtr encode(ExecState* exec, const ArgList& args, const char* doNotEscape)
{
    UString str = args.at(exec, 0)->toString(exec);
    CString cstr = str.UTF8String(true);
    if (!cstr.c_str())
        return throwError(exec, URIError, "String contained an illegal UTF-16 sequence.");

    UString result = "";
    const char* p = cstr.c_str();
    for (size_t k = 0; k < cstr.size(); k++, p++) {
        char c = *p;
        if (c && strchr(doNotEscape, c))
            result.append(c);
        else {
            char tmp[4];
            sprintf(tmp, "%%%02X", static_cast<unsigned char>(c));
            result += tmp;
        }
    }
    return jsString(exec, result);
}

static JSValuePtr decode(ExecState* exec, const ArgList& args, const char* doNotUnescape, bool strict)
{
    UString result = "";
    UString str = args.at(exec, 0)->toString(exec);
    int k = 0;
    int len = str.size();
    const UChar* d = str.data();
    UChar u = 0;
    while (k < len) {
        const UChar* p = d + k;
        UChar c = *p;
        if (c == '%') {
            int charLen = 0;
            if (k <= len - 3 && isASCIIHexDigit(p[1]) && isASCIIHexDigit(p[2])) {
                const char b0 = Lexer::convertHex(p[1], p[2]);
                const int sequenceLen = UTF8SequenceLength(b0);
                if (sequenceLen != 0 && k <= len - sequenceLen * 3) {
                    charLen = sequenceLen * 3;
                    char sequence[5];
                    sequence[0] = b0;
                    for (int i = 1; i < sequenceLen; ++i) {
                        const UChar* q = p + i * 3;
                        if (q[0] == '%' && isASCIIHexDigit(q[1]) && isASCIIHexDigit(q[2]))
                            sequence[i] = Lexer::convertHex(q[1], q[2]);
                        else {
                            charLen = 0;
                            break;
                        }
                    }
                    if (charLen != 0) {
                        sequence[sequenceLen] = 0;
                        const int character = decodeUTF8Sequence(sequence);
                        if (character < 0 || character >= 0x110000)
                            charLen = 0;
                        else if (character >= 0x10000) {
                            // Convert to surrogate pair.
                            result.append(static_cast<UChar>(0xD800 | ((character - 0x10000) >> 10)));
                            u = static_cast<UChar>(0xDC00 | ((character - 0x10000) & 0x3FF));
                        } else
                            u = static_cast<UChar>(character);
                    }
                }
            }
            if (charLen == 0) {
                if (strict)
                    return throwError(exec, URIError);
                // The only case where we don't use "strict" mode is the "unescape" function.
                // For that, it's good to support the wonky "%u" syntax for compatibility with WinIE.
                if (k <= len - 6 && p[1] == 'u'
                        && isASCIIHexDigit(p[2]) && isASCIIHexDigit(p[3])
                        && isASCIIHexDigit(p[4]) && isASCIIHexDigit(p[5])) {
                    charLen = 6;
                    u = Lexer::convertUnicode(p[2], p[3], p[4], p[5]);
                }
            }
            if (charLen && (u == 0 || u >= 128 || !strchr(doNotUnescape, u))) {
                c = u;
                k += charLen - 1;
            }
        }
        k++;
        result.append(c);
    }
    return jsString(exec, result);
}

bool isStrWhiteSpace(UChar c)
{
    switch (c) {
        case 0x0009:
        case 0x000A:
        case 0x000B:
        case 0x000C:
        case 0x000D:
        case 0x0020:
        case 0x00A0:
        case 0x2028:
        case 0x2029:
            return true;
        default:
            return c > 0xff && isSeparatorSpace(c);
    }
}

static int parseDigit(unsigned short c, int radix)
{
    int digit = -1;

    if (c >= '0' && c <= '9')
        digit = c - '0';
    else if (c >= 'A' && c <= 'Z')
        digit = c - 'A' + 10;
    else if (c >= 'a' && c <= 'z')
        digit = c - 'a' + 10;

    if (digit >= radix)
        return -1;
    return digit;
}

double parseIntOverflow(const char* s, int length, int radix)
{
    double number = 0.0;
    double radixMultiplier = 1.0;

    for (const char* p = s + length - 1; p >= s; p--) {
        if (radixMultiplier == Inf) {
            if (*p != '0') {
                number = Inf;
                break;
            }
        } else {
            int digit = parseDigit(*p, radix);
            number += digit * radixMultiplier;
        }

        radixMultiplier *= radix;
    }

    return number;
}

static double parseInt(const UString& s, int radix)
{
    int length = s.size();
    const UChar* data = s.data();
    int p = 0;

    while (p < length && isStrWhiteSpace(data[p]))
        ++p;

    double sign = 1;
    if (p < length) {
        if (data[p] == '+')
            ++p;
        else if (data[p] == '-') {
            sign = -1;
            ++p;
        }
    }

    if ((radix == 0 || radix == 16) && length - p >= 2 && data[p] == '0' && (data[p + 1] == 'x' || data[p + 1] == 'X')) {
        radix = 16;
        p += 2;
    } else if (radix == 0) {
        if (p < length && data[p] == '0')
            radix = 8;
        else
            radix = 10;
    }

    if (radix < 2 || radix > 36)
        return NaN;

    int firstDigitPosition = p;
    bool sawDigit = false;
    double number = 0;
    while (p < length) {
        int digit = parseDigit(data[p], radix);
        if (digit == -1)
            break;
        sawDigit = true;
        number *= radix;
        number += digit;
        ++p;
    }

    if (number >= mantissaOverflowLowerBound) {
        if (radix == 10)
            number = WTF::strtod(s.substr(firstDigitPosition, p - firstDigitPosition).ascii(), 0);
        else if (radix == 2 || radix == 4 || radix == 8 || radix == 16 || radix == 32)
            number = parseIntOverflow(s.substr(firstDigitPosition, p - firstDigitPosition).ascii(), p - firstDigitPosition, radix);
    }

    if (!sawDigit)
        return NaN;

    return sign * number;
}

static double parseFloat(const UString& s)
{
    // Check for 0x prefix here, because toDouble allows it, but we must treat it as 0.
    // Need to skip any whitespace and then one + or - sign.
    int length = s.size();
    const UChar* data = s.data();
    int p = 0;
    while (p < length && isStrWhiteSpace(data[p]))
        ++p;

    if (p < length && (data[p] == '+' || data[p] == '-'))
        ++p;

    if (length - p >= 2 && data[p] == '0' && (data[p + 1] == 'x' || data[p + 1] == 'X'))
        return 0;

    return s.toDouble(true /*tolerant*/, false /* NaN for empty string */);
}

JSValuePtr globalFuncEval(ExecState* exec, JSObject* function, JSValuePtr thisValue, const ArgList& args)
{
    JSObject* thisObject = thisValue->toThisObject(exec);
    JSObject* unwrappedObject = thisObject->unwrappedObject();
    if (!unwrappedObject->isGlobalObject() || static_cast<JSGlobalObject*>(unwrappedObject)->evalFunction() != function)
        return throwError(exec, EvalError, "The \"this\" value passed to eval must be the global object from which eval originated");

    JSValuePtr x = args.at(exec, 0);
    if (!x->isString())
        return x;

    UString s = x->toString(exec);

    int errLine;
    UString errMsg;

    SourceCode source = makeSource(s);
    RefPtr<EvalNode> evalNode = exec->globalData().parser->parse<EvalNode>(exec, exec->dynamicGlobalObject()->debugger(), source, &errLine, &errMsg);

    if (!evalNode)
        return throwError(exec, SyntaxError, errMsg, errLine, source.provider()->asID(), NULL);

    return exec->interpreter()->execute(evalNode.get(), exec, thisObject, static_cast<JSGlobalObject*>(unwrappedObject)->globalScopeChain().node(), exec->exceptionSlot());
}

JSValuePtr globalFuncParseInt(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    JSValuePtr value = args.at(exec, 0);
    int32_t radix = args.at(exec, 1)->toInt32(exec);

    if (value->isNumber() && (radix == 0 || radix == 10)) {
        if (JSImmediate::isImmediate(value))
            return value;
        double d = value->uncheckedGetNumber();
        if (isfinite(d))
            return jsNumber(exec, floor(d));
        if (isnan(d) || isinf(d))
            return jsNaN(&exec->globalData());
        return JSImmediate::zeroImmediate();
    }

    return jsNumber(exec, parseInt(value->toString(exec), radix));
}

JSValuePtr globalFuncParseFloat(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    return jsNumber(exec, parseFloat(args.at(exec, 0)->toString(exec)));
}

JSValuePtr globalFuncIsNaN(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    return jsBoolean(isnan(args.at(exec, 0)->toNumber(exec)));
}

JSValuePtr globalFuncIsFinite(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    double n = args.at(exec, 0)->toNumber(exec);
    return jsBoolean(!isnan(n) && !isinf(n));
}

JSValuePtr globalFuncDecodeURI(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    static const char do_not_unescape_when_decoding_URI[] =
        "#$&+,/:;=?@";

    return decode(exec, args, do_not_unescape_when_decoding_URI, true);
}

JSValuePtr globalFuncDecodeURIComponent(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    return decode(exec, args, "", true);
}

JSValuePtr globalFuncEncodeURI(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    static const char do_not_escape_when_encoding_URI[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "0123456789"
        "!#$&'()*+,-./:;=?@_~";

    return encode(exec, args, do_not_escape_when_encoding_URI);
}

JSValuePtr globalFuncEncodeURIComponent(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    static const char do_not_escape_when_encoding_URI_component[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "0123456789"
        "!'()*-._~";

    return encode(exec, args, do_not_escape_when_encoding_URI_component);
}

JSValuePtr globalFuncEscape(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    static const char do_not_escape[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "0123456789"
        "*+-./@_";

    UString result = "";
    UString s;
    UString str = args.at(exec, 0)->toString(exec);
    const UChar* c = str.data();
    for (int k = 0; k < str.size(); k++, c++) {
        int u = c[0];
        if (u > 255) {
            char tmp[7];
            sprintf(tmp, "%%u%04X", u);
            s = UString(tmp);
        } else if (u != 0 && strchr(do_not_escape, static_cast<char>(u)))
            s = UString(c, 1);
        else {
            char tmp[4];
            sprintf(tmp, "%%%02X", u);
            s = UString(tmp);
        }
        result += s;
    }

    return jsString(exec, result);
}

JSValuePtr globalFuncUnescape(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    UString result = "";
    UString str = args.at(exec, 0)->toString(exec);
    int k = 0;
    int len = str.size();
    while (k < len) {
        const UChar* c = str.data() + k;
        UChar u;
        if (c[0] == '%' && k <= len - 6 && c[1] == 'u') {
            if (Lexer::isHexDigit(c[2]) && Lexer::isHexDigit(c[3]) && Lexer::isHexDigit(c[4]) && Lexer::isHexDigit(c[5])) {
                u = Lexer::convertUnicode(c[2], c[3], c[4], c[5]);
                c = &u;
                k += 5;
            }
        } else if (c[0] == '%' && k <= len - 3 && Lexer::isHexDigit(c[1]) && Lexer::isHexDigit(c[2])) {
            u = UChar(Lexer::convertHex(c[1], c[2]));
            c = &u;
            k += 2;
        }
        k++;
        result.append(*c);
    }

    return jsString(exec, result);
}

#ifndef NDEBUG
JSValuePtr globalFuncJSCPrint(ExecState* exec, JSObject*, JSValuePtr, const ArgList& args)
{
    CStringBuffer string;
    args.at(exec, 0)->toString(exec).getCString(string);
    puts(string.data());
    return jsUndefined();
}
#endif

} // namespace JSC
l opt">(v), 'g', 17, 0, NULL); if (!buf) { p->error = WFERR_NOMEMORY; return; } n = strlen(buf); w_byte((int)n, p); w_string(buf, (int)n, p); PyMem_Free(buf); buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), 'g', 17, 0, NULL); if (!buf) { p->error = WFERR_NOMEMORY; return; } n = strlen(buf); w_byte((int)n, p); w_string(buf, (int)n, p); PyMem_Free(buf); } } else if (PyBytes_CheckExact(v)) { w_byte(TYPE_STRING, p); n = PyBytes_GET_SIZE(v); if (n > INT_MAX) { /* huge strings are not supported */ p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } w_long((long)n, p); w_string(PyBytes_AS_STRING(v), (int)n, p); } else if (PyUnicode_CheckExact(v)) { PyObject *utf8; utf8 = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(v), PyUnicode_GET_SIZE(v), "surrogatepass"); if (utf8 == NULL) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } w_byte(TYPE_UNICODE, p); n = PyBytes_GET_SIZE(utf8); if (n > INT_MAX) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } w_long((long)n, p); w_string(PyBytes_AS_STRING(utf8), (int)n, p); Py_DECREF(utf8); } else if (PyTuple_CheckExact(v)) { w_byte(TYPE_TUPLE, p); n = PyTuple_Size(v); w_long((long)n, p); for (i = 0; i < n; i++) { w_object(PyTuple_GET_ITEM(v, i), p); } } else if (PyList_CheckExact(v)) { w_byte(TYPE_LIST, p); n = PyList_GET_SIZE(v); w_long((long)n, p); for (i = 0; i < n; i++) { w_object(PyList_GET_ITEM(v, i), p); } } else if (PyDict_CheckExact(v)) { Py_ssize_t pos; PyObject *key, *value; w_byte(TYPE_DICT, p); /* This one is NULL object terminated! */ pos = 0; while (PyDict_Next(v, &pos, &key, &value)) { w_object(key, p); w_object(value, p); } w_object((PyObject *)NULL, p); } else if (PyAnySet_CheckExact(v)) { PyObject *value, *it; if (PyObject_TypeCheck(v, &PySet_Type)) w_byte(TYPE_SET, p); else w_byte(TYPE_FROZENSET, p); n = PyObject_Size(v); if (n == -1) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } w_long((long)n, p); it = PyObject_GetIter(v); if (it == NULL) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } while ((value = PyIter_Next(it)) != NULL) { w_object(value, p); Py_DECREF(value); } Py_DECREF(it); if (PyErr_Occurred()) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } } else if (PyCode_Check(v)) { PyCodeObject *co = (PyCodeObject *)v; w_byte(TYPE_CODE, p); w_long(co->co_argcount, p); w_long(co->co_kwonlyargcount, p); w_long(co->co_nlocals, p); w_long(co->co_stacksize, p); w_long(co->co_flags, p); w_object(co->co_code, p); w_object(co->co_consts, p); w_object(co->co_names, p); w_object(co->co_varnames, p); w_object(co->co_freevars, p); w_object(co->co_cellvars, p); w_object(co->co_filename, p); w_object(co->co_name, p); w_long(co->co_firstlineno, p); w_object(co->co_lnotab, p); } else if (PyObject_CheckBuffer(v)) { /* Write unknown buffer-style objects as a string */ char *s; PyBufferProcs *pb = v->ob_type->tp_as_buffer; Py_buffer view; if ((*pb->bf_getbuffer)(v, &view, PyBUF_SIMPLE) != 0) { w_byte(TYPE_UNKNOWN, p); p->error = WFERR_UNMARSHALLABLE; } w_byte(TYPE_STRING, p); n = view.len; s = view.buf; if (n > INT_MAX) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } w_long((long)n, p); w_string(s, (int)n, p); if (pb->bf_releasebuffer != NULL) (*pb->bf_releasebuffer)(v, &view); } else { w_byte(TYPE_UNKNOWN, p); p->error = WFERR_UNMARSHALLABLE; } p->depth--; } /* version currently has no effect for writing longs. */ void PyMarshal_WriteLongToFile(long x, FILE *fp, int version) { WFILE wf; wf.fp = fp; wf.error = WFERR_OK; wf.depth = 0; wf.strings = NULL; wf.version = version; w_long(x, &wf); } void PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version) { WFILE wf; wf.fp = fp; wf.error = WFERR_OK; wf.depth = 0; wf.strings = (version > 0) ? PyDict_New() : NULL; wf.version = version; w_object(x, &wf); Py_XDECREF(wf.strings); } typedef WFILE RFILE; /* Same struct with different invariants */ #define rs_byte(p) (((p)->ptr < (p)->end) ? (unsigned char)*(p)->ptr++ : EOF) #define r_byte(p) ((p)->fp ? getc((p)->fp) : rs_byte(p)) static int r_string(char *s, int n, RFILE *p) { if (p->fp != NULL) /* The result fits into int because it must be <=n. */ return (int)fread(s, 1, n, p->fp); if (p->end - p->ptr < n) n = (int)(p->end - p->ptr); memcpy(s, p->ptr, n); p->ptr += n; return n; } static int r_short(RFILE *p) { register short x; x = r_byte(p); x |= r_byte(p) << 8; /* Sign-extension, in case short greater than 16 bits */ x |= -(x & 0x8000); return x; } static long r_long(RFILE *p) { register long x; register FILE *fp = p->fp; if (fp) { x = getc(fp); x |= (long)getc(fp) << 8; x |= (long)getc(fp) << 16; x |= (long)getc(fp) << 24; } else { x = rs_byte(p); x |= (long)rs_byte(p) << 8; x |= (long)rs_byte(p) << 16; x |= (long)rs_byte(p) << 24; } #if SIZEOF_LONG > 4 /* Sign extension for 64-bit machines */ x |= -(x & 0x80000000L); #endif return x; } /* r_long64 deals with the TYPE_INT64 code. On a machine with sizeof(long) > 4, it returns a Python int object, else a Python long object. Note that w_long64 writes out TYPE_INT if 32 bits is enough, so there's no inefficiency here in returning a PyLong on 32-bit boxes for everything written via TYPE_INT64 (i.e., if an int is written via TYPE_INT64, it *needs* more than 32 bits). */ static PyObject * r_long64(RFILE *p) { long lo4 = r_long(p); long hi4 = r_long(p); #if SIZEOF_LONG > 4 long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL); return PyLong_FromLong(x); #else unsigned char buf[8]; int one = 1; int is_little_endian = (int)*(char*)&one; if (is_little_endian) { memcpy(buf, &lo4, 4); memcpy(buf+4, &hi4, 4); } else { memcpy(buf, &hi4, 4); memcpy(buf+4, &lo4, 4); } return _PyLong_FromByteArray(buf, 8, is_little_endian, 1); #endif } static PyObject * r_PyLong(RFILE *p) { PyLongObject *ob; int size, i, j, md, shorts_in_top_digit; long n; digit d; n = r_long(p); if (n == 0) return (PyObject *)_PyLong_New(0); if (n < -INT_MAX || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (long size out of range)"); return NULL; } size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO; shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO; ob = _PyLong_New(size); if (ob == NULL) return NULL; Py_SIZE(ob) = n > 0 ? size : -size; for (i = 0; i < size-1; i++) { d = 0; for (j=0; j < PyLong_MARSHAL_RATIO; j++) { md = r_short(p); if (md < 0 || md > PyLong_MARSHAL_BASE) goto bad_digit; d += (digit)md << j*PyLong_MARSHAL_SHIFT; } ob->ob_digit[i] = d; } d = 0; for (j=0; j < shorts_in_top_digit; j++) { md = r_short(p); if (md < 0 || md > PyLong_MARSHAL_BASE) goto bad_digit; /* topmost marshal digit should be nonzero */ if (md == 0 && j == shorts_in_top_digit - 1) { Py_DECREF(ob); PyErr_SetString(PyExc_ValueError, "bad marshal data (unnormalized long data)"); return NULL; } d += (digit)md << j*PyLong_MARSHAL_SHIFT; } /* top digit should be nonzero, else the resulting PyLong won't be normalized */ ob->ob_digit[size-1] = d; return (PyObject *)ob; bad_digit: Py_DECREF(ob); PyErr_SetString(PyExc_ValueError, "bad marshal data (digit out of range in long)"); return NULL; } static PyObject * r_object(RFILE *p) { /* NULL is a valid return value, it does not necessarily means that an exception is set. */ PyObject *v, *v2; long i, n; int type = r_byte(p); PyObject *retval; p->depth++; if (p->depth > MAX_MARSHAL_STACK_DEPTH) { p->depth--; PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); return NULL; } switch (type) { case EOF: PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); retval = NULL; break; case TYPE_NULL: retval = NULL; break; case TYPE_NONE: Py_INCREF(Py_None); retval = Py_None; break; case TYPE_STOPITER: Py_INCREF(PyExc_StopIteration); retval = PyExc_StopIteration; break; case TYPE_ELLIPSIS: Py_INCREF(Py_Ellipsis); retval = Py_Ellipsis; break; case TYPE_FALSE: Py_INCREF(Py_False); retval = Py_False; break; case TYPE_TRUE: Py_INCREF(Py_True); retval = Py_True; break; case TYPE_INT: retval = PyLong_FromLong(r_long(p)); break; case TYPE_INT64: retval = r_long64(p); break; case TYPE_LONG: retval = r_PyLong(p); break; case TYPE_FLOAT: { char buf[256]; double dx; retval = NULL; n = r_byte(p); if (n == EOF || r_string(buf, (int)n, p) != n) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } buf[n] = '\0'; dx = PyOS_string_to_double(buf, NULL, NULL); if (dx == -1.0 && PyErr_Occurred()) break; retval = PyFloat_FromDouble(dx); break; } case TYPE_BINARY_FLOAT: { unsigned char buf[8]; double x; if (r_string((char*)buf, 8, p) != 8) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); retval = NULL; break; } x = _PyFloat_Unpack8(buf, 1); if (x == -1.0 && PyErr_Occurred()) { retval = NULL; break; } retval = PyFloat_FromDouble(x); break; } case TYPE_COMPLEX: { char buf[256]; Py_complex c; retval = NULL; n = r_byte(p); if (n == EOF || r_string(buf, (int)n, p) != n) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } buf[n] = '\0'; c.real = PyOS_string_to_double(buf, NULL, NULL); if (c.real == -1.0 && PyErr_Occurred()) break; n = r_byte(p); if (n == EOF || r_string(buf, (int)n, p) != n) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } buf[n] = '\0'; c.imag = PyOS_string_to_double(buf, NULL, NULL); if (c.imag == -1.0 && PyErr_Occurred()) break; retval = PyComplex_FromCComplex(c); break; } case TYPE_BINARY_COMPLEX: { unsigned char buf[8]; Py_complex c; if (r_string((char*)buf, 8, p) != 8) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); retval = NULL; break; } c.real = _PyFloat_Unpack8(buf, 1); if (c.real == -1.0 && PyErr_Occurred()) { retval = NULL; break; } if (r_string((char*)buf, 8, p) != 8) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); retval = NULL; break; } c.imag = _PyFloat_Unpack8(buf, 1); if (c.imag == -1.0 && PyErr_Occurred()) { retval = NULL; break; } retval = PyComplex_FromCComplex(c); break; } case TYPE_STRING: n = r_long(p); if (n < 0 || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); retval = NULL; break; } v = PyBytes_FromStringAndSize((char *)NULL, n); if (v == NULL) { retval = NULL; break; } if (r_string(PyBytes_AS_STRING(v), (int)n, p) != n) { Py_DECREF(v); PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); retval = NULL; break; } retval = v; break; case TYPE_UNICODE: { char *buffer; n = r_long(p); if (n < 0 || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); retval = NULL; break; } buffer = PyMem_NEW(char, n); if (buffer == NULL) { retval = PyErr_NoMemory(); break; } if (r_string(buffer, (int)n, p) != n) { PyMem_DEL(buffer); PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); retval = NULL; break; } v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass"); PyMem_DEL(buffer); retval = v; break; } case TYPE_TUPLE: n = r_long(p); if (n < 0 || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); retval = NULL; break; } v = PyTuple_New((int)n); if (v == NULL) { retval = NULL; break; } for (i = 0; i < n; i++) { v2 = r_object(p); if ( v2 == NULL ) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for tuple"); Py_DECREF(v); v = NULL; break; } PyTuple_SET_ITEM(v, (int)i, v2); } retval = v; break; case TYPE_LIST: n = r_long(p); if (n < 0 || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); retval = NULL; break; } v = PyList_New((int)n); if (v == NULL) { retval = NULL; break; } for (i = 0; i < n; i++) { v2 = r_object(p); if ( v2 == NULL ) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for list"); Py_DECREF(v); v = NULL; break; } PyList_SET_ITEM(v, (int)i, v2); } retval = v; break; case TYPE_DICT: v = PyDict_New(); if (v == NULL) { retval = NULL; break; } for (;;) { PyObject *key, *val; key = r_object(p); if (key == NULL) break; val = r_object(p); if (val != NULL) PyDict_SetItem(v, key, val); Py_DECREF(key); Py_XDECREF(val); } if (PyErr_Occurred()) { Py_DECREF(v); v = NULL; } retval = v; break; case TYPE_SET: case TYPE_FROZENSET: n = r_long(p); if (n < 0 || n > INT_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); retval = NULL; break; } v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); if (v == NULL) { retval = NULL; break; } for (i = 0; i < n; i++) { v2 = r_object(p); if ( v2 == NULL ) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for set"); Py_DECREF(v); v = NULL; break; } if (PySet_Add(v, v2) == -1) { Py_DECREF(v); Py_DECREF(v2); v = NULL; break; } Py_DECREF(v2); } retval = v; break; case TYPE_CODE: { int argcount; int kwonlyargcount; int nlocals; int stacksize; int flags; PyObject *code = NULL; PyObject *consts = NULL; PyObject *names = NULL; PyObject *varnames = NULL; PyObject *freevars = NULL; PyObject *cellvars = NULL; PyObject *filename = NULL; PyObject *name = NULL; int firstlineno; PyObject *lnotab = NULL; v = NULL; /* XXX ignore long->int overflows for now */ argcount = (int)r_long(p); kwonlyargcount = (int)r_long(p); nlocals = (int)r_long(p); stacksize = (int)r_long(p); flags = (int)r_long(p); code = r_object(p); if (code == NULL) goto code_error; consts = r_object(p); if (consts == NULL) goto code_error; names = r_object(p); if (names == NULL) goto code_error; varnames = r_object(p); if (varnames == NULL) goto code_error; freevars = r_object(p); if (freevars == NULL) goto code_error; cellvars = r_object(p); if (cellvars == NULL) goto code_error; filename = r_object(p); if (filename == NULL) goto code_error; name = r_object(p); if (name == NULL) goto code_error; firstlineno = (int)r_long(p); lnotab = r_object(p); if (lnotab == NULL) goto code_error; v = (PyObject *) PyCode_New( argcount, kwonlyargcount, nlocals, stacksize, flags, code, consts, names, varnames, freevars, cellvars, filename, name, firstlineno, lnotab); code_error: Py_XDECREF(code); Py_XDECREF(consts); Py_XDECREF(names); Py_XDECREF(varnames); Py_XDECREF(freevars); Py_XDECREF(cellvars); Py_XDECREF(filename); Py_XDECREF(name); Py_XDECREF(lnotab); } retval = v; break; default: /* Bogus data got written, which isn't ideal. This will let you keep working and recover. */ PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); retval = NULL; break; } p->depth--; return retval; } static PyObject * read_object(RFILE *p) { PyObject *v; if (PyErr_Occurred()) { fprintf(stderr, "XXX readobject called with exception set\n"); return NULL; } v = r_object(p); if (v == NULL && !PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); return v; } int PyMarshal_ReadShortFromFile(FILE *fp) { RFILE rf; assert(fp); rf.fp = fp; rf.strings = NULL; rf.end = rf.ptr = NULL; return r_short(&rf); } long PyMarshal_ReadLongFromFile(FILE *fp) { RFILE rf; rf.fp = fp; rf.strings = NULL; rf.ptr = rf.end = NULL; return r_long(&rf); } #ifdef HAVE_FSTAT /* Return size of file in bytes; < 0 if unknown. */ static off_t getfilesize(FILE *fp) { struct stat st; if (fstat(fileno(fp), &st) != 0) return -1; else return st.st_size; } #endif /* If we can get the size of the file up-front, and it's reasonably small, * read it in one gulp and delegate to ...FromString() instead. Much quicker * than reading a byte at a time from file; speeds .pyc imports. * CAUTION: since this may read the entire remainder of the file, don't * call it unless you know you're done with the file. */ PyObject * PyMarshal_ReadLastObjectFromFile(FILE *fp) { /* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */ #define REASONABLE_FILE_LIMIT (1L << 18) #ifdef HAVE_FSTAT off_t filesize; filesize = getfilesize(fp); if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) { char* pBuf = (char *)PyMem_MALLOC(filesize); if (pBuf != NULL) { PyObject* v; size_t n; /* filesize must fit into an int, because it is smaller than REASONABLE_FILE_LIMIT */ n = fread(pBuf, 1, (int)filesize, fp); v = PyMarshal_ReadObjectFromString(pBuf, n); PyMem_FREE(pBuf); return v; } } #endif /* We don't have fstat, or we do but the file is larger than * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. */ return PyMarshal_ReadObjectFromFile(fp); #undef REASONABLE_FILE_LIMIT } PyObject * PyMarshal_ReadObjectFromFile(FILE *fp) { RFILE rf; PyObject *result; rf.fp = fp; rf.strings = PyList_New(0); rf.depth = 0; rf.ptr = rf.end = NULL; result = r_object(&rf); Py_DECREF(rf.strings); return result; } PyObject * PyMarshal_ReadObjectFromString(char *str, Py_ssize_t len) { RFILE rf; PyObject *result; rf.fp = NULL; rf.ptr = str; rf.end = str + len; rf.strings = PyList_New(0); rf.depth = 0; result = r_object(&rf); Py_DECREF(rf.strings); return result; } PyObject * PyMarshal_WriteObjectToString(PyObject *x, int version) { WFILE wf; PyObject *res = NULL; wf.fp = NULL; wf.str = PyBytes_FromStringAndSize((char *)NULL, 50); if (wf.str == NULL) return NULL; wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str); wf.end = wf.ptr + PyBytes_Size(wf.str); wf.error = WFERR_OK; wf.depth = 0; wf.version = version; wf.strings = (version > 0) ? PyDict_New() : NULL; w_object(x, &wf); Py_XDECREF(wf.strings); if (wf.str != NULL) { char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str); if (wf.ptr - base > PY_SSIZE_T_MAX) { Py_DECREF(wf.str); PyErr_SetString(PyExc_OverflowError, "too much marshal data for a string"); return NULL; } if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0) return NULL; } if (wf.error != WFERR_OK) { Py_XDECREF(wf.str); if (wf.error == WFERR_NOMEMORY) PyErr_NoMemory(); else PyErr_SetString(PyExc_ValueError, (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object" :"object too deeply nested to marshal"); return NULL; } if (wf.str != NULL) { /* XXX Quick hack -- need to do this differently */ res = PyBytes_FromObject(wf.str); Py_DECREF(wf.str); } return res; } /* And an interface for Python programs... */ static PyObject * marshal_dump(PyObject *self, PyObject *args) { /* XXX Quick hack -- need to do this differently */ PyObject *x; PyObject *f; int version = Py_MARSHAL_VERSION; PyObject *s; PyObject *res; if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version)) return NULL; s = PyMarshal_WriteObjectToString(x, version); if (s == NULL) return NULL; res = PyObject_CallMethod(f, "write", "O", s); Py_DECREF(s); return res; } PyDoc_STRVAR(dump_doc, "dump(value, file[, version])\n\ \n\ Write the value on the open file. The value must be a supported type.\n\ The file must be an open file object such as sys.stdout or returned by\n\ open() or os.popen(). It must be opened in binary mode ('wb' or 'w+b').\n\ \n\ If the value has (or contains an object that has) an unsupported type, a\n\ ValueError exception is raised — but garbage data will also be written\n\ to the file. The object will not be properly read back by load()\n\ \n\ The version argument indicates the data format that dump should use."); static PyObject * marshal_load(PyObject *self, PyObject *f) { /* XXX Quick hack -- need to do this differently */ PyObject *data, *result; RFILE rf; data = PyObject_CallMethod(f, "read", ""); if (data == NULL) return NULL; rf.fp = NULL; if (PyBytes_Check(data)) { rf.ptr = PyBytes_AS_STRING(data); rf.end = rf.ptr + PyBytes_GET_SIZE(data); } else if (PyBytes_Check(data)) { rf.ptr = PyBytes_AS_STRING(data); rf.end = rf.ptr + PyBytes_GET_SIZE(data); } else { PyErr_Format(PyExc_TypeError, "f.read() returned neither string " "nor bytes but %.100s", data->ob_type->tp_name); Py_DECREF(data); return NULL; } rf.strings = PyList_New(0); rf.depth = 0; result = read_object(&rf); Py_DECREF(rf.strings); Py_DECREF(data); return result; } PyDoc_STRVAR(load_doc, "load(file)\n\ \n\ Read one value from the open file and return it. If no valid value is\n\ read (e.g. because the data has a different Python version’s\n\ incompatible marshal format), raise EOFError, ValueError or TypeError.\n\ The file must be an open file object opened in binary mode ('rb' or\n\ 'r+b').\n\ \n\ Note: If an object containing an unsupported type was marshalled with\n\ dump(), load() will substitute None for the unmarshallable type."); static PyObject * marshal_dumps(PyObject *self, PyObject *args) { PyObject *x; int version = Py_MARSHAL_VERSION; if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version)) return NULL; return PyMarshal_WriteObjectToString(x, version); } PyDoc_STRVAR(dumps_doc, "dumps(value[, version])\n\ \n\ Return the string that would be written to a file by dump(value, file).\n\ The value must be a supported type. Raise a ValueError exception if\n\ value has (or contains an object that has) an unsupported type.\n\ \n\ The version argument indicates the data format that dumps should use."); static PyObject * marshal_loads(PyObject *self, PyObject *args) { RFILE rf; Py_buffer p; char *s; Py_ssize_t n; PyObject* result; if (!PyArg_ParseTuple(args, "s*:loads", &p)) return NULL; s = p.buf; n = p.len; rf.fp = NULL; rf.ptr = s; rf.end = s + n; rf.strings = PyList_New(0); rf.depth = 0; result = read_object(&rf); Py_DECREF(rf.strings); PyBuffer_Release(&p); return result; } PyDoc_STRVAR(loads_doc, "loads(string)\n\ \n\ Convert the string to a value. If no valid value is found, raise\n\ EOFError, ValueError or TypeError. Extra characters in the string are\n\ ignored."); static PyMethodDef marshal_methods[] = { {"dump", marshal_dump, METH_VARARGS, dump_doc}, {"load", marshal_load, METH_O, load_doc}, {"dumps", marshal_dumps, METH_VARARGS, dumps_doc}, {"loads", marshal_loads, METH_VARARGS, loads_doc}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "This module contains functions that can read and write Python values in\n\ a binary format. The format is specific to Python, but independent of\n\ machine architecture issues.\n\ \n\ Not all Python object types are supported; in general, only objects\n\ whose value is independent from a particular invocation of Python can be\n\ written and read by this module. The following types are supported:\n\ None, integers, floating point numbers, strings, bytes, bytearrays,\n\ tuples, lists, sets, dictionaries, and code objects, where it\n\ should be understood that tuples, lists and dictionaries are only\n\ supported as long as the values contained therein are themselves\n\ supported; and recursive lists and dictionaries should not be written\n\ (they will cause infinite loops).\n\ \n\ Variables:\n\ \n\ version -- indicates the format that the module uses. Version 0 is the\n\ historical format, version 1 shares interned strings and version 2\n\ uses a binary format for floating point numbers.\n\ \n\ Functions:\n\ \n\ dump() -- write value to a file\n\ load() -- read value from a file\n\ dumps() -- write value to a string\n\ loads() -- read value from a string"); static struct PyModuleDef marshalmodule = { PyModuleDef_HEAD_INIT, "marshal", module_doc, 0, marshal_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyMarshal_Init(void) { PyObject *mod = PyModule_Create(&marshalmodule); if (mod == NULL) return NULL; PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); return mod; }