<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[209651] trunk</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.webkit.org/projects/webkit/changeset/209651">209651</a></dd>
<dt>Author</dt> <dd>jfbastien@apple.com</dd>
<dt>Date</dt> <dd>2016-12-09 23:08:31 -0800 (Fri, 09 Dec 2016)</dd>
</dl>

<h3>Log Message</h3>
<pre>WebAssembly: implement data section
https://bugs.webkit.org/show_bug.cgi?id=165696

Reviewed by Keith Miller.

As specified in https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#data-section
Note that some of the interesting corner cases are ill-defined by the spec: https://github.com/WebAssembly/design/issues/897

JSTests:

* wasm/Builder.js: create a data section from JavaScript
* wasm/Builder_WebAssemblyBinary.js: assemble the data section into the proper binary encoding
(const.emitters.Data):
* wasm/js-api/test_Data.js: Added.
(DataSection):
(DataSectionOffTheEnd):
(DataSectionPartlyOffTheEnd):
(DataSectionEmptyOffTheEnd):
(DataSectionSeenByStart):
* wasm/self-test/test_BuilderJSON.js: make sure the JSON structure is fine (this sanity checks before going to binary)

Source/JavaScriptCore:

* wasm/WasmFormat.h: segments are what represent sections of memory to initialize (similar to ELF's non-zero intializer data / rodata)
(JSC::Wasm::Segment::make):
(JSC::Wasm::Segment::destroy):
(JSC::Wasm::Segment::byte):
(JSC::Wasm::Segment::makePtr):
* wasm/WasmModuleParser.cpp: parse the data section, and prevent a few overflows if a user passes in UINT_MAX (the loops would overflow)
(JSC::Wasm::ModuleParser::parseType):
(JSC::Wasm::ModuleParser::parseImport):
(JSC::Wasm::ModuleParser::parseFunction):
(JSC::Wasm::ModuleParser::parseExport):
(JSC::Wasm::ModuleParser::parseCode):
(JSC::Wasm::ModuleParser::parseData):
* wasm/js/WebAssemblyModuleRecord.cpp:
(JSC::WebAssemblyModuleRecord::evaluate): the only sensible time to initialize the data section is after linking, but before calling start, I test for this but the spec isn't clear it's correct yet</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunkJSTestsChangeLog">trunk/JSTests/ChangeLog</a></li>
<li><a href="#trunkJSTestswasmBuilderjs">trunk/JSTests/wasm/Builder.js</a></li>
<li><a href="#trunkJSTestswasmBuilder_WebAssemblyBinaryjs">trunk/JSTests/wasm/Builder_WebAssemblyBinary.js</a></li>
<li><a href="#trunkJSTestswasmselftesttest_BuilderJSONjs">trunk/JSTests/wasm/self-test/test_BuilderJSON.js</a></li>
<li><a href="#trunkSourceJavaScriptCoreChangeLog">trunk/Source/JavaScriptCore/ChangeLog</a></li>
<li><a href="#trunkSourceJavaScriptCorewasmWasmFormath">trunk/Source/JavaScriptCore/wasm/WasmFormat.h</a></li>
<li><a href="#trunkSourceJavaScriptCorewasmWasmModuleParsercpp">trunk/Source/JavaScriptCore/wasm/WasmModuleParser.cpp</a></li>
<li><a href="#trunkSourceJavaScriptCorewasmjsWebAssemblyModuleRecordcpp">trunk/Source/JavaScriptCore/wasm/js/WebAssemblyModuleRecord.cpp</a></li>
</ul>

<h3>Added Paths</h3>
<ul>
<li><a href="#trunkJSTestswasmjsapitest_Datajs">trunk/JSTests/wasm/js-api/test_Data.js</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunkJSTestsChangeLog"></a>
<div class="modfile"><h4>Modified: trunk/JSTests/ChangeLog (209650 => 209651)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/JSTests/ChangeLog        2016-12-10 06:04:28 UTC (rev 209650)
+++ trunk/JSTests/ChangeLog        2016-12-10 07:08:31 UTC (rev 209651)
</span><span class="lines">@@ -1,5 +1,26 @@
</span><span class="cx"> 2016-12-09  JF Bastien  &lt;jfbastien@apple.com&gt;
</span><span class="cx"> 
</span><ins>+        WebAssembly: implement data section
+        https://bugs.webkit.org/show_bug.cgi?id=165696
+
+        Reviewed by Keith Miller.
+
+        As specified in https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#data-section
+        Note that some of the interesting corner cases are ill-defined by the spec: https://github.com/WebAssembly/design/issues/897
+
+        * wasm/Builder.js: create a data section from JavaScript
+        * wasm/Builder_WebAssemblyBinary.js: assemble the data section into the proper binary encoding
+        (const.emitters.Data):
+        * wasm/js-api/test_Data.js: Added.
+        (DataSection):
+        (DataSectionOffTheEnd):
+        (DataSectionPartlyOffTheEnd):
+        (DataSectionEmptyOffTheEnd):
+        (DataSectionSeenByStart):
+        * wasm/self-test/test_BuilderJSON.js: make sure the JSON structure is fine (this sanity checks before going to binary)
+
+2016-12-09  JF Bastien  &lt;jfbastien@apple.com&gt;
+
</ins><span class="cx">         WebAssembly JS API: implement start function
</span><span class="cx">         https://bugs.webkit.org/show_bug.cgi?id=165150
</span><span class="cx"> 
</span></span></pre></div>
<a id="trunkJSTestswasmBuilderjs"></a>
<div class="modfile"><h4>Modified: trunk/JSTests/wasm/Builder.js (209650 => 209651)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/JSTests/wasm/Builder.js        2016-12-10 06:04:28 UTC (rev 209650)
+++ trunk/JSTests/wasm/Builder.js        2016-12-10 07:08:31 UTC (rev 209651)
</span><span class="lines">@@ -523,8 +523,38 @@
</span><span class="cx">                 break;
</span><span class="cx"> 
</span><span class="cx">             case &quot;Data&quot;:
</span><del>-                // FIXME implement data https://bugs.webkit.org/show_bug.cgi?id=161709
-                this[section] = () =&gt; { throw new Error(`Unimplemented: section type &quot;${section}&quot;`); };
</del><ins>+                this[section] = function() {
+                    const s = this._addSection(section);
+                    const dataBuilder = {
+                        End: () =&gt; this,
+                        Segment: data =&gt; {
+                            assert.isArray(data);
+                            for (const datum of data) {
+                                assert.isNumber(datum);
+                                assert.ge(datum, 0);
+                                assert.le(datum, 0xff);
+                            }
+                            s.data.push({ data: data, index: 0, offset: 0 });
+                            let thisSegment = s.data[s.data.length - 1];
+                            const segmentBuilder = {
+                                End: () =&gt; dataBuilder,
+                                Index: index =&gt; {
+                                    assert.eq(index, 0); // Linear memory index must be zero in MVP.
+                                    thisSegment.index = index;
+                                    return segmentBuilder;
+                                },
+                                Offset: offset =&gt; {
+                                    // FIXME allow complex init_expr here. https://bugs.webkit.org/show_bug.cgi?id=165700
+                                    assert.isNumber(offset);
+                                    thisSegment.offset = offset;
+                                    return segmentBuilder;
+                                },
+                            };
+                            return segmentBuilder;
+                        },
+                    };
+                    return dataBuilder;
+                };
</ins><span class="cx">                 break;
</span><span class="cx"> 
</span><span class="cx">             default:
</span></span></pre></div>
<a id="trunkJSTestswasmBuilder_WebAssemblyBinaryjs"></a>
<div class="modfile"><h4>Modified: trunk/JSTests/wasm/Builder_WebAssemblyBinary.js (209650 => 209651)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/JSTests/wasm/Builder_WebAssemblyBinary.js        2016-12-10 06:04:28 UTC (rev 209650)
+++ trunk/JSTests/wasm/Builder_WebAssemblyBinary.js        2016-12-10 07:08:31 UTC (rev 209651)
</span><span class="lines">@@ -156,7 +156,20 @@
</span><span class="cx">         }
</span><span class="cx">     },
</span><span class="cx"> 
</span><del>-    Data: (section, bin) =&gt; { throw new Error(`Not yet implemented`); },
</del><ins>+    Data: (section, bin) =&gt; {
+        put(bin, &quot;varuint32&quot;, section.data.length);
+        for (const datum of section.data) {
+            put(bin, &quot;varuint32&quot;, datum.index);
+            // FIXME allow complex init_expr here. https://bugs.webkit.org/show_bug.cgi?id=165700
+            // For now we only handle i32.const as offset.
+            put(bin, &quot;uint8&quot;, WASM.description.opcode[&quot;i32.const&quot;].value);
+            put(bin, WASM.description.opcode[&quot;i32.const&quot;].immediate[0].type, datum.offset);
+            put(bin, &quot;uint8&quot;, WASM.description.opcode[&quot;end&quot;].value);
+            put(bin, &quot;varuint32&quot;, datum.data.length);
+            for (const byte of datum.data)
+                put(bin, &quot;uint8&quot;, byte);
+        }
+    },
</ins><span class="cx"> };
</span><span class="cx"> 
</span><span class="cx"> export const Binary = (preamble, sections) =&gt; {
</span></span></pre></div>
<a id="trunkJSTestswasmjsapitest_Datajs"></a>
<div class="addfile"><h4>Added: trunk/JSTests/wasm/js-api/test_Data.js (0 => 209651)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/JSTests/wasm/js-api/test_Data.js                                (rev 0)
+++ trunk/JSTests/wasm/js-api/test_Data.js        2016-12-10 07:08:31 UTC (rev 209651)
</span><span class="lines">@@ -0,0 +1,135 @@
</span><ins>+import * as assert from '../assert.js';
+import Builder from '../Builder.js';
+
+const memSizeInPages = 1;
+const pageSizeInBytes = 64 * 1024;
+const memoryDescription = { initial: memSizeInPages, maximum: memSizeInPages };
+
+// FIXME Some corner cases are ill-specified: https://github.com/WebAssembly/design/issues/897
+
+(function DataSection() {
+    const builder = (new Builder())
+        .Type().End()
+        .Import().Memory(&quot;imp&quot;, &quot;memory&quot;, memoryDescription).End()
+        .Data()
+          .Segment([0xff, 0x2a]).Offset(4).End()
+          .Segment([0xde, 0xad, 0xbe, 0xef]).Offset(24).End()
+          .Segment([0xca, 0xfe]).Offset(25).End() // Overwrite.
+          .Segment([]).Offset(4).End() // Empty.
+        .End();
+    const bin = builder.WebAssembly().get();
+    const module = new WebAssembly.Module(bin);
+    const memory = new WebAssembly.Memory(memoryDescription);
+    const instance = new WebAssembly.Instance(module, { imp: { memory: memory } });
+    const buffer = new Uint8Array(memory.buffer);
+    for (let idx = 0; idx &lt; memSizeInPages * pageSizeInBytes; ++idx) {
+        const value = buffer[idx];
+        switch (idx) {
+        case 4: assert.eq(value, 0xff); break;
+        case 5: assert.eq(value, 0x2a); break;
+        case 24: assert.eq(value, 0xde); break;
+        case 25: assert.eq(value, 0xca); break;
+        case 26: assert.eq(value, 0xfe); break;
+        case 27: assert.eq(value, 0xef); break;
+        default: assert.eq(value, 0x00); break;
+        }
+    }
+})();
+
+(function DataSectionOffTheEnd() {
+    const builder = (new Builder())
+        .Type().End()
+        .Import().Memory(&quot;imp&quot;, &quot;memory&quot;, memoryDescription).End()
+        .Data()
+          .Segment([0xff]).Offset(memSizeInPages * pageSizeInBytes).End()
+        .End();
+    const bin = builder.WebAssembly().get();
+    const module = new WebAssembly.Module(bin);
+    const memory = new WebAssembly.Memory(memoryDescription);
+    assert.throws(() =&gt; new WebAssembly.Instance(module, { imp: { memory: memory } }), RangeError, `Data segment initializes memory out of range`);
+    const buffer = new Uint8Array(memory.buffer);
+    for (let idx = 0; idx &lt; memSizeInPages * pageSizeInBytes; ++idx) {
+        const value = buffer[idx];
+        assert.eq(value, 0x00);
+    }
+})();
+
+(function DataSectionPartlyOffTheEnd() {
+    const builder = (new Builder())
+        .Type().End()
+        .Import().Memory(&quot;imp&quot;, &quot;memory&quot;, memoryDescription).End()
+        .Data()
+          .Segment([0xff, 0xff]).Offset(memSizeInPages * pageSizeInBytes - 1).End()
+        .End();
+    const bin = builder.WebAssembly().get();
+    const module = new WebAssembly.Module(bin);
+    const memory = new WebAssembly.Memory(memoryDescription);
+    assert.throws(() =&gt; new WebAssembly.Instance(module, { imp: { memory: memory } }), RangeError, `Data segment initializes memory out of range`);
+    const buffer = new Uint8Array(memory.buffer);
+    for (let idx = 0; idx &lt; memSizeInPages * pageSizeInBytes; ++idx) {
+        const value = buffer[idx];
+        assert.eq(value, 0x00);
+    }
+})();
+
+(function DataSectionEmptyOffTheEnd() {
+    const builder = (new Builder())
+        .Type().End()
+        .Import().Memory(&quot;imp&quot;, &quot;memory&quot;, memoryDescription).End()
+        .Data()
+          .Segment([]).Offset(memSizeInPages * pageSizeInBytes).End()
+        .End();
+    const bin = builder.WebAssembly().get();
+    const module = new WebAssembly.Module(bin);
+    const memory = new WebAssembly.Memory(memoryDescription);
+    const instance = new WebAssembly.Instance(module, { imp: { memory: memory } });
+    const buffer = new Uint8Array(memory.buffer);
+    for (let idx = 0; idx &lt; memSizeInPages * pageSizeInBytes; ++idx) {
+        const value = buffer[idx];
+        assert.eq(value, 0x00);
+    }
+})();
+
+(function DataSectionSeenByStart() {
+    const offset = 1024;
+    const builder = (new Builder())
+        .Type().End()
+        .Import()
+            .Memory(&quot;imp&quot;, &quot;memory&quot;, memoryDescription)
+            .Function(&quot;imp&quot;, &quot;func&quot;, { params: [&quot;i32&quot;] })
+        .End()
+        .Function().End()
+        .Start(&quot;foo&quot;).End()
+        .Code()
+            .Function(&quot;foo&quot;, { params: [] })
+                .I32Const(offset)
+                .I32Load8U(2, 0)
+                .Call(0) // Calls func((i8.load(offset), align=2, offset=0). This should observe 0xff as set by the data section.
+            .End()
+        .End()
+        .Data()
+          .Segment([0xff]).Offset(offset).End()
+        .End();
+    const bin = builder.WebAssembly().get();
+    const module = new WebAssembly.Module(bin);
+    const memory = new WebAssembly.Memory(memoryDescription);
+    let value = 0;
+    const setter = v =&gt; value = v;
+    const instance = new WebAssembly.Instance(
+        module,
+        {
+            imp: {
+                memory: memory,
+                func: setter
+            }
+        });
+    assert.eq(value, 0xff);
+    const buffer = new Uint8Array(memory.buffer);
+    for (let idx = 0; idx &lt; memSizeInPages * pageSizeInBytes; ++idx) {
+        const value = buffer[idx];
+        if (idx == offset)
+            assert.eq(value, 0xff);
+        else
+            assert.eq(value, 0x00);
+    }
+})();
</ins></span></pre></div>
<a id="trunkJSTestswasmselftesttest_BuilderJSONjs"></a>
<div class="modfile"><h4>Modified: trunk/JSTests/wasm/self-test/test_BuilderJSON.js (209650 => 209651)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/JSTests/wasm/self-test/test_BuilderJSON.js        2016-12-10 06:04:28 UTC (rev 209650)
+++ trunk/JSTests/wasm/self-test/test_BuilderJSON.js        2016-12-10 07:08:31 UTC (rev 209651)
</span><span class="lines">@@ -619,6 +619,7 @@
</span><span class="cx">     assert.eq(j.section[1].data[0].code.length, 6);
</span><span class="cx">     assert.eq(j.section[1].data[0].code[3].name, &quot;select&quot;);
</span><span class="cx"> })();
</span><ins>+// FIXME test type mismatch with select. https://bugs.webkit.org/show_bug.cgi?id=163267
</ins><span class="cx"> 
</span><span class="cx"> (function MemoryImport() {
</span><span class="cx">     const builder = (new Builder())
</span><span class="lines">@@ -639,4 +640,27 @@
</span><span class="cx">     assert.eq(json.section[1].data[0].memoryDescription.maximum, 31);
</span><span class="cx"> })();
</span><span class="cx"> 
</span><del>-// FIXME test type mismatch with select. https://bugs.webkit.org/show_bug.cgi?id=163267
</del><ins>+(function DataSection() {
+    const builder = (new Builder())
+        .Memory().InitialMaxPages(64, 64).End()
+        .Data()
+          .Segment([0xff, 0x2a]).Offset(4).End()
+          .Segment([0xde, 0xad, 0xbe, 0xef]).Index(0).Offset(24).End()
+        .End();
+    const json = JSON.parse(builder.json());
+    assert.eq(json.section.length, 2);
+    assert.eq(json.section[1].name, &quot;Data&quot;);
+    assert.eq(json.section[1].data.length, 2);
+    assert.eq(json.section[1].data[0].index, 0);
+    assert.eq(json.section[1].data[0].offset, 4);
+    assert.eq(json.section[1].data[0].data.length, 2);
+    assert.eq(json.section[1].data[0].data[0], 0xff);
+    assert.eq(json.section[1].data[0].data[1], 0x2a);
+    assert.eq(json.section[1].data[1].index, 0);
+    assert.eq(json.section[1].data[1].offset, 24);
+    assert.eq(json.section[1].data[1].data.length, 4);
+    assert.eq(json.section[1].data[1].data[0], 0xde);
+    assert.eq(json.section[1].data[1].data[1], 0xad);
+    assert.eq(json.section[1].data[1].data[2], 0xbe);
+    assert.eq(json.section[1].data[1].data[3], 0xef);
+})();
</ins></span></pre></div>
<a id="trunkSourceJavaScriptCoreChangeLog"></a>
<div class="modfile"><h4>Modified: trunk/Source/JavaScriptCore/ChangeLog (209650 => 209651)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/JavaScriptCore/ChangeLog        2016-12-10 06:04:28 UTC (rev 209650)
+++ trunk/Source/JavaScriptCore/ChangeLog        2016-12-10 07:08:31 UTC (rev 209651)
</span><span class="lines">@@ -1,3 +1,28 @@
</span><ins>+2016-12-09  JF Bastien  &lt;jfbastien@apple.com&gt;
+
+        WebAssembly: implement data section
+        https://bugs.webkit.org/show_bug.cgi?id=165696
+
+        Reviewed by Keith Miller.
+
+        As specified in https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#data-section
+        Note that some of the interesting corner cases are ill-defined by the spec: https://github.com/WebAssembly/design/issues/897
+
+        * wasm/WasmFormat.h: segments are what represent sections of memory to initialize (similar to ELF's non-zero intializer data / rodata)
+        (JSC::Wasm::Segment::make):
+        (JSC::Wasm::Segment::destroy):
+        (JSC::Wasm::Segment::byte):
+        (JSC::Wasm::Segment::makePtr):
+        * wasm/WasmModuleParser.cpp: parse the data section, and prevent a few overflows if a user passes in UINT_MAX (the loops would overflow)
+        (JSC::Wasm::ModuleParser::parseType):
+        (JSC::Wasm::ModuleParser::parseImport):
+        (JSC::Wasm::ModuleParser::parseFunction):
+        (JSC::Wasm::ModuleParser::parseExport):
+        (JSC::Wasm::ModuleParser::parseCode):
+        (JSC::Wasm::ModuleParser::parseData):
+        * wasm/js/WebAssemblyModuleRecord.cpp:
+        (JSC::WebAssemblyModuleRecord::evaluate): the only sensible time to initialize the data section is after linking, but before calling start, I test for this but the spec isn't clear it's correct yet
+
</ins><span class="cx"> 2016-12-09  Karim H  &lt;karim@karhm.com&gt;
</span><span class="cx"> 
</span><span class="cx">         It is okay to turn undefined into null because we are producing values for a
</span></span></pre></div>
<a id="trunkSourceJavaScriptCorewasmWasmFormath"></a>
<div class="modfile"><h4>Modified: trunk/Source/JavaScriptCore/wasm/WasmFormat.h (209650 => 209651)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/JavaScriptCore/wasm/WasmFormat.h        2016-12-10 06:04:28 UTC (rev 209650)
+++ trunk/Source/JavaScriptCore/wasm/WasmFormat.h        2016-12-10 07:08:31 UTC (rev 209651)
</span><span class="lines">@@ -35,6 +35,8 @@
</span><span class="cx"> #include &quot;WasmMemoryInformation.h&quot;
</span><span class="cx"> #include &quot;WasmOps.h&quot;
</span><span class="cx"> #include &quot;WasmPageCount.h&quot;
</span><ins>+#include &lt;memory&gt;
+#include &lt;wtf/FastMalloc.h&gt;
</ins><span class="cx"> #include &lt;wtf/Optional.h&gt;
</span><span class="cx"> #include &lt;wtf/Vector.h&gt;
</span><span class="cx"> 
</span><span class="lines">@@ -114,6 +116,35 @@
</span><span class="cx">     size_t end;
</span><span class="cx"> };
</span><span class="cx"> 
</span><ins>+struct Segment {
+    uint32_t offset;
+    uint32_t sizeInBytes;
+    // Bytes are allocated at the end.
+    static Segment* make(uint32_t offset, uint32_t sizeInBytes)
+    {
+        auto allocated = tryFastCalloc(sizeof(Segment) + sizeInBytes, 1);
+        Segment* segment;
+        if (!allocated.getValue(segment))
+            return nullptr;
+        segment-&gt;offset = offset;
+        segment-&gt;sizeInBytes = sizeInBytes;
+        return segment;
+    }
+    static void destroy(Segment *segment)
+    {
+        fastFree(segment);
+    }
+    uint8_t&amp; byte(uint32_t pos)
+    {
+        ASSERT(pos &lt; sizeInBytes);
+        return *reinterpret_cast&lt;uint8_t*&gt;(reinterpret_cast&lt;char*&gt;(this) + sizeof(offset) + sizeof(sizeInBytes) + pos);
+    }
+    typedef std::unique_ptr&lt;Segment, decltype(&amp;Segment::destroy)&gt; Ptr;
+    static Ptr makePtr(Segment* segment)
+    {
+        return Ptr(segment, &amp;Segment::destroy);
+    }
+};
</ins><span class="cx"> 
</span><span class="cx"> struct ModuleInformation {
</span><span class="cx">     Vector&lt;Signature&gt; signatures;
</span><span class="lines">@@ -125,6 +156,7 @@
</span><span class="cx">     MemoryInformation memory;
</span><span class="cx">     Vector&lt;Export&gt; exports;
</span><span class="cx">     std::optional&lt;uint32_t&gt; startFunctionIndexSpace;
</span><ins>+    Vector&lt;Segment::Ptr&gt; data;
</ins><span class="cx"> 
</span><span class="cx">     ~ModuleInformation();
</span><span class="cx"> };
</span></span></pre></div>
<a id="trunkSourceJavaScriptCorewasmWasmModuleParsercpp"></a>
<div class="modfile"><h4>Modified: trunk/Source/JavaScriptCore/wasm/WasmModuleParser.cpp (209650 => 209651)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/JavaScriptCore/wasm/WasmModuleParser.cpp        2016-12-10 06:04:28 UTC (rev 209650)
+++ trunk/Source/JavaScriptCore/wasm/WasmModuleParser.cpp        2016-12-10 07:08:31 UTC (rev 209651)
</span><span class="lines">@@ -157,12 +157,12 @@
</span><span class="cx"> bool ModuleParser::parseType()
</span><span class="cx"> {
</span><span class="cx">     uint32_t count;
</span><del>-    if (!parseVarUInt32(count))
</del><ins>+    if (!parseVarUInt32(count)
+        || count == std::numeric_limits&lt;uint32_t&gt;::max()
+        || !m_module-&gt;signatures.tryReserveCapacity(count))
</ins><span class="cx">         return false;
</span><span class="cx">     if (verbose)
</span><del>-        dataLogLn(&quot;count: &quot;, count);
-    if (!m_module-&gt;signatures.tryReserveCapacity(count))
-        return false;
</del><ins>+        dataLogLn(&quot;  count: &quot;, count);
</ins><span class="cx"> 
</span><span class="cx">     for (uint32_t i = 0; i &lt; count; ++i) {
</span><span class="cx">         int8_t type;
</span><span class="lines">@@ -175,17 +175,15 @@
</span><span class="cx">             dataLogLn(&quot;Got function type.&quot;);
</span><span class="cx"> 
</span><span class="cx">         uint32_t argumentCount;
</span><del>-        if (!parseVarUInt32(argumentCount))
</del><ins>+        Vector&lt;Type&gt; argumentTypes;
+        if (!parseVarUInt32(argumentCount)
+            || argumentCount == std::numeric_limits&lt;uint32_t&gt;::max()
+            || !argumentTypes.tryReserveCapacity(argumentCount))
</ins><span class="cx">             return false;
</span><del>-
</del><span class="cx">         if (verbose)
</span><del>-            dataLogLn(&quot;argumentCount: &quot;, argumentCount);
</del><ins>+            dataLogLn(&quot;  argument count: &quot;, argumentCount);
</ins><span class="cx"> 
</span><del>-        Vector&lt;Type&gt; argumentTypes;
-        if (!argumentTypes.tryReserveCapacity(argumentCount))
-            return false;
-
-        for (unsigned i = 0; i != argumentCount; ++i) {
</del><ins>+        for (unsigned i = 0; i &lt; argumentCount; ++i) {
</ins><span class="cx">             Type argumentType;
</span><span class="cx">             if (!parseResultType(argumentType))
</span><span class="cx">                 return false;
</span><span class="lines">@@ -216,14 +214,14 @@
</span><span class="cx"> bool ModuleParser::parseImport()
</span><span class="cx"> {
</span><span class="cx">     uint32_t importCount;
</span><del>-    if (!parseVarUInt32(importCount))
-        return false;
-    if (!m_module-&gt;imports.tryReserveCapacity(importCount) // FIXME this over-allocates when we fix the FIXMEs below.
</del><ins>+    if (!parseVarUInt32(importCount)
+        || importCount == std::numeric_limits&lt;uint32_t&gt;::max()
+        || !m_module-&gt;imports.tryReserveCapacity(importCount) // FIXME this over-allocates when we fix the FIXMEs below.
</ins><span class="cx">         || !m_module-&gt;importFunctions.tryReserveCapacity(importCount) // FIXME this over-allocates when we fix the FIXMEs below.
</span><span class="cx">         || !m_functionIndexSpace.tryReserveCapacity(importCount)) // FIXME this over-allocates when we fix the FIXMEs below. We'll allocate some more here when we know how many functions to expect.
</span><span class="cx">         return false;
</span><span class="cx"> 
</span><del>-    for (uint32_t importNumber = 0; importNumber != importCount; ++importNumber) {
</del><ins>+    for (uint32_t importNumber = 0; importNumber &lt; importCount; ++importNumber) {
</ins><span class="cx">         Import imp;
</span><span class="cx">         uint32_t moduleLen;
</span><span class="cx">         uint32_t fieldLen;
</span><span class="lines">@@ -278,12 +276,13 @@
</span><span class="cx"> {
</span><span class="cx">     uint32_t count;
</span><span class="cx">     if (!parseVarUInt32(count)
</span><ins>+        || count == std::numeric_limits&lt;uint32_t&gt;::max()
</ins><span class="cx">         || !m_module-&gt;internalFunctionSignatures.tryReserveCapacity(count)
</span><span class="cx">         || !m_functionLocationInBinary.tryReserveCapacity(count)
</span><span class="cx">         || !m_functionIndexSpace.tryReserveCapacity(m_functionIndexSpace.size() + count))
</span><span class="cx">         return false;
</span><span class="cx"> 
</span><del>-    for (uint32_t i = 0; i != count; ++i) {
</del><ins>+    for (uint32_t i = 0; i &lt; count; ++i) {
</ins><span class="cx">         uint32_t typeNumber;
</span><span class="cx">         if (!parseVarUInt32(typeNumber)
</span><span class="cx">             || typeNumber &gt;= m_module-&gt;signatures.size())
</span><span class="lines">@@ -374,10 +373,11 @@
</span><span class="cx"> {
</span><span class="cx">     uint32_t exportCount;
</span><span class="cx">     if (!parseVarUInt32(exportCount)
</span><ins>+        || exportCount == std::numeric_limits&lt;uint32_t&gt;::max()
</ins><span class="cx">         || !m_module-&gt;exports.tryReserveCapacity(exportCount))
</span><span class="cx">         return false;
</span><span class="cx"> 
</span><del>-    for (uint32_t exportNumber = 0; exportNumber != exportCount; ++exportNumber) {
</del><ins>+    for (uint32_t exportNumber = 0; exportNumber &lt; exportCount; ++exportNumber) {
</ins><span class="cx">         Export exp;
</span><span class="cx">         uint32_t fieldLen;
</span><span class="cx">         String fieldString;
</span><span class="lines">@@ -385,8 +385,10 @@
</span><span class="cx">             || !consumeUTF8String(fieldString, fieldLen))
</span><span class="cx">             return false;
</span><span class="cx">         exp.field = Identifier::fromString(m_vm, fieldString);
</span><ins>+
</ins><span class="cx">         if (!parseExternalKind(exp.kind))
</span><span class="cx">             return false;
</span><ins>+
</ins><span class="cx">         switch (exp.kind) {
</span><span class="cx">         case External::Function: {
</span><span class="cx">             if (!parseVarUInt32(exp.functionIndex)
</span><span class="lines">@@ -440,10 +442,11 @@
</span><span class="cx"> {
</span><span class="cx">     uint32_t count;
</span><span class="cx">     if (!parseVarUInt32(count)
</span><ins>+        || count == std::numeric_limits&lt;uint32_t&gt;::max()
</ins><span class="cx">         || count != m_functionLocationInBinary.size())
</span><span class="cx">         return false;
</span><span class="cx"> 
</span><del>-    for (uint32_t i = 0; i != count; ++i) {
</del><ins>+    for (uint32_t i = 0; i &lt; count; ++i) {
</ins><span class="cx">         uint32_t functionSize;
</span><span class="cx">         if (!parseVarUInt32(functionSize)
</span><span class="cx">             || functionSize &gt; length()
</span><span class="lines">@@ -460,8 +463,56 @@
</span><span class="cx"> 
</span><span class="cx"> bool ModuleParser::parseData()
</span><span class="cx"> {
</span><del>-    // FIXME https://bugs.webkit.org/show_bug.cgi?id=161709
-    RELEASE_ASSERT_NOT_REACHED();
</del><ins>+    uint32_t segmentCount;
+    if (!parseVarUInt32(segmentCount)
+        || segmentCount == std::numeric_limits&lt;uint32_t&gt;::max()
+        || !m_module-&gt;data.tryReserveCapacity(segmentCount))
+        return false;
+    if (verbose)
+        dataLogLn(&quot;  segments: &quot;, segmentCount);
+
+    for (uint32_t segmentNumber = 0; segmentNumber &lt; segmentCount; ++segmentNumber) {
+        if (verbose)
+            dataLogLn(&quot;  segment #&quot;, segmentNumber);
+        uint32_t index;
+        uint8_t opcode;
+        uint32_t offset;
+        uint8_t endOpcode;
+        uint32_t dataByteLength;
+        if (!parseVarUInt32(index)
+            || index)
+            return false;
+
+        // FIXME allow complex init_expr here. https://bugs.webkit.org/show_bug.cgi?id=165700
+        // For now we only handle i32.const as offset.
+        if (!parseUInt8(opcode)
+            || opcode != Wasm::I32Const
+            || !parseVarUInt32(offset)
+            || !parseUInt8(endOpcode)
+            || endOpcode != Wasm::End)
+            return false;
+        if (verbose)
+            dataLogLn(&quot;    offset: &quot;, offset);
+
+        if (!parseVarUInt32(dataByteLength)
+            || dataByteLength == std::numeric_limits&lt;uint32_t&gt;::max())
+            return false;
+        if (verbose)
+            dataLogLn(&quot;    data bytes: &quot;, dataByteLength);
+
+        Segment* segment = Segment::make(offset, dataByteLength);
+        if (!segment)
+            return false;
+        m_module-&gt;data.uncheckedAppend(Segment::makePtr(segment));
+        for (uint32_t dataByte = 0; dataByte &lt; dataByteLength; ++dataByte) {
+            uint8_t byte;
+            if (!parseUInt8(byte))
+                return false;
+            segment-&gt;byte(dataByte) = byte;
+            if (verbose)
+                dataLogLn(&quot;    [&quot;, dataByte, &quot;] = &quot;, segment-&gt;byte(dataByte));
+        }
+    }
</ins><span class="cx">     return true;
</span><span class="cx"> }
</span><span class="cx"> 
</span></span></pre></div>
<a id="trunkSourceJavaScriptCorewasmjsWebAssemblyModuleRecordcpp"></a>
<div class="modfile"><h4>Modified: trunk/Source/JavaScriptCore/wasm/js/WebAssemblyModuleRecord.cpp (209650 => 209651)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/JavaScriptCore/wasm/js/WebAssemblyModuleRecord.cpp        2016-12-10 06:04:28 UTC (rev 209650)
+++ trunk/Source/JavaScriptCore/wasm/js/WebAssemblyModuleRecord.cpp        2016-12-10 07:08:31 UTC (rev 209651)
</span><span class="lines">@@ -187,9 +187,27 @@
</span><span class="cx"> 
</span><span class="cx"> JSValue WebAssemblyModuleRecord::evaluate(ExecState* state)
</span><span class="cx"> {
</span><ins>+    VM&amp; vm = state-&gt;vm();
+    auto scope = DECLARE_THROW_SCOPE(vm);
+
+    if (JSWebAssemblyMemory* jsMemory = m_instance-&gt;memory()) {
+        uint8_t* memory = reinterpret_cast&lt;uint8_t*&gt;(jsMemory-&gt;memory()-&gt;memory());
+        auto sizeInBytes = jsMemory-&gt;memory()-&gt;size();
+        if (memory) {
+            const Vector&lt;Wasm::Segment::Ptr&gt;&amp; data = m_instance-&gt;module()-&gt;moduleInformation().data;
+            for (auto&amp; segment : data) {
+                if (segment-&gt;sizeInBytes) {
+                    if (sizeInBytes &lt; segment-&gt;sizeInBytes
+                        || segment-&gt;offset &gt; sizeInBytes
+                        || segment-&gt;offset &gt; sizeInBytes - segment-&gt;sizeInBytes)
+                        return throwException(state, scope, createRangeError(state, ASCIILiteral(&quot;Data segment initializes memory out of range&quot;)));
+                    memcpy(memory + segment-&gt;offset, &amp;segment-&gt;byte(0), segment-&gt;sizeInBytes);
+                }
+            }
+        }
+    }
+
</ins><span class="cx">     if (WebAssemblyFunction* startFunction = m_startFunction.get()) {
</span><del>-        VM&amp; vm = state-&gt;vm();
-        auto scope = DECLARE_THROW_SCOPE(vm);
</del><span class="cx">         ProtoCallFrame protoCallFrame;
</span><span class="cx">         protoCallFrame.init(nullptr, startFunction, JSValue(), 1, nullptr);
</span><span class="cx">         startFunction-&gt;call(vm, &amp;protoCallFrame);
</span></span></pre>
</div>
</div>

</body>
</html>