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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
use anyhow::Result;
use indexmap::{map::Entry, IndexMap};
use serde::Serialize;
use std::fmt;
use wasmparser::{
ComponentNameSectionReader, NameSectionReader, Parser, Payload::*, ProducersSectionReader,
};
#[derive(Debug, Serialize)]
pub struct Producers(
#[serde(serialize_with = "indexmap::serde_seq::serialize")]
IndexMap<String, IndexMap<String, String>>,
);
impl Producers {
pub fn empty() -> Self {
Producers(IndexMap::new())
}
pub fn from_reader(section: ProducersSectionReader) -> Result<Self> {
let mut fields = IndexMap::new();
for field in section.into_iter() {
let field = field?;
let mut values = IndexMap::new();
for value in field.values.into_iter() {
let value = value?;
values.insert(value.name.to_owned(), value.version.to_owned());
}
fields.insert(field.name.to_owned(), values);
}
Ok(Producers(fields))
}
pub fn add(&mut self, field: &str, name: &str, version: &str) {
match self.0.entry(field.to_string()) {
Entry::Occupied(e) => {
e.into_mut().insert(name.to_owned(), version.to_owned());
}
Entry::Vacant(e) => {
let mut m = IndexMap::new();
m.insert(name.to_owned(), version.to_owned());
e.insert(m);
}
}
}
pub fn get<'a>(&'a self, field: &str) -> Option<ProducersField<'a>> {
self.0.get(&field.to_owned()).map(ProducersField)
}
pub fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a String, ProducersField<'a>)> + 'a {
self.0
.iter()
.map(|(name, field)| (name, ProducersField(field)))
}
fn add_meta(&mut self, add: &AddMetadata) {
for lang in add.language.iter() {
self.add("language", &lang, "");
}
for (name, version) in add.processed_by.iter() {
self.add("processed-by", &name, &version);
}
for (name, version) in add.sdk.iter() {
self.add("sdk", &name, &version);
}
}
pub fn section(&self) -> wasm_encoder::ProducersSection {
let mut section = wasm_encoder::ProducersSection::new();
for (fieldname, fieldvalues) in self.0.iter() {
let mut field = wasm_encoder::ProducersField::new();
for (name, version) in fieldvalues {
field.value(&name, &version);
}
section.field(&fieldname, &field);
}
section
}
fn display(&self, f: &mut fmt::Formatter, indent: usize) -> fmt::Result {
let indent = std::iter::repeat(" ").take(indent).collect::<String>();
for (fieldname, fieldvalues) in self.0.iter() {
writeln!(f, "{indent}{fieldname}:")?;
for (name, version) in fieldvalues {
if version.is_empty() {
writeln!(f, "{indent} {name}")?;
} else {
writeln!(f, "{indent} {name}: {version}")?;
}
}
}
Ok(())
}
}
impl fmt::Display for Producers {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.display(f, 0)
}
}
pub struct ProducersField<'a>(&'a IndexMap<String, String>);
impl<'a> ProducersField<'a> {
pub fn get(&self, name: &str) -> Option<&'a String> {
self.0.get(&name.to_owned())
}
pub fn iter(&self) -> impl Iterator<Item = (&'a String, &'a String)> + 'a {
self.0.iter()
}
}
#[cfg_attr(feature = "clap", derive(clap::Parser))]
#[derive(Debug, Clone, Default)]
pub struct AddMetadata {
#[cfg_attr(feature = "clap", clap(long, value_name = "NAME"))]
pub name: Option<String>,
#[cfg_attr(feature = "clap", clap(long, value_name = "NAME"))]
pub language: Vec<String>,
#[cfg_attr(feature = "clap", clap(long = "processed-by", value_parser = parse_key_value, value_name="NAME=VERSION"))]
pub processed_by: Vec<(String, String)>,
#[cfg_attr(feature="clap", clap(long, value_parser = parse_key_value, value_name="NAME=VERSION"))]
pub sdk: Vec<(String, String)>,
}
#[cfg(feature = "clap")]
fn parse_key_value(s: &str) -> Result<(String, String)> {
s.split_once('=')
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.ok_or_else(|| anyhow::anyhow!("expected KEY=VALUE"))
}
impl AddMetadata {
pub fn to_wasm(&self, input: &[u8]) -> Result<Vec<u8>> {
let mut parser = Parser::new(0).parse_all(&input);
enum Output {
Component(wasm_encoder::Component),
Module(wasm_encoder::Module),
}
impl Output {
fn section(
&mut self,
section: &(impl wasm_encoder::Section + wasm_encoder::ComponentSection),
) {
match self {
Output::Component(c) => {
c.section(section);
}
Output::Module(m) => {
m.section(section);
}
}
}
fn finish(self) -> Vec<u8> {
match self {
Output::Component(c) => c.finish(),
Output::Module(m) => m.finish(),
}
}
}
let mut output = match parser
.next()
.ok_or_else(|| anyhow::anyhow!("at least a version tag on binary"))??
{
Version {
encoding: wasmparser::Encoding::Component,
..
} => Output::Component(wasm_encoder::Component::new()),
Version {
encoding: wasmparser::Encoding::Module,
..
} => Output::Module(wasm_encoder::Module::new()),
_ => {
panic!("first item from parser must be a Version tag")
}
};
let mut producers_found = false;
let mut names_found = false;
let mut depth = 0;
for payload in parser {
let payload = payload?;
match payload {
ModuleSection { .. } | ComponentSection { .. } => depth += 1,
End { .. } => depth -= 1,
_ => {}
}
match payload {
CustomSection(c) if c.name() == "producers" && depth == 0 => {
producers_found = true;
let section = ProducersSectionReader::new(c.data(), c.data_offset())?;
let mut producers = Producers::from_reader(section)?;
producers.add_meta(&self);
output.section(&producers.section());
}
CustomSection(c) if c.name() == "name" && depth == 0 => {
names_found = true;
let section = NameSectionReader::new(c.data(), c.data_offset());
let mut names = ModuleNames::from_reader(section)?;
names.add_meta(&self);
output.section(&names.section()?.as_custom());
}
CustomSection(c) if c.name() == "component-name" && depth == 0 => {
names_found = true;
let section = ComponentNameSectionReader::new(c.data(), c.data_offset());
let mut names = ComponentNames::from_reader(section)?;
names.add_meta(&self);
output.section(&names.section()?.as_custom());
}
_ => {
if let Some((id, range)) = payload.as_section() {
output.section(&wasm_encoder::RawSection {
id,
data: &input[range],
});
}
}
}
}
if !names_found && self.name.is_some() {
match &mut output {
Output::Component(c) => {
let mut names = ComponentNames::empty();
names.add_meta(&self);
c.section(&names.section()?);
}
Output::Module(m) => {
let mut names = ModuleNames::empty();
names.add_meta(&self);
m.section(&names.section()?);
}
}
}
if !producers_found
&& (!self.language.is_empty() || !self.processed_by.is_empty() || !self.sdk.is_empty())
{
let mut producers = Producers::empty();
producers.add_meta(&self);
output.section(&producers.section());
}
Ok(output.finish())
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Metadata {
Component {
name: Option<String>,
producers: Option<Producers>,
children: Vec<Box<Metadata>>,
},
Module {
name: Option<String>,
producers: Option<Producers>,
},
}
impl Metadata {
pub fn from_binary(input: &[u8]) -> Result<Self> {
let mut metadata = Vec::new();
for payload in Parser::new(0).parse_all(&input) {
match payload? {
Version { encoding, .. } => {
if metadata.is_empty() {
match encoding {
wasmparser::Encoding::Module => metadata.push(Metadata::empty_module()),
wasmparser::Encoding::Component => {
metadata.push(Metadata::empty_component())
}
}
}
}
ModuleSection { .. } => metadata.push(Metadata::empty_module()),
ComponentSection { .. } => metadata.push(Metadata::empty_component()),
End { .. } => {
let finished = metadata.pop().expect("non-empty metadata stack");
if metadata.is_empty() {
return Ok(finished);
} else {
metadata.last_mut().unwrap().push_child(finished);
}
}
CustomSection(c) if c.name() == "name" => {
let section = NameSectionReader::new(c.data(), c.data_offset());
let names = ModuleNames::from_reader(section)?;
if let Some(name) = names.get_name() {
metadata
.last_mut()
.expect("non-empty metadata stack")
.set_name(&name);
}
}
CustomSection(c) if c.name() == "component-name" => {
let section = ComponentNameSectionReader::new(c.data(), c.data_offset());
let names = ComponentNames::from_reader(section)?;
if let Some(name) = names.get_name() {
metadata
.last_mut()
.expect("non-empty metadata stack")
.set_name(name);
}
}
CustomSection(c) if c.name() == "producers" => {
let section = ProducersSectionReader::new(c.data(), c.data_offset())?;
let producers = Producers::from_reader(section)?;
metadata
.last_mut()
.expect("non-empty metadata stack")
.set_producers(producers);
}
_ => {}
}
}
Err(anyhow::anyhow!(
"malformed wasm binary, should have reached end"
))
}
fn empty_component() -> Self {
Metadata::Component {
name: None,
producers: None,
children: Vec::new(),
}
}
fn empty_module() -> Self {
Metadata::Module {
name: None,
producers: None,
}
}
fn set_name(&mut self, n: &str) {
match self {
Metadata::Module { name, .. } => *name = Some(n.to_owned()),
Metadata::Component { name, .. } => *name = Some(n.to_owned()),
}
}
fn set_producers(&mut self, p: Producers) {
match self {
Metadata::Module { producers, .. } => *producers = Some(p),
Metadata::Component { producers, .. } => *producers = Some(p),
}
}
fn push_child(&mut self, child: Self) {
match self {
Metadata::Module { .. } => panic!("module shouldnt have children"),
Metadata::Component { children, .. } => children.push(Box::new(child)),
}
}
fn display(&self, f: &mut fmt::Formatter, indent: usize) -> fmt::Result {
let spaces = std::iter::repeat(" ").take(indent).collect::<String>();
match self {
Metadata::Module { name, producers } => {
if let Some(name) = name {
writeln!(f, "{spaces}module {name}:")?;
} else {
writeln!(f, "{spaces}module:")?;
}
if let Some(producers) = producers {
producers.display(f, indent + 4)?;
}
Ok(())
}
Metadata::Component {
name,
producers,
children,
} => {
if let Some(name) = name {
writeln!(f, "{spaces}component {name}:")?;
} else {
writeln!(f, "{spaces}component:")?;
}
if let Some(producers) = producers {
producers.display(f, indent + 4)?;
}
for c in children {
c.display(f, indent + 4)?;
}
Ok(())
}
}
}
}
impl fmt::Display for Metadata {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.display(f, 0)
}
}
pub struct ModuleNames<'a> {
module_name: Option<String>,
names: Vec<wasmparser::Name<'a>>,
}
impl<'a> ModuleNames<'a> {
pub fn empty() -> Self {
ModuleNames {
module_name: None,
names: Vec::new(),
}
}
pub fn from_reader(section: NameSectionReader<'a>) -> Result<ModuleNames<'a>> {
let mut s = Self::empty();
for name in section.into_iter() {
let name = name?;
match name {
wasmparser::Name::Module { name, .. } => s.module_name = Some(name.to_owned()),
_ => s.names.push(name),
}
}
Ok(s)
}
fn add_meta(&mut self, add: &AddMetadata) {
self.module_name = add.name.clone();
}
pub fn set_name(&mut self, name: &str) {
self.module_name = Some(name.to_owned())
}
pub fn get_name(&self) -> Option<&String> {
self.module_name.as_ref()
}
pub fn section(&self) -> Result<wasm_encoder::NameSection> {
let mut section = wasm_encoder::NameSection::new();
if let Some(module_name) = &self.module_name {
section.module(&module_name);
}
for n in self.names.iter() {
match n {
wasmparser::Name::Module { .. } => unreachable!(),
wasmparser::Name::Function(m) => section.functions(&name_map(&m)?),
wasmparser::Name::Local(m) => section.locals(&indirect_name_map(&m)?),
wasmparser::Name::Label(m) => section.labels(&indirect_name_map(&m)?),
wasmparser::Name::Type(m) => section.types(&name_map(&m)?),
wasmparser::Name::Table(m) => section.tables(&name_map(&m)?),
wasmparser::Name::Memory(m) => section.memories(&name_map(&m)?),
wasmparser::Name::Global(m) => section.globals(&name_map(&m)?),
wasmparser::Name::Element(m) => section.elements(&name_map(&m)?),
wasmparser::Name::Data(m) => section.types(&name_map(&m)?),
wasmparser::Name::Unknown { .. } => {} }
}
Ok(section)
}
}
pub struct ComponentNames<'a> {
component_name: Option<String>,
names: Vec<wasmparser::ComponentName<'a>>,
}
impl<'a> ComponentNames<'a> {
pub fn empty() -> Self {
ComponentNames {
component_name: None,
names: Vec::new(),
}
}
pub fn from_reader(section: ComponentNameSectionReader<'a>) -> Result<ComponentNames<'a>> {
let mut s = Self::empty();
for name in section.into_iter() {
let name = name?;
match name {
wasmparser::ComponentName::Component { name, .. } => {
s.component_name = Some(name.to_owned())
}
_ => s.names.push(name),
}
}
Ok(s)
}
fn add_meta(&mut self, add: &AddMetadata) {
self.component_name = add.name.clone();
}
pub fn set_name(&mut self, name: &str) {
self.component_name = Some(name.to_owned())
}
pub fn get_name(&self) -> Option<&String> {
self.component_name.as_ref()
}
pub fn section(&self) -> Result<wasm_encoder::ComponentNameSection> {
let mut section = wasm_encoder::ComponentNameSection::new();
if let Some(component_name) = &self.component_name {
section.component(&component_name);
}
for n in self.names.iter() {
match n {
wasmparser::ComponentName::Component { .. } => unreachable!(),
wasmparser::ComponentName::CoreFuncs(m) => section.core_funcs(&name_map(&m)?),
wasmparser::ComponentName::CoreGlobals(m) => section.core_globals(&name_map(&m)?),
wasmparser::ComponentName::CoreMemories(m) => section.core_memories(&name_map(&m)?),
wasmparser::ComponentName::CoreTables(m) => section.core_tables(&name_map(&m)?),
wasmparser::ComponentName::CoreModules(m) => section.core_modules(&name_map(&m)?),
wasmparser::ComponentName::CoreInstances(m) => {
section.core_instances(&name_map(&m)?)
}
wasmparser::ComponentName::CoreTypes(m) => section.core_types(&name_map(&m)?),
wasmparser::ComponentName::Types(m) => section.types(&name_map(&m)?),
wasmparser::ComponentName::Instances(m) => section.instances(&name_map(&m)?),
wasmparser::ComponentName::Components(m) => section.components(&name_map(&m)?),
wasmparser::ComponentName::Funcs(m) => section.funcs(&name_map(&m)?),
wasmparser::ComponentName::Values(m) => section.values(&name_map(&m)?),
wasmparser::ComponentName::Unknown { .. } => {} }
}
Ok(section)
}
}
fn name_map(map: &wasmparser::NameMap<'_>) -> Result<wasm_encoder::NameMap> {
let mut out = wasm_encoder::NameMap::new();
for m in map.clone().into_iter() {
let m = m?;
out.append(m.index, m.name);
}
Ok(out)
}
fn indirect_name_map(
map: &wasmparser::IndirectNameMap<'_>,
) -> Result<wasm_encoder::IndirectNameMap> {
let mut out = wasm_encoder::IndirectNameMap::new();
for m in map.clone().into_iter() {
let m = m?;
out.append(m.index, &name_map(&m.names)?);
}
Ok(out)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn add_to_empty_module() {
let wat = "(module)";
let module = wat::parse_str(wat).unwrap();
let add = AddMetadata {
name: Some("foo".to_owned()),
language: vec!["bar".to_owned()],
processed_by: vec![("baz".to_owned(), "1.0".to_owned())],
sdk: vec![],
};
let module = add.to_wasm(&module).unwrap();
let metadata = Metadata::from_binary(&module).unwrap();
match metadata {
Metadata::Module { name, producers } => {
assert_eq!(name, Some("foo".to_owned()));
let producers = producers.expect("some producers");
assert_eq!(producers.get("language").unwrap().get("bar").unwrap(), "");
assert_eq!(
producers.get("processed-by").unwrap().get("baz").unwrap(),
"1.0"
);
}
_ => panic!("metadata should be module"),
}
}
#[test]
fn add_to_empty_component() {
let wat = "(component)";
let component = wat::parse_str(wat).unwrap();
let add = AddMetadata {
name: Some("foo".to_owned()),
language: vec!["bar".to_owned()],
processed_by: vec![("baz".to_owned(), "1.0".to_owned())],
sdk: vec![],
};
let component = add.to_wasm(&component).unwrap();
let metadata = Metadata::from_binary(&component).unwrap();
match metadata {
Metadata::Component {
name,
producers,
children,
} => {
assert!(children.is_empty());
assert_eq!(name, Some("foo".to_owned()));
let producers = producers.expect("some producers");
assert_eq!(producers.get("language").unwrap().get("bar").unwrap(), "");
assert_eq!(
producers.get("processed-by").unwrap().get("baz").unwrap(),
"1.0"
);
}
_ => panic!("metadata should be component"),
}
}
#[test]
fn add_to_nested_component() {
let wat = "(module)";
let module = wat::parse_str(wat).unwrap();
let add = AddMetadata {
name: Some("foo".to_owned()),
language: vec!["bar".to_owned()],
processed_by: vec![("baz".to_owned(), "1.0".to_owned())],
sdk: vec![],
};
let module = add.to_wasm(&module).unwrap();
let mut component = wasm_encoder::Component::new();
component.section(&wasm_encoder::RawSection {
id: wasm_encoder::ComponentSectionId::CoreModule.into(),
data: &module,
});
let component = component.finish();
let add = AddMetadata {
name: Some("gussie".to_owned()),
sdk: vec![("willa".to_owned(), "sparky".to_owned())],
..Default::default()
};
let component = add.to_wasm(&component).unwrap();
let metadata = Metadata::from_binary(&component).unwrap();
match metadata {
Metadata::Component {
name,
producers,
children,
} => {
assert_eq!(name, Some("gussie".to_owned()));
let producers = producers.as_ref().expect("some producers");
assert_eq!(
producers.get("sdk").unwrap().get("willa").unwrap(),
&"sparky".to_owned()
);
assert_eq!(children.len(), 1);
let child = children.get(0).unwrap();
match &**child {
Metadata::Module { name, producers } => {
assert_eq!(name, &Some("foo".to_owned()));
let producers = producers.as_ref().expect("some producers");
assert_eq!(producers.get("language").unwrap().get("bar").unwrap(), "");
assert_eq!(
producers.get("processed-by").unwrap().get("baz").unwrap(),
"1.0"
);
}
_ => panic!("child is a module"),
}
}
_ => panic!("root should be component"),
}
}
}