项目作者: Salpadding

项目描述 :
wasmer java binding
高级语言: Rust
项目地址: git://github.com/Salpadding/wasmer-jni.git
创建时间: 2021-07-23T07:44:03Z
项目社区:https://github.com/Salpadding/wasmer-jni

开源协议:

下载


wasmer-jni

wasmer jni binding, support host function, memory read/write

TODO:

  1. support metering
  2. module validation
  3. memory/frame/stack and other resources limitaion
  4. multiple compiler choice, current is single

How to use?

  1. add wasmer_jni.jar to your project

  2. example code:

  1. package com.github.salpadding.wasmer.example;
  2. import com.github.salpadding.wasmer.*;
  3. import java.util.Arrays;
  4. import java.util.Collections;
  5. import java.util.List;
  6. class MemoryPeek implements HostFunction {
  7. @Override
  8. public String getName() {
  9. return "__peek";
  10. }
  11. @Override
  12. public long[] execute(Instance inst, long[] args) {
  13. int off = (int) args[0];
  14. int len = (int) args[1];
  15. byte[] data = inst.getMemory("memory").read(off, len);
  16. for (byte b : data) {
  17. System.out.print(Integer.toString(b & 0xff, 16));
  18. }
  19. System.out.println();
  20. return Instance.EMPTY_LONGS;
  21. }
  22. @Override
  23. public List<ValType> getParams() {
  24. return Arrays.asList(ValType.I32, ValType.I32);
  25. }
  26. @Override
  27. public List<ValType> getRet() {
  28. return Collections.emptyList();
  29. }
  30. }
  31. class EmptyHost implements HostFunction {
  32. private final String name;
  33. public EmptyHost(String name) {
  34. this.name = name;
  35. }
  36. @Override
  37. public String getName() {
  38. return name;
  39. }
  40. @Override
  41. public long[] execute(Instance inst, long[] args) {
  42. System.out.println("empty host function executed");
  43. return EMPTY_LONGS;
  44. }
  45. @Override
  46. public List<ValType> getParams() {
  47. return Collections.singletonList(ValType.I64);
  48. }
  49. @Override
  50. public List<ValType> getRet() {
  51. return Collections.emptyList();
  52. }
  53. }
  54. public class Example {
  55. public static void main(String[] args) {
  56. Natives.initialize(1024);
  57. byte[] bin = TestUtil.readClassPathFile("testdata/wasm.wasm");
  58. Instance ins = Instance.create(bin, Options.empty(), Arrays.asList(new EmptyHost("alert"), new MemoryPeek()));
  59. try {
  60. // for Integer, use Integer.toUnsignedLong
  61. // for Float, use Float.floatToIntBits + Integer.toUnsignedLong
  62. // for Double, use Double.doubleToLongBits
  63. long[] params = new long[2];
  64. params[0] = Long.MAX_VALUE;
  65. params[1] = Integer.toUnsignedLong(Integer.MAX_VALUE);
  66. ins.execute("init", params);
  67. } finally {
  68. ins.close();
  69. }
  70. }
  71. }