/* Any copyright is dedicated to the Public Domain.
   http://creativecommons.org/publicdomain/zero/1.0/ */

/**
 * Verify that wasm frame(s) can be requested from the client.
 */

var gDebuggee;
var gClient;
var gThreadClient;
var gOldPref;

function run_test()
{
  gOldPref = Services.prefs.getBoolPref("javascript.options.wasm");
  Services.prefs.setBoolPref("javascript.options.wasm", true);

  if (typeof WebAssembly == "undefined") {
    return; // wasm is not enabled for this platform
  }

  initTestDebuggerServer();
  gDebuggee = addTestGlobal("test-stack");
  gClient = new DebuggerClient(DebuggerServer.connectPipe());
  gClient.connect().then(function () {
    attachTestTabAndResume(gClient, "test-stack", function (aResponse, aTabClient, aThreadClient) {
      gThreadClient = aThreadClient;
      gThreadClient.reconfigure({ observeAsmJS: true }, function (aResponse) {
        do_check_eq(!!aResponse.error, false);
        test_pause_frame();
      });
    });
  });
  do_test_pending();
}

function test_pause_frame()
{
  gThreadClient.addOneTimeListener("paused", function (aEvent, aPacket1) {
    gThreadClient.getFrames(0, null, function (aFrameResponse) {
      do_check_eq(aFrameResponse.frames.length, 4);

      let wasmFrame = aFrameResponse.frames[1];
      do_check_eq(wasmFrame.type, "wasmcall");
      do_check_eq(wasmFrame.this, undefined);

      let location = wasmFrame.where;
      do_check_eq(location.line > 0, true);
      do_check_eq(location.column > 0, true);
      do_check_eq(location.source.url.endsWith(" > wasm"), true);

      Services.prefs.setBoolPref("javascript.options.wasm", gOldPref);
      finishClient(gClient);
    });
  });

  gDebuggee.eval("(" + function () {
    // WebAssembly bytecode was generated by running:
    // js -e 'print(wasmTextToBinary("(module(import \"a\" \"b\")(func(export \"c\")call 0))"))'
    var m = new WebAssembly.Module(new Uint8Array([
      0,97,115,109,13,0,0,0,1,132,128,128,128,0,1,96,0,0,2,135,128,128,128,0,1,1,97,1,
      98,0,0,3,130,128,128,128,0,1,0,6,129,128,128,128,0,0,7,133,128,128,128,0,1,1,99,
      0,1,10,138,128,128,128,0,1,132,128,128,128,0,0,16,0,11
    ]));
    var i = new WebAssembly.Instance(m, {a: {b: () => {
      debugger;
    }}});
    i.exports.c();
  } + ")()");
}
