Imported Upstream version 1.0.0
[platform/upstream/js.git] / js / src / jsapi-tests / testXDR.cpp
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2  * vim: set ts=8 sw=4 et tw=99:
3  */
4
5 #include "tests.h"
6 #include "jsscript.h"
7 #include "jsxdrapi.h"
8
9 BEGIN_TEST(testXDR_bug506491)
10 {
11     const char *s =
12         "function makeClosure(s, name, value) {\n"
13         "    eval(s);\n"
14         "    return let (n = name, v = value) function () { return String(v); };\n"
15         "}\n"
16         "var f = makeClosure('0;', 'status', 'ok');\n";
17
18     // compile
19     JSObject *scriptObj = JS_CompileScript(cx, global, s, strlen(s), __FILE__, __LINE__);
20     CHECK(scriptObj);
21
22     // freeze
23     JSXDRState *w = JS_XDRNewMem(cx, JSXDR_ENCODE);
24     CHECK(w);
25     CHECK(JS_XDRScriptObject(w, &scriptObj));
26     uint32 nbytes;
27     void *p = JS_XDRMemGetData(w, &nbytes);
28     CHECK(p);
29     void *frozen = JS_malloc(cx, nbytes);
30     CHECK(frozen);
31     memcpy(frozen, p, nbytes);
32     JS_XDRDestroy(w);
33
34     // thaw
35     scriptObj = NULL;
36     JSXDRState *r = JS_XDRNewMem(cx, JSXDR_DECODE);
37     JS_XDRMemSetData(r, frozen, nbytes);
38     CHECK(JS_XDRScriptObject(r, &scriptObj));
39     JS_XDRDestroy(r);  // this frees `frozen`
40
41     // execute
42     jsvalRoot v2(cx);
43     CHECK(JS_ExecuteScript(cx, global, scriptObj, v2.addr()));
44
45     // try to break the Block object that is the parent of f
46     JS_GC(cx);
47
48     // confirm
49     EVAL("f() === 'ok';\n", v2.addr());
50     jsvalRoot trueval(cx, JSVAL_TRUE);
51     CHECK_SAME(v2, trueval);
52     return true;
53 }
54 END_TEST(testXDR_bug506491)
55
56 BEGIN_TEST(testXDR_bug516827)
57 {
58     // compile an empty script
59     JSObject *scriptObj = JS_CompileScript(cx, global, "", 0, __FILE__, __LINE__);
60     CHECK(scriptObj);
61
62     // freeze
63     JSXDRState *w = JS_XDRNewMem(cx, JSXDR_ENCODE);
64     CHECK(w);
65     CHECK(JS_XDRScriptObject(w, &scriptObj));
66     uint32 nbytes;
67     void *p = JS_XDRMemGetData(w, &nbytes);
68     CHECK(p);
69     void *frozen = JS_malloc(cx, nbytes);
70     CHECK(frozen);
71     memcpy(frozen, p, nbytes);
72     JS_XDRDestroy(w);
73
74     // thaw
75     scriptObj = NULL;
76     JSXDRState *r = JS_XDRNewMem(cx, JSXDR_DECODE);
77     JS_XDRMemSetData(r, frozen, nbytes);
78     CHECK(JS_XDRScriptObject(r, &scriptObj));
79     JS_XDRDestroy(r);  // this frees `frozen`
80
81     // execute with null result meaning no result wanted
82     CHECK(JS_ExecuteScript(cx, global, scriptObj, NULL));
83     return true;
84 }
85 END_TEST(testXDR_bug516827)