• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/wasm/wasm-module-builder.h"
6 
7 #include "src/base/memory.h"
8 #include "src/codegen/signature.h"
9 #include "src/handles/handles.h"
10 #include "src/init/v8.h"
11 #include "src/objects/objects-inl.h"
12 #include "src/wasm/function-body-decoder.h"
13 #include "src/wasm/leb-helper.h"
14 #include "src/wasm/wasm-constants.h"
15 #include "src/wasm/wasm-module.h"
16 #include "src/zone/zone-containers.h"
17 
18 namespace v8 {
19 namespace internal {
20 namespace wasm {
21 
22 namespace {
23 
24 // Emit a section code and the size as a padded varint that can be patched
25 // later.
EmitSection(SectionCode code,ZoneBuffer * buffer)26 size_t EmitSection(SectionCode code, ZoneBuffer* buffer) {
27   // Emit the section code.
28   buffer->write_u8(code);
29 
30   // Emit a placeholder for the length.
31   return buffer->reserve_u32v();
32 }
33 
34 // Patch the size of a section after it's finished.
FixupSection(ZoneBuffer * buffer,size_t start)35 void FixupSection(ZoneBuffer* buffer, size_t start) {
36   buffer->patch_u32v(start, static_cast<uint32_t>(buffer->offset() - start -
37                                                   kPaddedVarInt32Size));
38 }
39 
40 }  // namespace
41 
WasmFunctionBuilder(WasmModuleBuilder * builder)42 WasmFunctionBuilder::WasmFunctionBuilder(WasmModuleBuilder* builder)
43     : builder_(builder),
44       locals_(builder->zone()),
45       signature_index_(0),
46       func_index_(static_cast<uint32_t>(builder->functions_.size())),
47       body_(builder->zone(), 256),
48       i32_temps_(builder->zone()),
49       i64_temps_(builder->zone()),
50       f32_temps_(builder->zone()),
51       f64_temps_(builder->zone()),
52       direct_calls_(builder->zone()),
53       asm_offsets_(builder->zone(), 8) {}
54 
EmitByte(byte val)55 void WasmFunctionBuilder::EmitByte(byte val) { body_.write_u8(val); }
56 
EmitI32V(int32_t val)57 void WasmFunctionBuilder::EmitI32V(int32_t val) { body_.write_i32v(val); }
58 
EmitU32V(uint32_t val)59 void WasmFunctionBuilder::EmitU32V(uint32_t val) { body_.write_u32v(val); }
60 
SetSignature(const FunctionSig * sig)61 void WasmFunctionBuilder::SetSignature(const FunctionSig* sig) {
62   DCHECK(!locals_.has_sig());
63   locals_.set_sig(sig);
64   signature_index_ = builder_->AddSignature(sig);
65 }
66 
SetSignature(uint32_t sig_index)67 void WasmFunctionBuilder::SetSignature(uint32_t sig_index) {
68   DCHECK(!locals_.has_sig());
69   DCHECK_EQ(builder_->types_[sig_index].kind, TypeDefinition::kFunction);
70   signature_index_ = sig_index;
71   locals_.set_sig(builder_->types_[sig_index].function_sig);
72 }
73 
AddLocal(ValueType type)74 uint32_t WasmFunctionBuilder::AddLocal(ValueType type) {
75   DCHECK(locals_.has_sig());
76   return locals_.AddLocals(1, type);
77 }
78 
EmitGetLocal(uint32_t local_index)79 void WasmFunctionBuilder::EmitGetLocal(uint32_t local_index) {
80   EmitWithU32V(kExprLocalGet, local_index);
81 }
82 
EmitSetLocal(uint32_t local_index)83 void WasmFunctionBuilder::EmitSetLocal(uint32_t local_index) {
84   EmitWithU32V(kExprLocalSet, local_index);
85 }
86 
EmitTeeLocal(uint32_t local_index)87 void WasmFunctionBuilder::EmitTeeLocal(uint32_t local_index) {
88   EmitWithU32V(kExprLocalTee, local_index);
89 }
90 
EmitCode(const byte * code,uint32_t code_size)91 void WasmFunctionBuilder::EmitCode(const byte* code, uint32_t code_size) {
92   body_.write(code, code_size);
93 }
94 
Emit(WasmOpcode opcode)95 void WasmFunctionBuilder::Emit(WasmOpcode opcode) { body_.write_u8(opcode); }
96 
EmitWithPrefix(WasmOpcode opcode)97 void WasmFunctionBuilder::EmitWithPrefix(WasmOpcode opcode) {
98   DCHECK_NE(0, opcode & 0xff00);
99   body_.write_u8(opcode >> 8);
100   if ((opcode >> 8) == WasmOpcode::kSimdPrefix) {
101     // SIMD opcodes are LEB encoded
102     body_.write_u32v(opcode & 0xff);
103   } else {
104     body_.write_u8(opcode);
105   }
106 }
107 
EmitWithU8(WasmOpcode opcode,const byte immediate)108 void WasmFunctionBuilder::EmitWithU8(WasmOpcode opcode, const byte immediate) {
109   body_.write_u8(opcode);
110   body_.write_u8(immediate);
111 }
112 
EmitWithU8U8(WasmOpcode opcode,const byte imm1,const byte imm2)113 void WasmFunctionBuilder::EmitWithU8U8(WasmOpcode opcode, const byte imm1,
114                                        const byte imm2) {
115   body_.write_u8(opcode);
116   body_.write_u8(imm1);
117   body_.write_u8(imm2);
118 }
119 
EmitWithI32V(WasmOpcode opcode,int32_t immediate)120 void WasmFunctionBuilder::EmitWithI32V(WasmOpcode opcode, int32_t immediate) {
121   body_.write_u8(opcode);
122   body_.write_i32v(immediate);
123 }
124 
EmitWithU32V(WasmOpcode opcode,uint32_t immediate)125 void WasmFunctionBuilder::EmitWithU32V(WasmOpcode opcode, uint32_t immediate) {
126   body_.write_u8(opcode);
127   body_.write_u32v(immediate);
128 }
129 
130 namespace {
WriteValueType(ZoneBuffer * buffer,const ValueType & type)131 void WriteValueType(ZoneBuffer* buffer, const ValueType& type) {
132   buffer->write_u8(type.value_type_code());
133   if (type.encoding_needs_heap_type()) {
134     buffer->write_i32v(type.heap_type().code());
135   }
136   if (type.is_rtt()) {
137     buffer->write_u32v(type.ref_index());
138   }
139 }
140 }  // namespace
141 
EmitValueType(ValueType type)142 void WasmFunctionBuilder::EmitValueType(ValueType type) {
143   WriteValueType(&body_, type);
144 }
145 
EmitI32Const(int32_t value)146 void WasmFunctionBuilder::EmitI32Const(int32_t value) {
147   EmitWithI32V(kExprI32Const, value);
148 }
149 
EmitI64Const(int64_t value)150 void WasmFunctionBuilder::EmitI64Const(int64_t value) {
151   body_.write_u8(kExprI64Const);
152   body_.write_i64v(value);
153 }
154 
EmitF32Const(float value)155 void WasmFunctionBuilder::EmitF32Const(float value) {
156   body_.write_u8(kExprF32Const);
157   body_.write_f32(value);
158 }
159 
EmitF64Const(double value)160 void WasmFunctionBuilder::EmitF64Const(double value) {
161   body_.write_u8(kExprF64Const);
162   body_.write_f64(value);
163 }
164 
EmitDirectCallIndex(uint32_t index)165 void WasmFunctionBuilder::EmitDirectCallIndex(uint32_t index) {
166   DirectCallIndex call;
167   call.offset = body_.size();
168   call.direct_index = index;
169   direct_calls_.push_back(call);
170   byte placeholder_bytes[kMaxVarInt32Size] = {0};
171   EmitCode(placeholder_bytes, arraysize(placeholder_bytes));
172 }
173 
SetName(base::Vector<const char> name)174 void WasmFunctionBuilder::SetName(base::Vector<const char> name) {
175   name_ = name;
176 }
177 
AddAsmWasmOffset(size_t call_position,size_t to_number_position)178 void WasmFunctionBuilder::AddAsmWasmOffset(size_t call_position,
179                                            size_t to_number_position) {
180   // We only want to emit one mapping per byte offset.
181   DCHECK(asm_offsets_.size() == 0 || body_.size() > last_asm_byte_offset_);
182 
183   DCHECK_LE(body_.size(), kMaxUInt32);
184   uint32_t byte_offset = static_cast<uint32_t>(body_.size());
185   asm_offsets_.write_u32v(byte_offset - last_asm_byte_offset_);
186   last_asm_byte_offset_ = byte_offset;
187 
188   DCHECK_GE(std::numeric_limits<uint32_t>::max(), call_position);
189   uint32_t call_position_u32 = static_cast<uint32_t>(call_position);
190   asm_offsets_.write_i32v(call_position_u32 - last_asm_source_position_);
191 
192   DCHECK_GE(std::numeric_limits<uint32_t>::max(), to_number_position);
193   uint32_t to_number_position_u32 = static_cast<uint32_t>(to_number_position);
194   asm_offsets_.write_i32v(to_number_position_u32 - call_position_u32);
195   last_asm_source_position_ = to_number_position_u32;
196 }
197 
SetAsmFunctionStartPosition(size_t function_position)198 void WasmFunctionBuilder::SetAsmFunctionStartPosition(
199     size_t function_position) {
200   DCHECK_EQ(0, asm_func_start_source_position_);
201   DCHECK_GE(std::numeric_limits<uint32_t>::max(), function_position);
202   uint32_t function_position_u32 = static_cast<uint32_t>(function_position);
203   // Must be called before emitting any asm.js source position.
204   DCHECK_EQ(0, asm_offsets_.size());
205   asm_func_start_source_position_ = function_position_u32;
206   last_asm_source_position_ = function_position_u32;
207 }
208 
SetCompilationHint(WasmCompilationHintStrategy strategy,WasmCompilationHintTier baseline,WasmCompilationHintTier top_tier)209 void WasmFunctionBuilder::SetCompilationHint(
210     WasmCompilationHintStrategy strategy, WasmCompilationHintTier baseline,
211     WasmCompilationHintTier top_tier) {
212   uint8_t hint_byte = static_cast<uint8_t>(strategy) |
213                       static_cast<uint8_t>(baseline) << 2 |
214                       static_cast<uint8_t>(top_tier) << 4;
215   DCHECK_NE(hint_byte, kNoCompilationHint);
216   hint_ = hint_byte;
217 }
218 
DeleteCodeAfter(size_t position)219 void WasmFunctionBuilder::DeleteCodeAfter(size_t position) {
220   DCHECK_LE(position, body_.size());
221   body_.Truncate(position);
222 }
223 
WriteSignature(ZoneBuffer * buffer) const224 void WasmFunctionBuilder::WriteSignature(ZoneBuffer* buffer) const {
225   buffer->write_u32v(signature_index_);
226 }
227 
WriteBody(ZoneBuffer * buffer) const228 void WasmFunctionBuilder::WriteBody(ZoneBuffer* buffer) const {
229   size_t locals_size = locals_.Size();
230   buffer->write_size(locals_size + body_.size());
231   buffer->EnsureSpace(locals_size);
232   byte** ptr = buffer->pos_ptr();
233   locals_.Emit(*ptr);
234   (*ptr) += locals_size;  // UGLY: manual bump of position pointer
235   if (body_.size() > 0) {
236     size_t base = buffer->offset();
237     buffer->write(body_.begin(), body_.size());
238     for (DirectCallIndex call : direct_calls_) {
239       buffer->patch_u32v(
240           base + call.offset,
241           call.direct_index +
242               static_cast<uint32_t>(builder_->function_imports_.size()));
243     }
244   }
245 }
246 
WriteAsmWasmOffsetTable(ZoneBuffer * buffer) const247 void WasmFunctionBuilder::WriteAsmWasmOffsetTable(ZoneBuffer* buffer) const {
248   if (asm_func_start_source_position_ == 0 && asm_offsets_.size() == 0) {
249     buffer->write_size(0);
250     return;
251   }
252   size_t locals_enc_size = LEBHelper::sizeof_u32v(locals_.Size());
253   size_t func_start_size =
254       LEBHelper::sizeof_u32v(asm_func_start_source_position_);
255   buffer->write_size(asm_offsets_.size() + locals_enc_size + func_start_size);
256   // Offset of the recorded byte offsets.
257   DCHECK_GE(kMaxUInt32, locals_.Size());
258   buffer->write_u32v(static_cast<uint32_t>(locals_.Size()));
259   // Start position of the function.
260   buffer->write_u32v(asm_func_start_source_position_);
261   buffer->write(asm_offsets_.begin(), asm_offsets_.size());
262 }
263 
WasmModuleBuilder(Zone * zone)264 WasmModuleBuilder::WasmModuleBuilder(Zone* zone)
265     : zone_(zone),
266       types_(zone),
267       function_imports_(zone),
268       global_imports_(zone),
269       exports_(zone),
270       functions_(zone),
271       tables_(zone),
272       data_segments_(zone),
273       element_segments_(zone),
274       globals_(zone),
275       exceptions_(zone),
276       signature_map_(zone),
277       current_recursive_group_start_(-1),
278       recursive_groups_(zone),
279       start_function_index_(-1),
280       min_memory_size_(16),
281       max_memory_size_(0),
282       has_max_memory_size_(false),
283       has_shared_memory_(false) {}
284 
AddFunction(const FunctionSig * sig)285 WasmFunctionBuilder* WasmModuleBuilder::AddFunction(const FunctionSig* sig) {
286   functions_.push_back(zone_->New<WasmFunctionBuilder>(this));
287   // Add the signature if one was provided here.
288   if (sig) functions_.back()->SetSignature(sig);
289   return functions_.back();
290 }
291 
AddFunction(uint32_t sig_index)292 WasmFunctionBuilder* WasmModuleBuilder::AddFunction(uint32_t sig_index) {
293   functions_.push_back(zone_->New<WasmFunctionBuilder>(this));
294   functions_.back()->SetSignature(sig_index);
295   return functions_.back();
296 }
297 
AddDataSegment(const byte * data,uint32_t size,uint32_t dest)298 void WasmModuleBuilder::AddDataSegment(const byte* data, uint32_t size,
299                                        uint32_t dest) {
300   data_segments_.push_back({ZoneVector<byte>(zone()), dest});
301   ZoneVector<byte>& vec = data_segments_.back().data;
302   for (uint32_t i = 0; i < size; i++) {
303     vec.push_back(data[i]);
304   }
305 }
306 
ForceAddSignature(const FunctionSig * sig,uint32_t supertype)307 uint32_t WasmModuleBuilder::ForceAddSignature(const FunctionSig* sig,
308                                               uint32_t supertype) {
309   uint32_t index = static_cast<uint32_t>(types_.size());
310   signature_map_.emplace(*sig, index);
311   types_.emplace_back(sig, supertype);
312   return index;
313 }
314 
AddSignature(const FunctionSig * sig,uint32_t supertype)315 uint32_t WasmModuleBuilder::AddSignature(const FunctionSig* sig,
316                                          uint32_t supertype) {
317   auto sig_entry = signature_map_.find(*sig);
318   if (sig_entry != signature_map_.end()) return sig_entry->second;
319   return ForceAddSignature(sig, supertype);
320 }
321 
AddException(const FunctionSig * type)322 uint32_t WasmModuleBuilder::AddException(const FunctionSig* type) {
323   DCHECK_EQ(0, type->return_count());
324   int type_index = AddSignature(type);
325   uint32_t except_index = static_cast<uint32_t>(exceptions_.size());
326   exceptions_.push_back(type_index);
327   return except_index;
328 }
329 
AddStructType(StructType * type,uint32_t supertype)330 uint32_t WasmModuleBuilder::AddStructType(StructType* type,
331                                           uint32_t supertype) {
332   uint32_t index = static_cast<uint32_t>(types_.size());
333   types_.emplace_back(type, supertype);
334   return index;
335 }
336 
AddArrayType(ArrayType * type,uint32_t supertype)337 uint32_t WasmModuleBuilder::AddArrayType(ArrayType* type, uint32_t supertype) {
338   uint32_t index = static_cast<uint32_t>(types_.size());
339   types_.emplace_back(type, supertype);
340   return index;
341 }
342 
IncreaseTableMinSize(uint32_t table_index,uint32_t count)343 uint32_t WasmModuleBuilder::IncreaseTableMinSize(uint32_t table_index,
344                                                  uint32_t count) {
345   DCHECK_LT(table_index, tables_.size());
346   uint32_t old_min_size = tables_[table_index].min_size;
347   if (count > FLAG_wasm_max_table_size - old_min_size) {
348     return std::numeric_limits<uint32_t>::max();
349   }
350   tables_[table_index].min_size = old_min_size + count;
351   tables_[table_index].max_size =
352       std::max(old_min_size + count, tables_[table_index].max_size);
353   return old_min_size;
354 }
355 
AddTable(ValueType type,uint32_t min_size)356 uint32_t WasmModuleBuilder::AddTable(ValueType type, uint32_t min_size) {
357   tables_.push_back({type, min_size, 0, false, {}});
358   return static_cast<uint32_t>(tables_.size() - 1);
359 }
360 
AddTable(ValueType type,uint32_t min_size,uint32_t max_size)361 uint32_t WasmModuleBuilder::AddTable(ValueType type, uint32_t min_size,
362                                      uint32_t max_size) {
363   tables_.push_back({type, min_size, max_size, true, {}});
364   return static_cast<uint32_t>(tables_.size() - 1);
365 }
366 
AddTable(ValueType type,uint32_t min_size,uint32_t max_size,WasmInitExpr init)367 uint32_t WasmModuleBuilder::AddTable(ValueType type, uint32_t min_size,
368                                      uint32_t max_size, WasmInitExpr init) {
369   tables_.push_back({type, min_size, max_size, true, init});
370   return static_cast<uint32_t>(tables_.size() - 1);
371 }
372 
AddElementSegment(WasmElemSegment segment)373 void WasmModuleBuilder::AddElementSegment(WasmElemSegment segment) {
374   element_segments_.push_back(std::move(segment));
375 }
376 
SetIndirectFunction(uint32_t table_index,uint32_t index_in_table,uint32_t direct_function_index,WasmElemSegment::FunctionIndexingMode indexing_mode)377 void WasmModuleBuilder::SetIndirectFunction(
378     uint32_t table_index, uint32_t index_in_table,
379     uint32_t direct_function_index,
380     WasmElemSegment::FunctionIndexingMode indexing_mode) {
381   WasmElemSegment segment(zone_, kWasmFuncRef, table_index,
382                           WasmInitExpr(static_cast<int>(index_in_table)));
383   segment.indexing_mode = indexing_mode;
384   segment.entries.emplace_back(WasmElemSegment::Entry::kRefFuncEntry,
385                                direct_function_index);
386   AddElementSegment(std::move(segment));
387 }
388 
AddImport(base::Vector<const char> name,FunctionSig * sig,base::Vector<const char> module)389 uint32_t WasmModuleBuilder::AddImport(base::Vector<const char> name,
390                                       FunctionSig* sig,
391                                       base::Vector<const char> module) {
392   DCHECK(adding_imports_allowed_);
393   function_imports_.push_back({module, name, AddSignature(sig)});
394   return static_cast<uint32_t>(function_imports_.size() - 1);
395 }
396 
AddGlobalImport(base::Vector<const char> name,ValueType type,bool mutability,base::Vector<const char> module)397 uint32_t WasmModuleBuilder::AddGlobalImport(base::Vector<const char> name,
398                                             ValueType type, bool mutability,
399                                             base::Vector<const char> module) {
400   global_imports_.push_back({module, name, type.value_type_code(), mutability});
401   return static_cast<uint32_t>(global_imports_.size() - 1);
402 }
403 
MarkStartFunction(WasmFunctionBuilder * function)404 void WasmModuleBuilder::MarkStartFunction(WasmFunctionBuilder* function) {
405   start_function_index_ = function->func_index();
406 }
407 
AddExport(base::Vector<const char> name,ImportExportKindCode kind,uint32_t index)408 void WasmModuleBuilder::AddExport(base::Vector<const char> name,
409                                   ImportExportKindCode kind, uint32_t index) {
410   DCHECK_LE(index, std::numeric_limits<int>::max());
411   exports_.push_back({name, kind, static_cast<int>(index)});
412 }
413 
AddExportedGlobal(ValueType type,bool mutability,WasmInitExpr init,base::Vector<const char> name)414 uint32_t WasmModuleBuilder::AddExportedGlobal(ValueType type, bool mutability,
415                                               WasmInitExpr init,
416                                               base::Vector<const char> name) {
417   uint32_t index = AddGlobal(type, mutability, init);
418   AddExport(name, kExternalGlobal, index);
419   return index;
420 }
421 
ExportImportedFunction(base::Vector<const char> name,int import_index)422 void WasmModuleBuilder::ExportImportedFunction(base::Vector<const char> name,
423                                                int import_index) {
424 #if DEBUG
425   // The size of function_imports_ must not change any more.
426   adding_imports_allowed_ = false;
427 #endif
428   exports_.push_back(
429       {name, kExternalFunction,
430        import_index - static_cast<int>(function_imports_.size())});
431 }
432 
AddGlobal(ValueType type,bool mutability,WasmInitExpr init)433 uint32_t WasmModuleBuilder::AddGlobal(ValueType type, bool mutability,
434                                       WasmInitExpr init) {
435   globals_.push_back({type, mutability, init});
436   return static_cast<uint32_t>(globals_.size() - 1);
437 }
438 
SetMinMemorySize(uint32_t value)439 void WasmModuleBuilder::SetMinMemorySize(uint32_t value) {
440   min_memory_size_ = value;
441 }
442 
SetMaxMemorySize(uint32_t value)443 void WasmModuleBuilder::SetMaxMemorySize(uint32_t value) {
444   has_max_memory_size_ = true;
445   max_memory_size_ = value;
446 }
447 
SetHasSharedMemory()448 void WasmModuleBuilder::SetHasSharedMemory() { has_shared_memory_ = true; }
449 
450 namespace {
WriteInitializerExpressionWithEnd(ZoneBuffer * buffer,const WasmInitExpr & init,ValueType type)451 void WriteInitializerExpressionWithEnd(ZoneBuffer* buffer,
452                                        const WasmInitExpr& init,
453                                        ValueType type) {
454   switch (init.kind()) {
455     case WasmInitExpr::kI32Const:
456       buffer->write_u8(kExprI32Const);
457       buffer->write_i32v(init.immediate().i32_const);
458       break;
459     case WasmInitExpr::kI64Const:
460       buffer->write_u8(kExprI64Const);
461       buffer->write_i64v(init.immediate().i64_const);
462       break;
463     case WasmInitExpr::kF32Const:
464       buffer->write_u8(kExprF32Const);
465       buffer->write_f32(init.immediate().f32_const);
466       break;
467     case WasmInitExpr::kF64Const:
468       buffer->write_u8(kExprF64Const);
469       buffer->write_f64(init.immediate().f64_const);
470       break;
471     case WasmInitExpr::kS128Const:
472       buffer->write_u8(kSimdPrefix);
473       buffer->write_u8(kExprS128Const & 0xFF);
474       buffer->write(init.immediate().s128_const.data(), kSimd128Size);
475       break;
476     case WasmInitExpr::kGlobalGet:
477       buffer->write_u8(kExprGlobalGet);
478       buffer->write_u32v(init.immediate().index);
479       break;
480     case WasmInitExpr::kRefNullConst:
481       buffer->write_u8(kExprRefNull);
482       buffer->write_i32v(HeapType(init.immediate().heap_type).code());
483       break;
484     case WasmInitExpr::kRefFuncConst:
485       buffer->write_u8(kExprRefFunc);
486       buffer->write_u32v(init.immediate().index);
487       break;
488     case WasmInitExpr::kNone: {
489       // No initializer, emit a default value.
490       switch (type.kind()) {
491         case kI32:
492           buffer->write_u8(kExprI32Const);
493           // LEB encoding of 0.
494           buffer->write_u8(0);
495           break;
496         case kI64:
497           buffer->write_u8(kExprI64Const);
498           // LEB encoding of 0.
499           buffer->write_u8(0);
500           break;
501         case kF32:
502           buffer->write_u8(kExprF32Const);
503           buffer->write_f32(0.f);
504           break;
505         case kF64:
506           buffer->write_u8(kExprF64Const);
507           buffer->write_f64(0.);
508           break;
509         case kOptRef:
510           buffer->write_u8(kExprRefNull);
511           buffer->write_i32v(type.heap_type().code());
512           break;
513         case kS128:
514           buffer->write_u8(static_cast<byte>(kSimdPrefix));
515           buffer->write_u8(static_cast<byte>(kExprS128Const & 0xff));
516           for (int i = 0; i < kSimd128Size; i++) buffer->write_u8(0);
517           break;
518         case kI8:
519         case kI16:
520         case kVoid:
521         case kBottom:
522         case kRef:
523         case kRtt:
524           UNREACHABLE();
525       }
526       break;
527     }
528     case WasmInitExpr::kStructNew:
529     case WasmInitExpr::kStructNewWithRtt:
530     case WasmInitExpr::kStructNewDefault:
531     case WasmInitExpr::kStructNewDefaultWithRtt:
532       STATIC_ASSERT((kExprStructNew >> 8) == kGCPrefix);
533       STATIC_ASSERT((kExprStructNewWithRtt >> 8) == kGCPrefix);
534       STATIC_ASSERT((kExprStructNewDefault >> 8) == kGCPrefix);
535       STATIC_ASSERT((kExprStructNewDefaultWithRtt >> 8) == kGCPrefix);
536       for (const WasmInitExpr& operand : *init.operands()) {
537         WriteInitializerExpressionWithEnd(buffer, operand, kWasmBottom);
538       }
539       buffer->write_u8(kGCPrefix);
540       WasmOpcode opcode;
541       switch (init.kind()) {
542         case WasmInitExpr::kStructNewWithRtt:
543           opcode = kExprStructNewWithRtt;
544           break;
545         case WasmInitExpr::kStructNew:
546           opcode = kExprStructNew;
547           break;
548         case WasmInitExpr::kStructNewDefaultWithRtt:
549           opcode = kExprStructNewDefaultWithRtt;
550           break;
551         case WasmInitExpr::kStructNewDefault:
552           opcode = kExprStructNewDefault;
553           break;
554         default:
555           UNREACHABLE();
556       }
557       buffer->write_u8(static_cast<uint8_t>(opcode));
558       buffer->write_u32v(init.immediate().index);
559       break;
560     case WasmInitExpr::kArrayInit:
561     case WasmInitExpr::kArrayInitStatic:
562       STATIC_ASSERT((kExprArrayInit >> 8) == kGCPrefix);
563       STATIC_ASSERT((kExprArrayInitStatic >> 8) == kGCPrefix);
564       for (const WasmInitExpr& operand : *init.operands()) {
565         WriteInitializerExpressionWithEnd(buffer, operand, kWasmBottom);
566       }
567       buffer->write_u8(kGCPrefix);
568       buffer->write_u8(static_cast<uint8_t>(
569           init.kind() == WasmInitExpr::kArrayInit ? kExprArrayInit
570                                                   : kExprArrayInitStatic));
571       buffer->write_u32v(init.immediate().index);
572       buffer->write_u32v(static_cast<uint32_t>(init.operands()->size() - 1));
573       break;
574     case WasmInitExpr::kRttCanon:
575       STATIC_ASSERT((kExprRttCanon >> 8) == kGCPrefix);
576       buffer->write_u8(kGCPrefix);
577       buffer->write_u8(static_cast<uint8_t>(kExprRttCanon));
578       buffer->write_i32v(static_cast<int32_t>(init.immediate().index));
579       break;
580   }
581 }
582 
WriteInitializerExpression(ZoneBuffer * buffer,const WasmInitExpr & init,ValueType type)583 void WriteInitializerExpression(ZoneBuffer* buffer, const WasmInitExpr& init,
584                                 ValueType type) {
585   WriteInitializerExpressionWithEnd(buffer, init, type);
586   buffer->write_u8(kExprEnd);
587 }
588 }  // namespace
589 
WriteTo(ZoneBuffer * buffer) const590 void WasmModuleBuilder::WriteTo(ZoneBuffer* buffer) const {
591   // == Emit magic =============================================================
592   buffer->write_u32(kWasmMagic);
593   buffer->write_u32(kWasmVersion);
594 
595   // == Emit types =============================================================
596   if (types_.size() > 0) {
597     size_t start = EmitSection(kTypeSectionCode, buffer);
598     size_t type_count = types_.size();
599     for (auto pair : recursive_groups_) {
600       // Every rec. group counts as one type entry.
601       type_count -= pair.second - 1;
602     }
603 
604     buffer->write_size(type_count);
605 
606     for (uint32_t i = 0; i < types_.size(); i++) {
607       auto recursive_group = recursive_groups_.find(i);
608 
609       if (recursive_group != recursive_groups_.end()) {
610         buffer->write_u8(kWasmRecursiveTypeGroupCode);
611         buffer->write_u32v(recursive_group->second);
612       }
613 
614       const TypeDefinition& type = types_[i];
615 
616       if (type.supertype != kNoSuperType) {
617         buffer->write_u8(kWasmSubtypeCode);
618         buffer->write_u8(1);  // The supertype count is always 1.
619         buffer->write_u32v(type.supertype);
620       }
621       switch (type.kind) {
622         case TypeDefinition::kFunction: {
623           const FunctionSig* sig = type.function_sig;
624           buffer->write_u8(kWasmFunctionTypeCode);
625           buffer->write_size(sig->parameter_count());
626           for (auto param : sig->parameters()) {
627             WriteValueType(buffer, param);
628           }
629           buffer->write_size(sig->return_count());
630           for (auto ret : sig->returns()) {
631             WriteValueType(buffer, ret);
632           }
633           break;
634         }
635         case TypeDefinition::kStruct: {
636           const StructType* struct_type = type.struct_type;
637           buffer->write_u8(kWasmStructTypeCode);
638           buffer->write_size(struct_type->field_count());
639           for (uint32_t i = 0; i < struct_type->field_count(); i++) {
640             WriteValueType(buffer, struct_type->field(i));
641             buffer->write_u8(struct_type->mutability(i) ? 1 : 0);
642           }
643           break;
644         }
645         case TypeDefinition::kArray: {
646           const ArrayType* array_type = type.array_type;
647           buffer->write_u8(kWasmArrayTypeCode);
648           WriteValueType(buffer, array_type->element_type());
649           buffer->write_u8(array_type->mutability() ? 1 : 0);
650           break;
651         }
652       }
653     }
654     FixupSection(buffer, start);
655   }
656 
657   // == Emit imports ===========================================================
658   if (global_imports_.size() + function_imports_.size() > 0) {
659     size_t start = EmitSection(kImportSectionCode, buffer);
660     buffer->write_size(global_imports_.size() + function_imports_.size());
661     for (auto import : global_imports_) {
662       buffer->write_string(import.module);  // module name
663       buffer->write_string(import.name);    // field name
664       buffer->write_u8(kExternalGlobal);
665       buffer->write_u8(import.type_code);
666       buffer->write_u8(import.mutability ? 1 : 0);
667     }
668     for (auto import : function_imports_) {
669       buffer->write_string(import.module);  // module name
670       buffer->write_string(import.name);    // field name
671       buffer->write_u8(kExternalFunction);
672       buffer->write_u32v(import.sig_index);
673     }
674     FixupSection(buffer, start);
675   }
676 
677   // == Emit function signatures ===============================================
678   uint32_t num_function_names = 0;
679   if (functions_.size() > 0) {
680     size_t start = EmitSection(kFunctionSectionCode, buffer);
681     buffer->write_size(functions_.size());
682     for (auto* function : functions_) {
683       function->WriteSignature(buffer);
684       if (!function->name_.empty()) ++num_function_names;
685     }
686     FixupSection(buffer, start);
687   }
688 
689   // == Emit tables ============================================================
690   if (tables_.size() > 0) {
691     size_t start = EmitSection(kTableSectionCode, buffer);
692     buffer->write_size(tables_.size());
693     for (const WasmTable& table : tables_) {
694       WriteValueType(buffer, table.type);
695       buffer->write_u8(table.has_maximum ? kWithMaximum : kNoMaximum);
696       buffer->write_size(table.min_size);
697       if (table.has_maximum) buffer->write_size(table.max_size);
698       if (table.init.kind() != WasmInitExpr::kNone) {
699         WriteInitializerExpression(buffer, table.init, table.type);
700       }
701     }
702     FixupSection(buffer, start);
703   }
704 
705   // == Emit memory declaration ================================================
706   {
707     size_t start = EmitSection(kMemorySectionCode, buffer);
708     buffer->write_u8(1);  // memory count
709     if (has_shared_memory_) {
710       buffer->write_u8(has_max_memory_size_ ? kSharedWithMaximum
711                                             : kSharedNoMaximum);
712     } else {
713       buffer->write_u8(has_max_memory_size_ ? kWithMaximum : kNoMaximum);
714     }
715     buffer->write_u32v(min_memory_size_);
716     if (has_max_memory_size_) {
717       buffer->write_u32v(max_memory_size_);
718     }
719     FixupSection(buffer, start);
720   }
721 
722   // Emit event section.
723   if (exceptions_.size() > 0) {
724     size_t start = EmitSection(kTagSectionCode, buffer);
725     buffer->write_size(exceptions_.size());
726     for (int type : exceptions_) {
727       buffer->write_u32v(kExceptionAttribute);
728       buffer->write_u32v(type);
729     }
730     FixupSection(buffer, start);
731   }
732 
733   // == Emit globals ===========================================================
734   if (globals_.size() > 0) {
735     size_t start = EmitSection(kGlobalSectionCode, buffer);
736     buffer->write_size(globals_.size());
737 
738     for (const WasmGlobal& global : globals_) {
739       WriteValueType(buffer, global.type);
740       buffer->write_u8(global.mutability ? 1 : 0);
741       WriteInitializerExpression(buffer, global.init, global.type);
742     }
743     FixupSection(buffer, start);
744   }
745 
746   // == emit exports ===========================================================
747   if (exports_.size() > 0) {
748     size_t start = EmitSection(kExportSectionCode, buffer);
749     buffer->write_size(exports_.size());
750     for (auto ex : exports_) {
751       buffer->write_string(ex.name);
752       buffer->write_u8(ex.kind);
753       switch (ex.kind) {
754         case kExternalFunction:
755           buffer->write_size(ex.index + function_imports_.size());
756           break;
757         case kExternalGlobal:
758           buffer->write_size(ex.index + global_imports_.size());
759           break;
760         case kExternalMemory:
761         case kExternalTable:
762           // The WasmModuleBuilder doesn't support importing tables or memories
763           // yet, so there is no index offset to add.
764           buffer->write_size(ex.index);
765           break;
766         case kExternalTag:
767           UNREACHABLE();
768       }
769     }
770     FixupSection(buffer, start);
771   }
772 
773   // == emit start function index ==============================================
774   if (start_function_index_ >= 0) {
775     size_t start = EmitSection(kStartSectionCode, buffer);
776     buffer->write_size(start_function_index_ + function_imports_.size());
777     FixupSection(buffer, start);
778   }
779 
780   // == emit element segments ==================================================
781   if (element_segments_.size() > 0) {
782     size_t start = EmitSection(kElementSectionCode, buffer);
783     buffer->write_size(element_segments_.size());
784     for (const WasmElemSegment& segment : element_segments_) {
785       bool is_active = segment.status == WasmElemSegment::kStatusActive;
786       // We pick the most general syntax, i.e., we always explicitly emit the
787       // table index and the type, and use the expressions-as-elements syntax.
788       // The initial byte is one of 0x05, 0x06, and 0x07.
789       uint8_t kind_mask =
790           segment.status == WasmElemSegment::kStatusActive
791               ? 0b10
792               : segment.status == WasmElemSegment::kStatusDeclarative ? 0b11
793                                                                       : 0b01;
794       uint8_t expressions_as_elements_mask = 0b100;
795       buffer->write_u8(kind_mask | expressions_as_elements_mask);
796       if (is_active) {
797         buffer->write_u32v(segment.table_index);
798         WriteInitializerExpression(buffer, segment.offset, segment.type);
799       }
800       WriteValueType(buffer, segment.type);
801       buffer->write_size(segment.entries.size());
802       for (const WasmElemSegment::Entry entry : segment.entries) {
803         uint8_t opcode =
804             entry.kind == WasmElemSegment::Entry::kGlobalGetEntry
805                 ? kExprGlobalGet
806                 : entry.kind == WasmElemSegment::Entry::kRefFuncEntry
807                       ? kExprRefFunc
808                       : kExprRefNull;
809         bool needs_function_offset =
810             segment.indexing_mode ==
811                 WasmElemSegment::kRelativeToDeclaredFunctions &&
812             entry.kind == WasmElemSegment::Entry::kRefFuncEntry;
813         uint32_t index =
814             entry.index + (needs_function_offset
815                                ? static_cast<uint32_t>(function_imports_.size())
816                                : 0);
817         buffer->write_u8(opcode);
818         buffer->write_u32v(index);
819         buffer->write_u8(kExprEnd);
820       }
821     }
822     FixupSection(buffer, start);
823   }
824 
825   // == emit compilation hints section =========================================
826   bool emit_compilation_hints = false;
827   for (auto* fn : functions_) {
828     if (fn->hint_ != kNoCompilationHint) {
829       emit_compilation_hints = true;
830       break;
831     }
832   }
833   if (emit_compilation_hints) {
834     // Emit the section code.
835     buffer->write_u8(kUnknownSectionCode);
836     // Emit a placeholder for section length.
837     size_t start = buffer->reserve_u32v();
838     // Emit custom section name.
839     buffer->write_string(base::CStrVector("compilationHints"));
840     // Emit hint count.
841     buffer->write_size(functions_.size());
842     // Emit hint bytes.
843     for (auto* fn : functions_) {
844       uint8_t hint_byte =
845           fn->hint_ != kNoCompilationHint ? fn->hint_ : kDefaultCompilationHint;
846       buffer->write_u8(hint_byte);
847     }
848     FixupSection(buffer, start);
849   }
850 
851   // == emit code ==============================================================
852   if (functions_.size() > 0) {
853     size_t start = EmitSection(kCodeSectionCode, buffer);
854     buffer->write_size(functions_.size());
855     for (auto* function : functions_) {
856       function->WriteBody(buffer);
857     }
858     FixupSection(buffer, start);
859   }
860 
861   // == emit data segments =====================================================
862   if (data_segments_.size() > 0) {
863     size_t start = EmitSection(kDataSectionCode, buffer);
864     buffer->write_size(data_segments_.size());
865 
866     for (auto segment : data_segments_) {
867       buffer->write_u8(0);              // linear memory segment
868       buffer->write_u8(kExprI32Const);  // initializer expression for dest
869       buffer->write_u32v(segment.dest);
870       buffer->write_u8(kExprEnd);
871       buffer->write_u32v(static_cast<uint32_t>(segment.data.size()));
872       buffer->write(&segment.data[0], segment.data.size());
873     }
874     FixupSection(buffer, start);
875   }
876 
877   // == Emit names =============================================================
878   if (num_function_names > 0 || !function_imports_.empty()) {
879     // Emit the section code.
880     buffer->write_u8(kUnknownSectionCode);
881     // Emit a placeholder for the length.
882     size_t start = buffer->reserve_u32v();
883     // Emit the section string.
884     buffer->write_string(base::CStrVector("name"));
885     // Emit a subsection for the function names.
886     buffer->write_u8(NameSectionKindCode::kFunctionCode);
887     // Emit a placeholder for the subsection length.
888     size_t functions_start = buffer->reserve_u32v();
889     // Emit the function names.
890     // Imports are always named.
891     uint32_t num_imports = static_cast<uint32_t>(function_imports_.size());
892     buffer->write_size(num_imports + num_function_names);
893     uint32_t function_index = 0;
894     for (; function_index < num_imports; ++function_index) {
895       const WasmFunctionImport* import = &function_imports_[function_index];
896       DCHECK(!import->name.empty());
897       buffer->write_u32v(function_index);
898       buffer->write_string(import->name);
899     }
900     if (num_function_names > 0) {
901       for (auto* function : functions_) {
902         DCHECK_EQ(function_index,
903                   function->func_index() + function_imports_.size());
904         if (!function->name_.empty()) {
905           buffer->write_u32v(function_index);
906           buffer->write_string(function->name_);
907         }
908         ++function_index;
909       }
910     }
911     FixupSection(buffer, functions_start);
912     FixupSection(buffer, start);
913   }
914 }
915 
WriteAsmJsOffsetTable(ZoneBuffer * buffer) const916 void WasmModuleBuilder::WriteAsmJsOffsetTable(ZoneBuffer* buffer) const {
917   // == Emit asm.js offset table ===============================================
918   buffer->write_size(functions_.size());
919   // Emit the offset table per function.
920   for (auto* function : functions_) {
921     function->WriteAsmWasmOffsetTable(buffer);
922   }
923 }
924 }  // namespace wasm
925 }  // namespace internal
926 }  // namespace v8
927