Compare commits

...
21 Commits
Author SHA1 Message Date
Rodrigo Kumpera 1efe2d0402 Better debug spew 2018-11-05 17:00:25 -05:00
Rodrigo Kumpera a6c04a0958 [wasm] Fix C++ 2018-11-05 16:31:25 -05:00
Rodrigo Kumpera 6638211294 DO NOT MERGE. Disable other tests that not the debuggers. 2018-11-05 15:16:41 -05:00
Rodrigo Kumpera c32366e7bc skeleton for async tests. 2018-11-05 14:52:58 -05:00
Rodrigo Kumpera cacac3a75a handle captured variables 2018-11-02 14:37:20 -04:00
Rodrigo Kumpera d4e4f14c15 [wasm] Handle lookup of nested types. 2018-11-01 18:30:48 -04:00
Rodrigo Kumpera 60486a4438 [wasm] Support properties. 2018-10-31 18:08:17 -04:00
Rodrigo Kumpera ee58c0507e [wasm] Add basic support for properties, base & private fields. 2018-10-30 14:27:18 -04:00
Rodrigo Kumpera 7131941578 handle properties. 2018-10-26 16:41:11 -04:00
Rodrigo Kumpera fb5abca543 Added object inspection, somewhat 2018-10-26 14:04:38 -04:00
Rodrigo Kumpera c06b6901d5 [wasm] Fix debugger sample. 2018-10-24 16:00:26 -04:00
Rodrigo Kumpera 05a8cfa693 [wasm] Add stepping tests. 2018-10-24 15:53:52 -04:00
Rodrigo Kumpera d43c2aae50 [wasm] Add test for local introspection. 2018-10-24 12:34:45 -04:00
Rodrigo Kumpera f4ffbfcce4 [wasm] add linux probing. 2018-10-23 14:00:16 -04:00
Rodrigo Kumpera 37a0cf107c [wasm] Add /Debug option to ProxyDriver to starta chrome debugging session. 2018-10-23 13:48:47 -04:00
Rodrigo Kumpera d246888987 [wasm] Add breakpoint hit test. 2018-10-22 16:53:39 -04:00
Rodrigo Kumpera e523644c8d [wasm] Add tests for setting breakpoints. 2018-10-22 15:47:24 -04:00
Rodrigo Kumpera 1a0d47c1d8 [wasm] Update CI to run debugger tests. 2018-10-22 14:34:58 -04:00
Rodrigo Kumpera de15e913ee [wasm] Pass --debug to packager.exe invocations and add test-debugger target. 2018-10-22 14:34:44 -04:00
Rodrigo Kumpera cbef721c31 [wasm] Change default CopyType mode to IfNewer. Old default was to fail if existing. 2018-10-22 14:34:17 -04:00
Rodrigo Kumpera f13a95a867 [wasm] Add test suite. 2018-10-22 12:33:09 -04:00
28 changed files with 2095 additions and 160 deletions

No files matched your search

+254 -49
View File
@@ -3,6 +3,7 @@
#include <mono/metadata/mono-debug.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/metadata.h>
#include <mono/metadata/mono-hash.h>
#include <mono/metadata/seq-points-data.h>
#include <mono/mini/aot-runtime.h>
#include <mono/mini/seq-points.h>
@@ -30,6 +31,8 @@ EMSCRIPTEN_KEEPALIVE void mono_wasm_enum_frames (void);
EMSCRIPTEN_KEEPALIVE void mono_wasm_get_var_info (int scope, int pos);
EMSCRIPTEN_KEEPALIVE void mono_wasm_clear_all_breakpoints (void);
EMSCRIPTEN_KEEPALIVE void mono_wasm_setup_single_step (int kind);
EMSCRIPTEN_KEEPALIVE void mono_wasm_get_obj_info (int objid, int requested_depth);
EMSCRIPTEN_KEEPALIVE void mono_wasm_get_prop_value (int object_id, int requested_depth, const char *prop_name);
//JS functions imported that we use
extern void mono_wasm_add_frame (int il_offset, int method_token, const char *assembly_name);
@@ -40,6 +43,10 @@ extern void mono_wasm_add_long_var (gint64);
extern void mono_wasm_add_float_var (float);
extern void mono_wasm_add_double_var (double);
extern void mono_wasm_add_string_var (const char*);
extern void mono_wasm_begin_object (const char*, int);
extern void mono_wasm_end_object (void);
extern void mono_wasm_set_last_var_name (const char*);
extern void mono_wasm_set_object_fqn (const char*);
G_END_DECLS
@@ -321,6 +328,35 @@ mono_wasm_debugger_init (void)
mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
}
//TODO respect release group requests
static MonoGHashTable *obj_to_objref;
static MonoGHashTable *objref_to_obj;
static int obj_id;
static int
get_object_id (MonoObject *obj)
{
if (!obj_to_objref) {
obj_to_objref = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Object Table");
objref_to_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Reverse Object Table");
}
void *res = mono_g_hash_table_lookup (obj_to_objref, obj);
if (res)
return GPOINTER_TO_INT (res);
int id = ++obj_id;
mono_g_hash_table_insert (obj_to_objref, obj, GINT_TO_POINTER (id));
mono_g_hash_table_insert (objref_to_obj, GINT_TO_POINTER (id), obj);
return id;
}
static MonoObject*
get_object_from_id (int object_id)
{
return (MonoObject*)mono_g_hash_table_lookup (objref_to_obj, GINT_TO_POINTER (object_id));
}
MONO_API void
mono_wasm_enable_debugging (void)
{
@@ -558,6 +594,101 @@ typedef struct {
int variable;
} FrameDescData;
static void
describe_address (void *addr, MonoType *type, MonoError *error)
{
error_init (error);
DEBUG_PRINTF (2, "adding val %p type [%p] %s\n", addr, type, mono_type_full_name (type));
retry:
switch (type->type) {
case MONO_TYPE_BOOLEAN:
mono_wasm_add_bool_var (*(gint8*)addr);
break;
case MONO_TYPE_I1:
case MONO_TYPE_U1:
mono_wasm_add_int_var (*(gint8*)addr);
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
mono_wasm_add_int_var (*(gint16*)addr);
break;
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I:
case MONO_TYPE_U:
mono_wasm_add_int_var (*(gint32*)addr);
break;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
mono_wasm_add_long_var (*(gint32*)addr);
break;
case MONO_TYPE_R4:
mono_wasm_add_float_var (*(float*)addr);
break;
case MONO_TYPE_R8:
mono_wasm_add_float_var (*(double*)addr);
break;
//TODO
// case MONO_TYPE_ARRAY:
// case MONO_TYPE_SZARRAY:
// case MONO_TYPE_VALUETYPE:
case MONO_TYPE_GENERICINST:
if (m_class_is_valuetype (mono_class_from_mono_type_internal (type))) {
char *type_name = mono_type_full_name (type);
char *msg = g_strdup_printf("Can't handle type %s [%p, 0x%x]", type_name, type, type->type);
mono_wasm_add_string_var (msg);
g_free (msg);
g_free (type_name);
break;
}
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_CLASS: {
MonoObject *obj = *(MonoObject**)addr;
if (!obj) {
mono_wasm_add_string_var (NULL);
break;
}
MonoClass *klass = mono_object_class (obj);
if (klass == mono_defaults.string_class) {
char *str = mono_string_to_utf8_checked ((MonoString*)obj, error);
mono_error_assert_ok (error); /* FIXME report error */
mono_wasm_add_string_var (str);
g_free (str);
break;
}
if (m_class_is_valuetype (klass)) {
type = m_class_get_byval_arg (klass);
addr = mono_object_unbox (obj);
goto retry;
}
char *type_name = mono_type_get_full_name (klass);
int object_id = get_object_id (obj);
printf ("WUT OBJ %p %d %s is vt %d\n", obj, object_id, type_name, m_class_is_valuetype (klass));
mono_wasm_begin_object (type_name, object_id);
//XXX the preview node is optional and marked as experimental
mono_wasm_end_object ();
g_free (type_name);
break;
}
default: {
char *type_name = mono_type_full_name (type);
char *msg = g_strdup_printf("Can't handle type %s [%p, 0x%x]", type_name, type, type->type);
mono_wasm_add_string_var (msg);
g_free (msg);
g_free (type_name);
}
}
}
static gboolean
describe_variable (MonoStackFrameInfo *info, MonoContext *ctx, gpointer ud)
{
@@ -596,60 +727,14 @@ describe_variable (MonoStackFrameInfo *info, MonoContext *ctx, gpointer ud)
addr = mini_get_interp_callbacks ()->frame_get_local (frame, pos);
}
DEBUG_PRINTF (2, "adding val %p type [%p] %s\n", addr, type, mono_type_full_name (type));
describe_address (addr, type, error);
mono_error_assert_ok (error);
switch (type->type) {
case MONO_TYPE_BOOLEAN:
mono_wasm_add_bool_var (*(gint8*)addr);
break;
case MONO_TYPE_I1:
case MONO_TYPE_U1:
mono_wasm_add_int_var (*(gint8*)addr);
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
mono_wasm_add_int_var (*(gint16*)addr);
break;
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I:
case MONO_TYPE_U:
mono_wasm_add_int_var (*(gint32*)addr);
break;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
mono_wasm_add_long_var (*(gint32*)addr);
break;
case MONO_TYPE_R4:
mono_wasm_add_float_var (*(float*)addr);
break;
case MONO_TYPE_R8:
mono_wasm_add_float_var (*(double*)addr);
break;
case MONO_TYPE_STRING: {
MonoString *str_obj = *(MonoString **)addr;
if (!str_obj)
mono_wasm_add_string_var (NULL);
char *str = mono_string_to_utf8_checked (str_obj, error);
mono_error_assert_ok (error); /* FIXME report error */
mono_wasm_add_string_var (str);
g_free (str);
break;
}
default: {
char *type_name = mono_type_full_name (type);
char *msg = g_strdup_printf("can't handle type %s [%p, %x]", type_name, type, type->type);
mono_wasm_add_string_var (msg);
g_free (msg);
g_free (type_name);
}
}
if (header)
mono_metadata_free_mh (header);
return TRUE;
}
//FIXME this doesn't support getting the return value pseudo-var
@@ -666,7 +751,127 @@ mono_wasm_get_var_info (int scope, int pos)
mono_walk_stack_with_ctx (describe_variable, NULL, MONO_UNWIND_NONE, &data);
}
static void
describe_object (MonoObject *obj, MonoClass *klass, MonoError *error)
{
error_init (error);
int count = mono_class_get_field_count (klass);
MonoClassField *fields = m_class_get_fields (klass);
char *fqn;
if (mono_class_is_ginst (klass)) {
MonoClass *gtd = mono_class_get_generic_type_definition (klass);
fqn = mono_type_get_name_full (m_class_get_byval_arg (gtd), MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
} else {
fqn = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
}
mono_wasm_set_object_fqn (fqn);
g_free (fqn);
for (int i = 0; i < count; ++i) {
MonoClassField *f = &fields [i];
MonoType *field_type = mono_field_get_type_checked (f, error);
mono_error_assert_ok (error);
if ((f->offset <= 0) || mono_field_is_deleted (f) || (field_type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
printf ("field %p offset %d\n", f, f->offset);
describe_address ((char*)obj + f->offset, field_type, error);
mono_error_assert_ok (error);
mono_wasm_set_last_var_name (f->name);
}
}
EMSCRIPTEN_KEEPALIVE void
mono_wasm_get_obj_info (int object_id, int requested_depth)
{
ERROR_DECL (error);
DEBUG_PRINTF (2, "getting info for objid %d at depth %d\n", object_id, requested_depth);
MonoObject *object = get_object_from_id (object_id);
MonoClass *klass = mono_object_class (object);
for (int i = 0; klass && i < requested_depth; ++i)
klass = m_class_get_parent (klass);
if (!klass) {
printf ("INVALID DEPTH %d\n", requested_depth);
mono_wasm_set_object_fqn ("Invalid depth request");
return;
}
printf ("GET INFO, ID %d PTR %p\n", object_id, object);
describe_object (object, klass, error);
mono_error_assert_ok (error);
}
static gboolean
is_obj_encoded_as_value (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_CHAR:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_STRING:
return TRUE;
}
return FALSE;
}
EMSCRIPTEN_KEEPALIVE void
mono_wasm_get_prop_value (int object_id, int requested_depth, const char *prop_name)
{
ERROR_DECL (error);
DEBUG_PRINTF (2, "getting property '%s' for objid %d at depth %d\n", prop_name, object_id, requested_depth);
MonoObject *object = get_object_from_id (object_id);
MonoClass *klass = mono_object_class (object);
for (int i = 0; klass && i < requested_depth; ++i)
klass = m_class_get_parent (klass);
if (!klass) {
printf ("INVALID DEPTH %d\n", requested_depth);
mono_wasm_add_string_var ("Invalid depth request");
return;
}
printf ("GET INFO, ID %d PTR %p\n", object_id, object);
MonoProperty *prop = mono_class_get_property_from_name (klass, prop_name);
if (!prop) {
printf ("INVALID PROP NAME %s\n", prop_name);
mono_wasm_add_string_var ("Invalid property name");
return;
}
MonoObject *res = mono_property_get_value_checked (prop, object, NULL, error);
mono_error_assert_ok (error);
MonoClass *prop_klass = res ? mono_object_class (res) : mono_defaults.string_class;
if (m_class_is_valuetype (prop_klass)) {
describe_address (mono_object_unbox (res), m_class_get_byval_arg (prop_klass), error);
mono_error_assert_ok (error);
} else {
describe_address ((void*)&res, m_class_get_byval_arg (prop_klass), error);
mono_error_assert_ok (error);
}
}
// Functions required by debugger-state-machine.
gsize
mono_debugger_tls_thread_id (DebuggerTlsData *debuggerTlsData)
+12 -11
View File
@@ -197,21 +197,22 @@ if [[ ${CI_TAGS} == *'webassembly'* ]] || [[ ${CI_TAGS} == *'wasm'* ]];
if [[ ${CI_TAGS} != *'no-tests'* ]]; then
${TESTCMD} --label=wasm-build --timeout=60m --fatal make -j ${CI_CPU_COUNT} -C sdks/wasm build
${TESTCMD} --label=ch-mini-test --timeout=60m make -C sdks/wasm run-ch-mini
${TESTCMD} --label=v8-mini-test --timeout=60m make -C sdks/wasm run-v8-mini
${TESTCMD} --label=sm-mini-test --timeout=60m make -C sdks/wasm run-sm-mini
${TESTCMD} --label=jsc-mini-test --timeout=60m make -C sdks/wasm run-jsc-mini
# ${TESTCMD} --label=ch-mini-test --timeout=60m make -C sdks/wasm run-ch-mini
# ${TESTCMD} --label=v8-mini-test --timeout=60m make -C sdks/wasm run-v8-mini
# ${TESTCMD} --label=sm-mini-test --timeout=60m make -C sdks/wasm run-sm-mini
# ${TESTCMD} --label=jsc-mini-test --timeout=60m make -C sdks/wasm run-jsc-mini
#The following tests are not passing yet, so enabling them would make us perma-red
#${TESTCMD} --label=mini-corlib --timeout=60m make -C sdks/wasm run-all-corlib
#${TESTCMD} --label=mini-system --timeout=60m make -C sdks/wasm run-all-system
# Chakra crashes with System.Core. See https://github.com/mono/mono/issues/8345
${TESTCMD} --label=ch-system-core --timeout=60m make -C sdks/wasm run-ch-system-core
${TESTCMD} --label=v8-system-core --timeout=60m make -C sdks/wasm run-v8-system-core
${TESTCMD} --label=sm-system-core --timeout=60m make -C sdks/wasm run-sm-system-core
${TESTCMD} --label=jsc-system-core --timeout=60m make -C sdks/wasm run-jsc-system-core
${TESTCMD} --label=aot-mini --timeout=60m make -j ${CI_CPU_COUNT} -C sdks/wasm run-aot-mini
${TESTCMD} --label=build-aot-all --timeout=60m make -j ${CI_CPU_COUNT} -C sdks/wasm build-aot-all
for suite in ${aot_test_suites}; do ${TESTCMD} --label=run-aot-${suite} --timeout=10m make -C sdks/wasm run-aot-${suite}; done
# ${TESTCMD} --label=ch-system-core --timeout=60m make -C sdks/wasm run-ch-system-core
# ${TESTCMD} --label=v8-system-core --timeout=60m make -C sdks/wasm run-v8-system-core
# ${TESTCMD} --label=sm-system-core --timeout=60m make -C sdks/wasm run-sm-system-core
# ${TESTCMD} --label=jsc-system-core --timeout=60m make -C sdks/wasm run-jsc-system-core
${TESTCMD} --label=debugger --timeout=60m make -C sdks/wasm test-debugger
# ${TESTCMD} --label=aot-mini --timeout=60m make -j ${CI_CPU_COUNT} -C sdks/wasm run-aot-mini
# ${TESTCMD} --label=build-aot-all --timeout=60m make -j ${CI_CPU_COUNT} -C sdks/wasm build-aot-all
# for suite in ${aot_test_suites}; do ${TESTCMD} --label=run-aot-${suite} --timeout=10m make -C sdks/wasm run-aot-${suite}; done
#${TESTCMD} --label=check-aot --timeout=60m make -C sdks/wasm check-aot
${TESTCMD} --label=package --timeout=60m make -C sdks/wasm package
fi
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProxyDriver\ProxyDriver.csproj" />
<ProjectReference Include="..\Mono.WebAssembly.DebuggerProxy\Mono.WebAssembly.DebuggerProxy.csproj" />
</ItemGroup>
</Project>
+128
View File
@@ -0,0 +1,128 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Net.WebSockets;
using System.Threading;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Mono.WebAssembly;
using Newtonsoft.Json.Linq;
using Xunit;
namespace DebuggerTests
{
class Inspector
{
// InspectorClient client;
Dictionary<string, TaskCompletionSource<JObject>> notifications = new Dictionary<string, TaskCompletionSource<JObject>> ();
Dictionary<string, Func<JObject, CancellationToken, Task>> eventListeners = new Dictionary<string, Func<JObject, CancellationToken, Task>> ();
public const string PAUSE = "pause";
public const string READY = "ready";
public Task<JObject> WaitFor(string what) {
if (notifications.ContainsKey (what))
throw new Exception ($"Invalid internal state, waiting for {what} while another wait is already setup");
var n = new TaskCompletionSource<JObject> ();
notifications [what] = n;
return n.Task;
}
void NotifyOf (string what, JObject args) {
if (!notifications.ContainsKey (what))
throw new Exception ($"Invalid internal state, notifying of {what}, but nobody waiting");
notifications [what].SetResult (args);
notifications.Remove (what);
}
public void On(string evtName, Func<JObject, CancellationToken, Task> cb) {
eventListeners[evtName] = cb;
}
async Task OnMessage(string method, JObject args, CancellationToken token)
{
switch (method) {
case "Debugger.paused":
NotifyOf (PAUSE, args);
break;
case "Mono.runtimeReady":
NotifyOf (READY, args);
break;
}
if (eventListeners.ContainsKey (method))
await eventListeners[method](args, token);
}
public async Task Ready (Func<InspectorClient, CancellationToken, Task> cb = null) {
using (var cts = new CancellationTokenSource ()) {
cts.CancelAfter (10 * 1000); //tests have 10 seconds to complete!
var uri = new Uri ("ws://localhost:9300/launch-chrome-and-connect");
using (var client = new InspectorClient ()) {
await client.Connect (uri, OnMessage, async token => {
Task[] init_cmds = new Task [] {
client.SendCommand ("Profiler.enable", null, token),
client.SendCommand ("Runtime.enable", null, token),
client.SendCommand ("Debugger.enable", null, token),
client.SendCommand ("Runtime.runIfWaitingForDebugger", null, token),
WaitFor (READY),
};
// await Task.WhenAll (init_cmds);
Console.WriteLine ("waiting for the runtime to be ready");
await init_cmds [4];
Console.WriteLine ("runtime ready, TEST TIME");
if (cb != null)
await cb (client, token);
}, cts.Token);
}
}
}
}
public class DebuggerTestBase {
static string FindTestPath () {
//FIXME how would I locate it otherwise?
var test_path = Environment.GetEnvironmentVariable ("TEST_SUITE_PATH");
//Lets try to guest
if (test_path != null && Directory.Exists (test_path))
return test_path;
var cwd = Environment.CurrentDirectory;
Console.WriteLine ("guessing from {0}", cwd);
//tests run from DebuggerTestSuite/bin/Debug/netcoreapp2.1
var new_path = Path.Combine (cwd, "../../../../bin/debugger-test-suite");
if (File.Exists (Path.Combine (new_path, "debugger-driver.html")))
return new_path;
throw new Exception ("Missing TEST_SUITE_PATH env var and could not guess path from CWD");
}
static string[] PROBE_LIST = new[] {
"/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
};
static string chrome_path;
static String FindChromePath ()
{
if (chrome_path != null)
return chrome_path;
foreach (var s in PROBE_LIST){
if (File.Exists (s)) {
chrome_path = s;
return s;
}
}
throw new Exception ("Could not find an installed Chrome to use");
}
public DebuggerTestBase () {
WsProxy.TestHarnessProxy.Start (FindChromePath (), FindTestPath (), "debugger-driver.html");
}
}
}
+325
View File
@@ -0,0 +1,325 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Net.WebSockets;
using System.Threading;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Xunit;
using Mono.WebAssembly;
namespace DebuggerTests
{
public class SourceList : DebuggerTestBase {
Dictionary<string, string> SubscribeToScripts (Inspector insp) {
Dictionary<string, string> scripts = new Dictionary<string, string> ();
insp.On("Debugger.scriptParsed", async (args, c) => {
var script_id = args? ["scriptId"]?.Value<string> ();
var url = args["url"]?.Value<string> ();
if (script_id.StartsWith("dotnet://"))
scripts [script_id] = url;
await Task.FromResult (0);
});
return scripts;
}
void CheckLocation (string script_loc, int line, int column, Dictionary<string, string> scripts, JToken location)
{
Assert.Equal (script_loc, scripts [location ["scriptId"].Value<string> ()]);
Assert.Equal (line, location ["lineNumber"].Value<int> ());
Assert.Equal (column, location ["columnNumber"].Value<int> ());
}
[Fact]
public async Task CheckThatAllSourcesAreSent () {
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
//all sources are sent before runtime ready is sent, nothing to check
await insp.Ready ();
Assert.Equal (3, scripts.Count);
Assert.True (scripts.ContainsValue ("dotnet://debugger-test.dll/debugger-test.cs"));
Assert.True (scripts.ContainsValue ("dotnet://debugger-test.dll/debugger-test2.cs"));
Assert.True (scripts.ContainsValue ("dotnet://Simple.Dependency.dll/dependency.cs"));
}
[Fact]
public async Task CreateGoodBreakpoint () {
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await insp.Ready (async (cli, token) => {
var bp1_req = JObject.FromObject(new {
lineNumber = 5,
columnNumber = 2,
url = "dotnet://debugger-test.dll/debugger-test.cs",
});
var bp1_res = await cli.SendCommand ("Debugger.setBreakpointByUrl", bp1_req, token);
Assert.True (bp1_res.IsOk);
Assert.Equal ("dotnet:0", bp1_res.Value ["breakpointId"]);
Assert.Equal (1, bp1_res.Value ["locations"]?.Value<JArray> ()?.Count);
var loc = bp1_res.Value ["locations"]?.Value<JArray> ()[0];
Assert.NotNull (loc ["scriptId"]);
Assert.Equal ("dotnet://debugger-test.dll/debugger-test.cs", scripts [loc["scriptId"]?.Value<string> ()]);
Assert.Equal (5, loc ["lineNumber"]);
Assert.Equal (2, loc ["columnNumber"]);
});
}
[Fact]
public async Task CreateBadBreakpoint () {
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await insp.Ready (async (cli, token) => {
var bp1_req = JObject.FromObject(new {
lineNumber = 5,
columnNumber = 2,
url = "dotnet://debugger-test.dll/this-file-doesnt-exist.cs",
});
var bp1_res = await cli.SendCommand ("Debugger.setBreakpointByUrl", bp1_req, token);
Assert.False (bp1_res.IsOk);
Assert.True (bp1_res.IsErr);
Assert.Equal ((int)MonoErrorCodes.BpNotFound, bp1_res.Error ["code"]?.Value<int> ());
});
}
[Fact]
public async Task CreateGoodBreakpointAndHit () {
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await insp.Ready (async (cli, token) => {
var bp1_req = JObject.FromObject(new {
lineNumber = 5,
columnNumber = 2,
url = "dotnet://debugger-test.dll/debugger-test.cs",
});
var bp1_res = await cli.SendCommand ("Debugger.setBreakpointByUrl", bp1_req, token);
Assert.True (bp1_res.IsOk);
var eval_req = JObject.FromObject(new {
expression = "window.setTimeout(function() { invoke_add(); }, 1);",
});
var eval_res = await cli.SendCommand ("Runtime.evaluate", eval_req, token);
Assert.True (eval_res.IsOk);
var pause_location = await insp.WaitFor(Inspector.PAUSE);
Assert.Equal ("other", pause_location ["reason"]?.Value<string> ());
Assert.Equal ("dotnet:0", pause_location ["hitBreakpoints"]?[0]?.Value<string> ());
var top_frame = pause_location ["callFrames"][0];
Assert.Equal ("IntAdd", top_frame ["functionName"].Value<string>());
Assert.Equal ("dotnet://debugger-test.dll/debugger-test.cs", top_frame ["url"].Value<string> ());
CheckLocation ("dotnet://debugger-test.dll/debugger-test.cs", 4, 41, scripts, top_frame["functionLocation"]);
CheckLocation ("dotnet://debugger-test.dll/debugger-test.cs", 5, 2, scripts, top_frame["location"]);
//now check the scope
var scope = top_frame ["scopeChain"][0];
Assert.Equal ("local", scope ["type"]);
Assert.Equal ("IntAdd", scope ["name"]);
Assert.Equal ("object", scope ["object"]["type"]);
Assert.Equal ("dotnet:scope:0", scope ["object"]["objectId"]);
CheckLocation ("dotnet://debugger-test.dll/debugger-test.cs", 4, 41, scripts, scope["startLocation"]);
CheckLocation ("dotnet://debugger-test.dll/debugger-test.cs", 10, 1, scripts, scope["endLocation"]);
});
}
void CheckNumber (JToken locals, string name, int value) {
foreach (var l in locals) {
if (name != l["name"]?.Value<string> ())
continue;
var val = l["value"];
Assert.Equal ("number", val ["type"]?.Value<string> ());
Assert.Equal (value, val["value"]?.Value <int> ());
return;
}
Assert.True(false, $"Could not find variable '{name}'");
}
[Fact]
public async Task InspectLocalsAtBreakpointSite () {
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await insp.Ready (async (cli, token) => {
var bp1_req = JObject.FromObject(new {
lineNumber = 5,
columnNumber = 2,
url = "dotnet://debugger-test.dll/debugger-test.cs",
});
var bp1_res = await cli.SendCommand ("Debugger.setBreakpointByUrl", bp1_req, token);
Assert.True (bp1_res.IsOk);
var eval_req = JObject.FromObject(new {
expression = "window.setTimeout(function() { invoke_add(); }, 1);",
});
var eval_res = await cli.SendCommand ("Runtime.evaluate", eval_req, token);
Assert.True (eval_res.IsOk);
var pause_location = await insp.WaitFor(Inspector.PAUSE);
//make sure we're on the right bp
Assert.Equal ("dotnet:0", pause_location ["hitBreakpoints"]?[0]?.Value<string> ());
var top_frame = pause_location ["callFrames"][0];
var scope = top_frame ["scopeChain"][0];
Assert.Equal ("dotnet:scope:0", scope ["object"]["objectId"]);
//ok, what's on that scope?
var get_prop_req = JObject.FromObject(new {
objectId = "dotnet:scope:0",
});
var frame_props = await cli.SendCommand ("Runtime.getProperties", get_prop_req, token);
Assert.True (frame_props.IsOk);
var locals = frame_props.Value ["result"];
CheckNumber (locals, "a", 10);
CheckNumber (locals, "b", 20);
CheckNumber (locals, "c", 0);
CheckNumber (locals, "d", 0);
CheckNumber (locals, "e", 0);
});
}
[Fact]
public async Task TrivalStepping () {
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await insp.Ready (async (cli, token) => {
var bp1_req = JObject.FromObject(new {
lineNumber = 5,
columnNumber = 2,
url = "dotnet://debugger-test.dll/debugger-test.cs",
});
var bp1_res = await cli.SendCommand ("Debugger.setBreakpointByUrl", bp1_req, token);
Assert.True (bp1_res.IsOk);
var eval_req = JObject.FromObject(new {
expression = "window.setTimeout(function() { invoke_add(); }, 1);",
});
var eval_res = await cli.SendCommand ("Runtime.evaluate", eval_req, token);
Assert.True (eval_res.IsOk);
var pause_location = await insp.WaitFor(Inspector.PAUSE);
//make sure we're on the right bp
Assert.Equal ("dotnet:0", pause_location ["hitBreakpoints"]?[0]?.Value<string> ());
var top_frame = pause_location ["callFrames"][0];
CheckLocation ("dotnet://debugger-test.dll/debugger-test.cs", 4, 41, scripts, top_frame["functionLocation"]);
CheckLocation ("dotnet://debugger-test.dll/debugger-test.cs", 5, 2, scripts, top_frame["location"]);
var step_res = await cli.SendCommand ("Debugger.stepOver", null, token);
Assert.True (step_res.IsOk);
var pause_location2 = await insp.WaitFor(Inspector.PAUSE);
var top_frame2 = pause_location2 ["callFrames"][0];
CheckLocation ("dotnet://debugger-test.dll/debugger-test.cs", 4, 41, scripts, top_frame2["functionLocation"]);
CheckLocation ("dotnet://debugger-test.dll/debugger-test.cs", 6, 2, scripts, top_frame2["location"]); //it moved one line!
});
}
[Fact]
public async Task InspectLocalsDuringStepping () {
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await insp.Ready (async (cli, token) => {
var bp1_req = JObject.FromObject(new {
lineNumber = 5,
columnNumber = 2,
url = "dotnet://debugger-test.dll/debugger-test.cs",
});
var bp1_res = await cli.SendCommand ("Debugger.setBreakpointByUrl", bp1_req, token);
Assert.True (bp1_res.IsOk);
var eval_req = JObject.FromObject(new {
expression = "window.setTimeout(function() { invoke_add(); }, 1);",
});
var eval_res = await cli.SendCommand ("Runtime.evaluate", eval_req, token);
Assert.True (eval_res.IsOk);
var pause_location = await insp.WaitFor(Inspector.PAUSE);
//ok, what's on that scope?
var get_prop_req = JObject.FromObject(new {
objectId = "dotnet:scope:0",
});
var frame_props = await cli.SendCommand ("Runtime.getProperties", get_prop_req, token);
Assert.True (frame_props.IsOk);
var locals = frame_props.Value ["result"];
CheckNumber (locals, "a", 10);
CheckNumber (locals, "b", 20);
CheckNumber (locals, "c", 0);
CheckNumber (locals, "d", 0);
CheckNumber (locals, "e", 0);
//step and get locals
var step_res = await cli.SendCommand ("Debugger.stepOver", null, token);
Assert.True (step_res.IsOk);
pause_location = await insp.WaitFor(Inspector.PAUSE);
frame_props = await cli.SendCommand ("Runtime.getProperties", get_prop_req, token);
Assert.True (frame_props.IsOk);
locals = frame_props.Value ["result"];
CheckNumber (locals, "a", 10);
CheckNumber (locals, "b", 20);
CheckNumber (locals, "c", 30);
CheckNumber (locals, "d", 0);
CheckNumber (locals, "e", 0);
//step and get locals
step_res = await cli.SendCommand ("Debugger.stepOver", null, token);
Assert.True (step_res.IsOk);
pause_location = await insp.WaitFor(Inspector.PAUSE);
frame_props = await cli.SendCommand ("Runtime.getProperties", get_prop_req, token);
Assert.True (frame_props.IsOk);
locals = frame_props.Value ["result"];
CheckNumber (locals, "a", 10);
CheckNumber (locals, "b", 20);
CheckNumber (locals, "c", 30);
CheckNumber (locals, "d", 50);
CheckNumber (locals, "e", 0);
});
}
//TODO add tests covering basic stepping behavior as step in/out/over
}
}
+24 -8
View File
@@ -80,7 +80,7 @@ release/:
MONO_LIBS = $(TOP)/sdks/out/wasm-runtime-release/lib/libmono-ee-interp.a $(TOP)/sdks/out/wasm-runtime-release/lib/libmonosgen-2.0.a $(TOP)/sdks/out/wasm-runtime-release/lib/libmono-ilgen.a $(TOP)/sdks/out/wasm-runtime-release/lib/libmono-icall-table.a
debug/.stamp-build: driver.o library_mono.js binding_support.js dotnet_support.js $(TOP)/sdks/out/wasm-runtime-release/lib/libmonosgen-2.0.a | debug/
$(EMCC) -g4 -Os -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s BINARYEN=1 -s "BINARYEN_TRAP_MODE='clamp'" -s ALIASING_FUNCTION_POINTERS=0 -s ASSERTIONS=1 --js-library library_mono.js --js-library binding_support.js --js-library dotnet_support.js driver.o $(MONO_LIBS) -o debug/mono.js -s NO_EXIT_RUNTIME=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall', 'FS_createPath', 'FS_createDataFile', 'cwrap', 'setValue', 'getValue', 'UTF8ToString']"
$(EMCC) -g4 -Os -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s BINARYEN=1 -s "BINARYEN_TRAP_MODE='clamp'" -s ALIASING_FUNCTION_POINTERS=0 -s ASSERTIONS=1 --js-library library_mono.js --js-library binding_support.js --js-library dotnet_support.js driver.o $(MONO_LIBS) -o debug/mono.js -s NO_EXIT_RUNTIME=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap', 'setValue', 'getValue', 'UTF8ToString']"
touch $@
# Notice that release/.stamp-build depends on debug/.stamp-build. This is the case as emcc is believed to not work well with parallel builds.
@@ -124,10 +124,15 @@ Simple.Dependency.dll: dependency.cs
sample.dll: Simple.Dependency.dll sample.cs WebAssembly.Bindings.dll WebAssembly.Net.Http.dll
$(CSC) $(CSC_FLAGS) /target:library -out:$@ /r:Simple.Dependency.dll /r:$(WASM_BCL_DIR)/mscorlib.dll /r:$(WASM_BCL_DIR)/System.dll /r:$(WASM_BCL_DIR)/System.Core.dll /r:$(WASM_BCL_DIR)/System.Net.Http.dll /r:WebAssembly.Bindings.dll /r:WebAssembly.Net.Http.dll sample.cs
debugger-test.dll: debugger-test.cs debugger-test2.cs Simple.Dependency.dll
$(CSC) $(CSC_FLAGS) /target:library -out:$@ /r:$(WASM_BCL_DIR)/mscorlib.dll /r:Simple.Dependency.dll debugger-test.cs debugger-test2.cs
OPTIONS_CS = $(TOP)/mcs/class/Mono.Options/Mono.Options/Options.cs
Mono.Cecil.dll: Makefile
Mono.Cecil.0.10.0/lib/net40/Mono.Cecil.dll:
nuget install -version 0.10.0 Mono.Cecil
Mono.Cecil.dll: Mono.Cecil.0.10.0/lib/net40/Mono.Cecil.dll
cp Mono.Cecil.0.10.0/lib/net40/Mono.Cecil.dll $@
# We use system csc as this is a desktop program
@@ -135,8 +140,7 @@ packager.exe: packager.cs Mono.Cecil.dll $(OPTIONS_CS)
csc /debug:portable /out:$@ /r:Mono.Cecil.dll packager.cs $(OPTIONS_CS)
.stamp-build-debug-sample: $(DRIVER_CONF)/.stamp-build packager.exe WebAssembly.Bindings.dll WebAssembly.Net.Http.dll sample.dll debug.html runtime.js
mono packager.exe -debug -out=debug_sample sample.dll
cp debug.html debug_sample
mono --debug packager.exe -debug -out=debug_sample --asset=debug.html sample.dll
touch $@
TEST_ASSEMBLIES = $(WASM_BCL_DIR)/nunitlite.dll $(WASM_BCL_DIR)/tests/wasm_corlib_test.dll $(WASM_BCL_DIR)/tests/wasm_System_test.dll $(WASM_BCL_DIR)/tests/wasm_System.Core_test.dll
@@ -146,16 +150,21 @@ TEST_ASSEMBLIES = $(WASM_BCL_DIR)/nunitlite.dll $(WASM_BCL_DIR)/tests/wasm_corli
ninja -v -C obj/test-suite
touch $@
.stamp-build-debugger-test-app: $(DRIVER_CONF)/.stamp-build packager.exe WebAssembly.Bindings.dll binding_tests.dll debugger-test.dll debugger-test-driver.js
mono --debug packager.exe --debugrt --debug --template=runtime.js --appdir=bin/debugger-test-suite --builddir=obj/debugger-test-suite debugger-test.dll --asset=debugger-driver.html
ninja -v -C obj/debugger-test-suite
touch $@
# For development
aot-sample: packager.exe mini_tests.dll main.exe runtime.js
mono packager.exe --emscripten-sdkdir=$(EMSCRIPTEN_SDKDIR) --mono-sdkdir=$(TOP)/sdks/out -appdir=bin/aot-sample --nobinding --builddir=obj/aot-sample --aot --template=runtime-tests.js mini_tests.dll
mono --debug packager.exe --emscripten-sdkdir=$(EMSCRIPTEN_SDKDIR) --mono-sdkdir=$(TOP)/sdks/out -appdir=bin/aot-sample --nobinding --builddir=obj/aot-sample --aot --template=runtime-tests.js mini_tests.dll
ninja -v -C obj/aot-sample
do-aot-sample: aot-sample
(cd bin/aot-sample && $(SM) runtime.js --regression mini_tests.dll)
build-aot-mini: packager.exe mini_tests.dll main.exe runtime.js
mono packager.exe --emscripten-sdkdir=$(EMSCRIPTEN_SDKDIR) --mono-sdkdir=$(TOP)/sdks/out -appdir=bin/aot-mini --nobinding --builddir=obj/aot-mini --aot --template=runtime-tests.js mini_tests.dll
mono --debug packager.exe --emscripten-sdkdir=$(EMSCRIPTEN_SDKDIR) --mono-sdkdir=$(TOP)/sdks/out -appdir=bin/aot-mini --nobinding --builddir=obj/aot-mini --aot --template=runtime-tests.js mini_tests.dll
ninja -v -C obj/aot-mini
check-aot-mini run-aot-mini: build-aot-mini
@@ -169,7 +178,7 @@ check-aot-mini run-aot-mini: build-aot-mini
define AotTestTemplate
build-aot-$(1): packager.exe runtime-tests.js main.exe WebAssembly.Bindings.dll binding_tests.dll $$(WASM_BCL_DIR)/nunitlite.dll $$(WASM_BCL_DIR)/tests/$(2)
mono packager.exe --emscripten-sdkdir=$$(EMSCRIPTEN_SDKDIR) --mono-sdkdir=$$(TOP)/sdks/out -appdir=bin/aot-$(1) --nobinding --builddir=obj/aot-$(1) --aot --template=runtime-tests.js main.exe WebAssembly.Bindings.dll binding_tests.dll $$(WASM_BCL_DIR)/tests/$(2)
mono --debug packager.exe --emscripten-sdkdir=$$(EMSCRIPTEN_SDKDIR) --mono-sdkdir=$$(TOP)/sdks/out -appdir=bin/aot-$(1) --nobinding --builddir=obj/aot-$(1) --aot --template=runtime-tests.js main.exe WebAssembly.Bindings.dll binding_tests.dll $$(WASM_BCL_DIR)/tests/$(2)
ninja -v -C obj/aot-$(1)
clean-aot-$(1):
@@ -196,11 +205,15 @@ build-debug-sample: .stamp-build-debug-sample
build-test-suite: .stamp-build-test-suite
build-managed: build-debug-sample build-test-suite $(WASM_BCL_DIR)/monolinker.exe $(WASM_BCL_DIR)/Mono.Cecil.dll
build-debugger-test-app: .stamp-build-debugger-test-app
build-managed: build-debug-sample build-test-suite build-dbg-testsuite $(WASM_BCL_DIR)/monolinker.exe $(WASM_BCL_DIR)/Mono.Cecil.dll
build-dbg-proxy:
dotnet build ProxyDriver
build-dbg-testsuite:
dotnet build DebuggerTestSuite
build-framework-nuget:
nuget pack WebAssembly.Framework.nuspec
@@ -230,6 +243,9 @@ run-all-%:
make -C . run-sm-$*
make -C . run-jsc-$*
test-debugger: build-debugger-test-app build-dbg-testsuite
dotnet test DebuggerTestSuite
clean:
package: build build-dbg-proxy build-framework-nuget
@@ -7,7 +7,8 @@ using System.Linq;
using Newtonsoft.Json.Linq;
using System.Net.Http;
namespace WsProxy {
namespace Mono.WebAssembly {
internal class BreakPointRequest {
public string Assembly { get; private set; }
public string File { get; private set; }
@@ -263,7 +264,7 @@ namespace WsProxy {
internal class AssemblyInfo {
static int next_id;
ModuleDefinition image;
internal readonly ModuleDefinition image;
readonly int id;
Dictionary<int, MethodInfo> methods = new Dictionary<int, MethodInfo> ();
readonly List<SourceFile> sources = new List<SourceFile> ();
@@ -345,6 +346,9 @@ namespace WsProxy {
return methods [token];
}
public TypeDefinition GetTypeByName (string name) {
return this.image.GetType (name);
}
}
internal class SourceFile {
@@ -507,7 +511,12 @@ namespace WsProxy {
public SourceLocation FindBestBreakpoint (BreakPointRequest req)
{
var asm = this.assemblies.FirstOrDefault (a => a.Name == req.Assembly);
if (asm == null)
return null;
var src = asm.Sources.FirstOrDefault (s => s.FileName == req.File);
if (src == null)
return null;
foreach (var m in src.Methods) {
foreach (var sp in m.methodDef.DebugInformation.SequencePoints) {
@@ -524,5 +533,18 @@ namespace WsProxy {
{
return GetFileById (location.Id).Url;
}
public TypeDefinition LookupType (string fqn) {
var parts = fqn.Split (',');
var typeName = parts[0].Trim ().Replace ("+", "/");
var asmName = parts[1].Trim ();
Console.WriteLine ($"({typeName}) ({asmName})");
var asm = this.assemblies.FirstOrDefault (a => a.image.Assembly.Name.Name == asmName);
Console.WriteLine ($"asm : {asm}");
if (asm == null)
return null;
return asm.GetTypeByName (typeName);
}
}
}
@@ -0,0 +1,75 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace Mono.WebAssembly {
public class InspectorClient : WsClient {
List<(int, TaskCompletionSource<Result>)> pending_cmds = new List<(int, TaskCompletionSource<Result>)> ();
Func<string, JObject, CancellationToken, Task> onEvent;
int next_cmd_id;
Task HandleMessage (string msg, CancellationToken token)
{
var res = JObject.Parse (msg);
if (res ["id"] == null)
DumpProtocol (string.Format("Event method: {0} params: {1}", res ["method"], res ["params"]));
else
DumpProtocol (string.Format ("Response id: {0} res: {1}", res ["id"], res));
if (res ["id"] == null)
return onEvent (res ["method"].Value<string> (), res ["params"] as JObject, token);
var id = res ["id"].Value<int> ();
var idx = pending_cmds.FindIndex (e => e.Item1 == id);
var item = pending_cmds [idx];
pending_cmds.RemoveAt (idx);
item.Item2.SetResult (Result.FromJson (res));
return null;
}
public async Task Connect(
Uri uri,
Func<string, JObject, CancellationToken, Task> onEvent,
Func<CancellationToken, Task> send,
CancellationToken token) {
this.onEvent = onEvent;
await ConnectWithMainLoops (uri, HandleMessage, send, token);
}
public Task<Result> SendCommand (string method, JObject args, CancellationToken token)
{
int id = ++next_cmd_id;
if (args == null)
args = new JObject ();
var o = JObject.FromObject (new {
id = id,
method = method,
@params = args
});
var tcs = new TaskCompletionSource<Result> ();
pending_cmds.Add ((id, tcs));
var str = o.ToString ();
DumpProtocol ($"Command: id: {id} method: {method} params: {args}");
var bytes = Encoding.UTF8.GetBytes (str);
Send (bytes, token);
return tcs.Task;
}
protected virtual void DumpProtocol (string msg){
// Console.WriteLine (msg);
//XXX make logging not stupid
}
}
}
@@ -6,7 +6,7 @@
<ItemGroup>
<PackageReference Include="Mono.Cecil" Version="0.10.0" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>
</Project>
@@ -8,8 +8,13 @@ using System.Threading;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace WsProxy {
using Mono.Cecil;
using Mono.Cecil.Cil;
namespace Mono.WebAssembly {
internal class MonoCommands {
public const string GET_CALL_STACK = "MONO.mono_wasm_get_call_stack()";
@@ -20,12 +25,274 @@ namespace WsProxy {
public const string REMOVE_BREAK_POINT = "MONO.mono_wasm_remove_breakpoint({0})";
public const string GET_LOADED_FILES = "MONO.mono_wasm_get_loaded_files()";
public const string CLEAR_ALL_BREAKPOINTS = "MONO.mono_wasm_clear_all_breakpoints()";
public const string GET_OBJECT_FIELDS = "MONO.mono_wasm_get_object_fields({0})";
public const string EVALUATE_PROPERTY = "MONO.mono_wasm_evaluate_property({0}, '{1}')";
}
internal enum MonoErrorCodes {
public enum MonoErrorCodes {
BpNotFound = 100000,
}
class ObjectId {
public int Id { get; private set; }
public bool NonPublicOnly { get; private set; }
public int DepthLevel { get; private set; }
public string PropertyName { get; private set; }
public bool IsPropertyFetch => PropertyName != null;
public bool IsParentFetch => DepthLevel > 0;
public static ObjectId TryParse (string str) {
if (!str.StartsWith ("dotnet:objid:", StringComparison.InvariantCulture))
return null;
var res = new ObjectId ();
var parts = str.Substring ("dotnet:objid:".Length).Split (':');
foreach (var p in parts) {
if (p.StartsWith ("base_", StringComparison.InvariantCulture)) {
res.DepthLevel = int.Parse (p.Substring ("base_".Length));
} else if (p == "priv") {
res.NonPublicOnly = true;
} else if (p.StartsWith ("prop_", StringComparison.InvariantCulture)) {
res.PropertyName = p.Substring ("prop_".Length);
} else {
res.Id = int.Parse (p);
}
}
return res;
}
static string MakeObjectId (int object_id, int depth_level, bool nonPublicOnly)
{
string parent_str = depth_level > 0 ? $":base_{depth_level}" : "";
string priv_str = nonPublicOnly ? ":priv" : "";
return $"dotnet:objid{parent_str}{priv_str}:{object_id}";
}
public string MakePropertyFetchID (string name) {
return $"{this}:prop_{name}";
}
public string JsQueryString {
get {
return $"{Id}, {DepthLevel}";
}
}
public string ParentObjectId {
get {
return MakeObjectId (Id, DepthLevel + 1, NonPublicOnly);
}
}
public string PrivateStuffObjectId {
get {
return MakeObjectId (Id, DepthLevel, true);
}
}
public override string ToString () {
return MakeObjectId (Id, DepthLevel, NonPublicOnly);
}
}
class DisplayCandidate {
public FieldDefinition Field { get; private set; }
public PropertyDefinition Property { get; private set; }
public bool Included { get; private set; }
public bool IsField => Field != null && Property == null;
public bool IsProperty => Property != null;
public bool IsGeneratedProperty => Property != null && Field != null;
public DisplayCandidate (FieldDefinition f) {
Field = f;
}
public DisplayCandidate (PropertyDefinition p, FieldDefinition f) {
Property = p;
Field = f;
}
public override string ToString () {
if (Property != null)
return $"prop {Property.Name} " + (Field == null ? "" : $"backed by {Field.Name}");
return $"field {Field.Name}";
}
//FIXME this method name SUCKS
public void AddFromFieldValue (List<JObject> list, JObject src) {
if (Included)
return;
Included = true;
if (IsGeneratedProperty)
src ["name"] = Property.Name;
list.Add (src);
}
public void AddWithoutValue (List<JObject> list, ObjectId objId) {
if (Included)
return;
Included = true;
if (IsProperty) {
list.Add (JObject.FromObject (new {
name = Property.Name,
// value = new {
// type = "object",
// description = "Computed Property", //This is needed otherwise it bricks the devtools debugger <o>
// objectId = objId.MakePropertyFetchID (Property.Name),
// }
// get could work, but it's complicated
get = objId.MakePropertyFetchID (Property.Name),
}));
} else {
throw new Exception ($"Unprocessed DisplayCandidate: {this}");
}
}
}
class TypeDescriber {
readonly ObjectId objId;
readonly TypeDefinition typeDesc;
readonly JObject[] fields;
internal TypeDescriber (ObjectId objId, TypeDefinition typeDesc, JObject[] fields) {
this.objId = objId;
this.typeDesc = typeDesc;
this.fields = fields;
}
internal List<JObject> CollectDisplayFields () {
/*Var display algorithm:
1) collect fields/properties from MD
2) match those to supplied data (including field->property conversion)
3) add the missing ones under prop fetch objIds
4) include pseudo base/private objects
*/
Console.WriteLine ($"RESOLVING ({objId}) for ({typeDesc})");
var var_list = new List<JObject> ();
if (typeDesc == null) {
for (int i = 0; fields != null && i < fields.Length; ++i)
var_list.Add (fields [i]);
return var_list;
}
var candidates = new Dictionary <string, DisplayCandidate> ();
var possibleBackingFields = new Dictionary <string, FieldDefinition> ();
var isBackingField = new Regex ("<(.*)>k__BackingField");
bool has_unmatched_data = false;
foreach (var f in typeDesc.Fields) {
if (f.IsStatic || f.IsLiteral)
continue;
if (isBackingField.IsMatch (f.Name)) {
var m = isBackingField.Match (f.Name);
var propNameInField = m.Groups[1].Value;
possibleBackingFields [propNameInField] = f;
}
if (this.objId.NonPublicOnly == f.IsPublic) {
has_unmatched_data = true;
continue;
}
candidates [f.Name] = new DisplayCandidate (f);
}
foreach (var pd in typeDesc.Properties) {
//ignore write only properties
if (pd.GetMethod == null)
continue;
if (pd.GetMethod.IsStatic)
continue;
if (this.objId.NonPublicOnly == pd.GetMethod.IsPublic) {
has_unmatched_data = true;
continue;
}
//try to find a backing field
FieldDefinition fd = null;
possibleBackingFields.TryGetValue (pd.Name, out fd);
var c = new DisplayCandidate (pd, fd);
candidates [pd.Name] = c;
if (fd != null)
candidates [fd.Name] = c;
}
// Console.WriteLine ("Candidates:");
// foreach (var kv in candidates)
// Console.WriteLine($"\t'{kv.Key}': {kv.Value}");
for (int i = 0; fields != null && i < fields.Length; ++i) {
var field = fields [i];
var fieldName = field ["name"].Value<string>();
DisplayCandidate cand = null;
if (!candidates.TryGetValue (fieldName, out cand))
continue;
cand.AddFromFieldValue (var_list, field);
}
foreach (var cand in candidates.Values)
cand.AddWithoutValue (var_list, objId);
if (!objId.NonPublicOnly && typeDesc.BaseType != null && typeDesc.BaseType.FullName != "System.Object")
var_list.Add (JObject.FromObject (new {
name = "Base",
value = new {
type = "object",
description = $"{typeDesc.BaseType.FullName} fields",
objectId = objId.ParentObjectId
}
}));
if (!objId.NonPublicOnly && has_unmatched_data)
var_list.Add (JObject.FromObject (new {
name = "Non-Public",
value = new {
type = "object",
description = "Non Public stuff",
objectId = objId.PrivateStuffObjectId
}
}));
return var_list;
}
bool FilterField (TypeDefinition typeDesc, JObject field)
{
//FIXME take some sort of filtering rule as argument
Console.WriteLine ("FILTERING {0} TD -> {1}", field, typeDesc);
if (typeDesc != null) {
var fieldName = field ["name"].Value<string>();
FieldDefinition field_def = typeDesc.Fields.FirstOrDefault (f => f.Name == fieldName);
if (field_def == null) {
Console.WriteLine ("can't find field info :(");
return true;
}
if (field_def.IsPublic)
return true;
var r = new Regex ("<(.*)>k__BackingField");
if (r.IsMatch (fieldName)) {
var m = r.Match (fieldName);
var propNameInField = m.Groups[1].Value;
var pd = typeDesc.Properties.FirstOrDefault (p => p.Name == propNameInField);
if (pd != null && pd.GetMethod != null && pd.GetMethod.IsPublic) {
field["name"] = pd.Name;
return true;
}
}
//<A>k__BackingField
//ok, field is private, maybe it's the backing field of a property?
// if (field_def != null && !field_def.IsPublic) {
Console.WriteLine ("filtering private field");
return false;
}
return true;
}
}
internal class MonoConstants {
public const string RUNTIME_IS_READY = "mono_wasm_runtime_ready";
@@ -200,11 +467,40 @@ namespace WsProxy {
await GetScopeProperties (id, int.Parse (objId.Substring ("dotnet:scope:".Length)), token);
return true;
}
var o = ObjectId.TryParse (objId);
if (o != null) {
await GetObjectProperties (id, o, token);
return true;
}
break;
}
}
case "Runtime.callFunctionOn": {
var objId = args? ["objectId"]?.Value<string> ();
var funcDecl = args? ["functionDeclaration"]?.Value<string> ();
var o = ObjectId.TryParse (objId);
if (o == null)
break;
//ensure devtools is calling invokeGetter
if (funcDecl.IndexOf ("invokeGetter") < 0)
break;
var prop_array = args? ["arguments"]? [0]? ["value"]?.Value<string> ();
string propName = null;
if (prop_array == null)
break;
var parts = prop_array.Split('\"');
if (parts == null || parts.Length < 2)
break;
propName = parts [1];
await EvaluateProperty (id, o, propName, token);
return true;
}
}
return false;
}
@@ -253,6 +549,10 @@ namespace WsProxy {
return;
}
var bp = this.breakpoints.FirstOrDefault (b => b.RemoteId == bp_id.Value);
Console.WriteLine ($"bp is {bp} bp_id is {bp_id.Value}");
foreach (var b in this.breakpoints) {
Console.WriteLine ($"\tddd {b.RemoteId}");
}
var src = bp == null ? null : store.GetFileById (bp.Location.Id);
@@ -269,6 +569,7 @@ namespace WsProxy {
var method_token = mono_frame ["method_token"].Value<int> ();
var assembly_name = mono_frame ["assembly_name"].Value<string> ();
Console.WriteLine ($"frame pos {il_pos} method_token {method_token} asm {assembly_name}");
var asm = store.GetAssemblyByName (assembly_name);
var method = asm.GetMethodByToken (method_token);
var location = method.GetLocationByIl (il_pos);
@@ -332,7 +633,7 @@ namespace WsProxy {
hitBreakpoints = bp_list,
});
SendEvent ("Debugger.paused", o, token);
SendEvent ("Debugger.paused", o, token);
}
async Task OnDefaultContext (int ctx_id, JObject aux_data, CancellationToken token)
@@ -401,6 +702,7 @@ namespace WsProxy {
var var_ids = string.Join (",", vars.Select (v => v.Index));
//TODO respect the objectGroup of the debugger
var o = JObject.FromObject (new {
expression = string.Format (MonoCommands.GET_SCOPE_VARIABLES, scope.Id, var_ids),
objectGroup = "mono_debugger",
@@ -424,13 +726,40 @@ namespace WsProxy {
// Trying to inspect the stack frame for DotNetDispatcher::InvokeSynchronously
// results in a "Memory access out of bounds", causing 'values' to be null,
// so skip returning variable values in that case.
JObject capture_object = null;
for (int i = 0; values != null && i < vars.Length; ++i) {
if (vars [i].Name.StartsWith ("CS$")) { //FIXME is this the right pattern to match?
capture_object = values [i] ["value"]?.Value<JObject> ();
continue;
}
var_list.Add (JObject.FromObject (new {
name = vars [i].Name,
value = values [i] ["value"]
}));
}
if (capture_object != null) {
var objId = ObjectId.TryParse (capture_object ["objectId"]?.Value<string> ());
o = JObject.FromObject (new {
expression = string.Format (MonoCommands.GET_OBJECT_FIELDS, objId.JsQueryString),
objectGroup = "mono_debugger",
includeCommandLineAPI = false,
silent = false,
returnByValue = true,
});
res = await SendCommand ("Runtime.evaluate", o, token);
if (!res.IsErr) {
var fields = res.Value? ["result"]? ["value"]? ["fields"]?.Values<JObject> ().ToArray ();
foreach (var f in fields) {
var_list.Add (JObject.FromObject (new {
name = f["name"],
value = f["value"]
}));
}
}
}
o = JObject.FromObject (new {
result = var_list
});
@@ -438,6 +767,67 @@ namespace WsProxy {
SendResponse (msg_id, Result.Ok (o), token);
}
async Task EvaluateProperty (int msg_id, ObjectId objId, string propName, CancellationToken token)
{
var o = JObject.FromObject (new {
expression = string.Format (MonoCommands.EVALUATE_PROPERTY, objId.JsQueryString, propName),
objectGroup = "mono_debugger",
includeCommandLineAPI = false,
silent = false,
returnByValue = true,
});
var res = await SendCommand ("Runtime.evaluate", o, token);
//if we fail we just buble that to the IDE (and let it panic over it)
if (res.IsErr) {
SendResponse (msg_id, res, token);
return;
}
o = JObject.FromObject (new {
result = res.Value? ["result"]? ["value"]? [0]? ["value"]
});
SendResponse (msg_id, Result.Ok (o), token);
}
async Task GetObjectProperties (int msg_id, ObjectId objId, CancellationToken token)
{
//TODO respect the objectGroup of the debugger
//TODO deal with
// "ownProperties": false,
// "accessorPropertiesOnly": false,
// "generatePreview": true
if (objId.IsPropertyFetch)
throw new Exception ($"Invalid GetProperty objid {objId}");
//XXX resolve the type locally and produce property info without going to the debugee
var o = JObject.FromObject (new {
expression = string.Format (MonoCommands.GET_OBJECT_FIELDS, objId.JsQueryString),
objectGroup = "mono_debugger",
includeCommandLineAPI = false,
silent = false,
returnByValue = true,
});
var res = await SendCommand ("Runtime.evaluate", o, token);
//if we fail we just buble that to the IDE (and let it panic over it)
if (res.IsErr) {
SendResponse (msg_id, res, token);
return;
}
var fqn = res.Value? ["result"]? ["value"]? ["fqn"]?.Value<string> ();
var fields = res.Value? ["result"]? ["value"]? ["fields"]?.Values<JObject> ().ToArray ();
var typeDesc = this.store.LookupType (fqn);
var td = new TypeDescriber (objId, typeDesc, fields);
o = JObject.FromObject (new {
result = td.CollectDisplayFields ()
});
SendResponse (msg_id, Result.Ok (o), token);
}
async Task<Result> EnableBreakPoint (Breakpoint bp, CancellationToken token)
{
var asm_name = bp.Location.CliLocation.Method.Assembly.Name;
@@ -477,6 +867,8 @@ namespace WsProxy {
var loaded_pdbs = await SendCommand ("Runtime.evaluate", o, token);
var the_value = loaded_pdbs.Value? ["result"]? ["value"];
var the_pdbs = the_value?.ToObject<string[]> ();
Console.WriteLine ("pdbs {0}", string.Join(",", the_pdbs));
this.store = new DebugStore (the_pdbs);
foreach (var s in store.AllSources ()) {
@@ -520,6 +912,8 @@ namespace WsProxy {
bp.State = BreakPointState.Disabled;
}
}
SendEvent ("Mono.runtimeReady", new JObject (), token);
}
async Task<bool> RemoveBreakpoint(int msg_id, JObject args, CancellationToken token) {
@@ -0,0 +1,129 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace Mono.WebAssembly {
public class WsClient: IDisposable {
ClientWebSocket socket;
List<Task> pending_ops = new List<Task> ();
TaskCompletionSource<bool> side_exit = new TaskCompletionSource<bool> ();
List<byte []> pending_writes = new List<byte []> ();
Task current_write;
public WsClient () {
}
~WsClient() {
Dispose(false);
}
public void Dispose() {
Dispose(true);
}
protected virtual void Dispose (bool disposing) {
if (disposing)
socket.Dispose ();
}
Task Pump (Task task, CancellationToken token)
{
if (task != current_write)
return null;
current_write = null;
pending_writes.RemoveAt (0);
if (pending_writes.Count > 0) {
current_write = socket.SendAsync (new ArraySegment<byte> (pending_writes [0]), WebSocketMessageType.Text, true, token);
return current_write;
}
return null;
}
async Task<string> ReadOne (CancellationToken token)
{
byte [] buff = new byte [4000];
var mem = new MemoryStream ();
while (true) {
var result = await this.socket.ReceiveAsync (new ArraySegment<byte> (buff), token);
if (result.MessageType == WebSocketMessageType.Close) {
return null;
}
if (result.EndOfMessage) {
mem.Write (buff, 0, result.Count);
return Encoding.UTF8.GetString (mem.GetBuffer (), 0, (int)mem.Length);
} else {
mem.Write (buff, 0, result.Count);
}
}
}
protected void Send (byte [] bytes, CancellationToken token)
{
pending_writes.Add (bytes);
if (pending_writes.Count == 1) {
if (current_write != null)
throw new Exception ("Internal state is bad. current_write must be null if there are no pending writes");
current_write = socket.SendAsync (new ArraySegment<byte> (bytes), WebSocketMessageType.Text, true, token);
pending_ops.Add (current_write);
}
}
async Task MarkCompleteAfterward (Func<CancellationToken, Task> send, CancellationToken token)
{
try {
await send(token);
side_exit.SetResult (true);
} catch (Exception e) {
side_exit.SetException (e);
}
}
protected async Task<bool> ConnectWithMainLoops(
Uri uri,
Func<string, CancellationToken, Task> receive,
Func<CancellationToken, Task> send,
CancellationToken token) {
Console.WriteLine ("connecting to {0}", uri);
this.socket = new ClientWebSocket ();
this.socket.Options.KeepAliveInterval = Timeout.InfiniteTimeSpan;
await this.socket.ConnectAsync (uri, token);
pending_ops.Add (ReadOne (token));
pending_ops.Add (side_exit.Task);
pending_ops.Add (MarkCompleteAfterward (send, token));
while (!token.IsCancellationRequested) {
var task = await Task.WhenAny (pending_ops);
if (task == pending_ops [0]) { //pending_ops[0] is for message reading
var msg = ((Task<string>)task).Result;
pending_ops [0] = ReadOne (token);
Task tsk = receive (msg, token);
if (tsk != null)
pending_ops.Add (tsk);
} else if (task == pending_ops [1]) {
var res = ((Task<bool>)task).Result;
//it might not throw if exiting successfull
return res;
} else { //must be a background task
pending_ops.Remove (task);
var tsk = Pump (task, token);
if (tsk != null)
pending_ops.Add (tsk);
}
}
return false;
}
}
}
@@ -9,9 +9,8 @@ using System.IO;
using System.Text;
using System.Collections.Generic;
namespace WsProxy {
internal struct Result {
namespace Mono.WebAssembly {
public struct Result {
public JObject Value { get; private set; }
public JObject Error { get; private set; }
@@ -52,9 +51,13 @@ namespace WsProxy {
});
}
}
public override string ToString () {
return ToJObject (-1).ToString ();
}
}
class WsQueue {
internal class WsQueue {
Task current_send;
List<byte []> pending;
@@ -119,16 +122,23 @@ namespace WsProxy {
byte [] buff = new byte [4000];
var mem = new MemoryStream ();
while (true) {
var result = await socket.ReceiveAsync (new ArraySegment<byte> (buff), token);
if (result.MessageType == WebSocketMessageType.Close) {
return null;
}
try {
var result = await socket.ReceiveAsync (new ArraySegment<byte> (buff), token);
if (result.MessageType == WebSocketMessageType.Close) {
return null;
}
if (result.EndOfMessage) {
mem.Write (buff, 0, result.Count);
return Encoding.UTF8.GetString (mem.GetBuffer (), 0, (int)mem.Length);
} else {
mem.Write (buff, 0, result.Count);
if (result.EndOfMessage) {
mem.Write (buff, 0, result.Count);
return Encoding.UTF8.GetString (mem.GetBuffer (), 0, (int)mem.Length);
} else {
mem.Write (buff, 0, result.Count);
}
} catch (WebSocketException e) {
//target just disconnected, meh
if (e.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
return null;
throw;
}
}
}
@@ -170,6 +180,9 @@ namespace WsProxy {
if (!await AcceptCommand (id, method, args, token)) {
var res = await SendCommandInternal (method, args, token);
SendResponseInternal (id, res, token);
if (method == "Runtime.getProperties")
Console.WriteLine ("req: {0}\n res: {1}", args, res);
}
} catch (Exception e) {
side_exception.TrySetException (e);
@@ -190,6 +203,11 @@ namespace WsProxy {
{
// Debug ($"browser: {msg}");
var res = JObject.Parse (msg);
if (res ["id"] == null) {
Dump (string.Format("BROWSER: event method: {0}", res ["method"]));
} else {
Dump (string.Format ("BROWSER: response id: {0} data {1}", res ["id"], res));
}
if (res ["id"] == null)
pending_ops.Add (OnEvent (res ["method"].Value<string> (), res ["params"] as JObject, token));
@@ -201,6 +219,7 @@ namespace WsProxy {
{
var res = JObject.Parse (msg);
Dump (string.Format ("IDE: id: {0} method: {1}", res ["id"], res ["method"]));
pending_ops.Add (OnCommand (res ["id"].Value<int> (), res ["method"].Value<string> (), res ["params"] as JObject, token));
}
@@ -222,6 +241,7 @@ namespace WsProxy {
//Console.WriteLine ("add cmd id {0}", id);
pending_cmds.Add ((id, tcs));
Dump($"->BROWSER cmd id: {id} method: {method}");
Send (this.browser, o, token);
return tcs.Task;
}
@@ -239,6 +259,7 @@ namespace WsProxy {
@params = args
});
Dump($"->IDE cmd method: {method}");
Send (this.ide, o, token);
}
@@ -252,6 +273,7 @@ namespace WsProxy {
{
JObject o = result.ToJObject (id);
Dump($"->IDE reply id {id}");
Send (this.ide, o, token);
}
@@ -280,10 +302,14 @@ namespace WsProxy {
//Console.WriteLine ("pump {0} {1}", task, pending_ops.IndexOf (task));
if (task == pending_ops [0]) {
var msg = ((Task<string>)task).Result;
if (msg == null)
break;
pending_ops [0] = ReadOne (browser, x.Token); //queue next read
ProcessBrowserMessage (msg, x.Token);
} else if (task == pending_ops [1]) {
var msg = ((Task<string>)task).Result;
if (msg == null)
break;
pending_ops [1] = ReadOne (ide, x.Token); //queue next read
ProcessIdeMessage (msg, x.Token);
} else if (task == pending_ops [2]) {
@@ -301,7 +327,7 @@ namespace WsProxy {
}
}
} catch (Exception e) {
Debug ($"got exception {e}");
Console.WriteLine ($"got exception {e}");
//throw;
} finally {
x.Cancel ();
@@ -312,12 +338,17 @@ namespace WsProxy {
protected void Debug (string msg)
{
Console.WriteLine (msg);
// Console.WriteLine (msg);
}
protected void Info (string msg)
{
Console.WriteLine (msg);
// Console.WriteLine (msg);
}
protected void Dump (string msg)
{
// Console.WriteLine (msg);
}
}
}
+158 -6
View File
@@ -1,28 +1,180 @@
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
namespace WsProxy
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseSetting(nameof(WebHostBuilderIISExtensions.UseIISIntegration), false.ToString())
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseSetting(nameof(WebHostBuilderIISExtensions.UseIISIntegration), false.ToString())
.ConfigureAppConfiguration (config => config.AddCommandLine (args))
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseUrls("http://localhost:9300")
.Build();
host.Run();
if (args.Length > 0 && args [0].StartsWith("/Debug=",StringComparison.OrdinalIgnoreCase)) {
var path = args [0].Substring ("/Debug=".Length);
var elems = path.Split ('/');
var x = new ChromeDebuggingSession (elems [elems.Length - 1]);
x.Start ();
}
host.Run();
}
}
public class TestHarnessProxy {
static IWebHost host;
public static void Start (string chrome_path, string app_path, string page_path) {
lock (typeof (TestHarnessProxy)) {
if (host != null)
return;
//FIXME wtf ConfigureAppConfiguration
string[] args = new [] {
$"/ChromePath={chrome_path}",
$"/AppPath={app_path}",
$"/PagePath={page_path}",
};
var h = new WebHostBuilder()
.UseSetting(nameof(WebHostBuilderIISExtensions.UseIISIntegration), false.ToString())
.ConfigureAppConfiguration (config => config.AddCommandLine (args))
.UseKestrel()
.UseStartup<TestHarnessStartup>()
.UseUrls("http://localhost:9300")
.Build();
host = h;
Task.Run (() => { host.Run (); });
//FIXME implement this using socket polling so it's faster
Thread.Sleep (1000);
Console.WriteLine ("WebServer Ready!");
}
}
}
class ChromeDebuggingSession {
string page_name;
TaskCompletionSource<bool> all_done = new TaskCompletionSource<bool> ();
public ChromeDebuggingSession (string page_name)
{
this.page_name = page_name;
}
public void Start ()
{
Task.Run (() => { Launch(); });
}
static string GuessChromePath() {
string chrome_path = null;
if (File.Exists ("/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"))
chrome_path = "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary";
else if (File.Exists ("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"))
chrome_path = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
if (chrome_path == null)
throw new Exception ("Could not find an installed Chrome to use");
return chrome_path;
}
void StageTwoLaunch (string wsURL)
{
//http://localhost:9222/devtools/inspector.html?ws:localhost:9300/devtools/page/43F58580226BB03ADB1955C9F0CF6BC9
//http://localhost:9222/devtools/inspector.html?ws=localhost:9300/devtools/page/C6E72B1B4E31893D99CF0448B7B56F11
var injected_url = wsURL.Replace ("://localhost:9222", "=localhost:9300");
var debugger_url = $"http://localhost:9222/devtools/inspector.html?{injected_url}";
Console.WriteLine("launching debugger pointing at {0}", debugger_url);
var psi = new ProcessStartInfo ();
psi.Arguments = $"--new-window --no-first-run --user-data-dir=ho --window-size=850,1000 --window-position=600,0 {debugger_url}";
psi.FileName = GuessChromePath ();
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
var proc = Process.Start (psi);
try {
proc.ErrorDataReceived += (sender, e) => {
var str = e.Data;
Console.WriteLine ($"dbg_cli: {str}");
};
proc.OutputDataReceived += (sender, e) => {
Console.WriteLine ($"dbg_cli: {e.Data}");
};
proc.BeginErrorReadLine ();
proc.BeginOutputReadLine ();
var _dummy = all_done.Task.Result;
} finally {
proc.CancelErrorRead ();
proc.CancelOutputRead ();
proc.Kill ();
proc.WaitForExit ();
proc.Close ();
}
}
void Launch()
{
//FIXME implement this using socket polling so it's faster
Thread.Sleep (1000);
Console.WriteLine ("proxy server is ready");
var page_to_debug = $"http://localhost:9300/app/{page_name}";
Console.WriteLine ("launching chrome to debug {0}", page_to_debug);
var psi = new ProcessStartInfo ();
psi.Arguments = $"--new-window --remote-debugging-port=9222 --no-first-run --user-data-dir={Path.GetTempPath ()} --window-size=600,1000 --window-position=0,0 {page_to_debug}";
psi.FileName = GuessChromePath ();
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
var proc = Process.Start (psi);
try {
proc.ErrorDataReceived += (sender, e) => {
var str = e.Data;
Console.WriteLine ($"page_cli: {str}");
//We wait for it as a signal that chrome finished launching
if (!str.StartsWith ("DevTools listening on ", StringComparison.Ordinal))
return;
var client = new HttpClient ();
var res = client.GetStringAsync ("http://localhost:9222/json/list").Result;
Console.WriteLine ("res is {0}", res);
var obj = JArray.Parse (res);
var wsURL = obj? [0]? ["webSocketDebuggerUrl"]?.Value<string> ();
Console.WriteLine (">>> {0}", wsURL);
StageTwoLaunch (wsURL);
};
proc.OutputDataReceived += (sender, e) => {
Console.WriteLine ($"page_cli: {e.Data}");
};
proc.BeginErrorReadLine ();
proc.BeginOutputReadLine ();
var _dummy = all_done.Task.Result;
} finally {
proc.CancelErrorRead ();
proc.CancelOutputRead ();
proc.Kill ();
proc.WaitForExit ();
proc.Close ();
}
}
}
}
+1 -4
View File
@@ -4,12 +4,9 @@
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.4" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>
<ItemGroup>
+32 -34
View File
@@ -1,18 +1,31 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using System.Net.WebSockets;
using System.Threading;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Newtonsoft.Json.Linq;
using Mono.WebAssembly;
namespace WsProxy
{
public class Startup {
private readonly IConfiguration configuration;
public Startup (IConfiguration configuration)
{
this.configuration = configuration;
}
internal class Startup {
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices (IServiceCollection services)
@@ -20,30 +33,6 @@ namespace WsProxy
services.AddRouting ();
}
public static async Task ProxyMsg (string desc, WebSocket from, WebSocket to)
{
byte [] buff = new byte [4000];
var mem = new MemoryStream ();
while (true) {
var result = await from.ReceiveAsync (new ArraySegment<byte> (buff), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close) {
await to.SendAsync (new ArraySegment<byte> (mem.GetBuffer (), 0, (int)mem.Length), WebSocketMessageType.Close, true, CancellationToken.None);
return;
}
if (result.EndOfMessage) {
mem.Write (buff, 0, result.Count);
var str = Encoding.UTF8.GetString (mem.GetBuffer (), 0, (int)mem.Length);
await to.SendAsync (new ArraySegment<byte> (mem.GetBuffer (), 0, (int)mem.Length), WebSocketMessageType.Text, true, CancellationToken.None);
mem.SetLength (0);
} else {
mem.Write (buff, 0, result.Count);
}
}
}
Uri GetBrowserUri (string path)
{
return new Uri ("ws://localhost:9222" + path);
@@ -52,11 +41,20 @@ namespace WsProxy
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure (IApplicationBuilder app, IHostingEnvironment env)
{
//loggerFactory.AddConsole();
//loggerFactory.AddDebug();
app.UseDeveloperExceptionPage ();
app.UseWebSockets ();
app.UseWebSockets (); app.UseRouter (router => {
var debug_path = configuration ["Debug"];
if (debug_path != null) {
var serve_path = Path.GetDirectoryName (debug_path);
Console.WriteLine ($"Configuring to server from {serve_path} under /app");
app.UseStaticFiles (new StaticFileOptions {
FileProvider = new PhysicalFileProvider (serve_path),
ServeUnknownFileTypes = true, //Cuz .wasm is not a known file type :cry:
RequestPath = "/app"
});
}
app.UseRouter (router => {
router.MapGet ("devtools/page/{pageId}", async context => {
if (!context.WebSockets.IsWebSocketRequest) {
context.Response.StatusCode = 400;
+187
View File
@@ -0,0 +1,187 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Newtonsoft.Json.Linq;
using Mono.WebAssembly;
namespace WsProxy {
public class TestHarnessStartup {
private readonly IConfiguration configuration;
public TestHarnessStartup (IConfiguration configuration)
{
this.configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices (IServiceCollection services)
{
services.AddRouting ();
}
async Task SendNodeVersion (HttpContext context)
{
Console.WriteLine ("hello chrome! json/version");
var resp_obj = new JObject ();
resp_obj ["Browser"] = "node.js/v9.11.1";
resp_obj ["Protocol-Version"] = "1.1";
var response = resp_obj.ToString ();
await context.Response.WriteAsync (response, new CancellationTokenSource ().Token);
}
async Task SendNodeList (HttpContext context)
{
Console.WriteLine ("hello chrome! json/list");
try {
var response = new JArray (JObject.FromObject (new {
description = "node.js instance",
devtoolsFrontendUrl = "chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=localhost:9300/91d87807-8a81-4f49-878c-a5604103b0a4",
faviconUrl = "https://nodejs.org/static/favicon.ico",
id = "91d87807-8a81-4f49-878c-a5604103b0a4",
title = "foo.js",
type = "node",
url = "file:///Users/kumpera/src/mono/sdks/wasm/dbg/foo.js",
webSocketDebuggerUrl = "ws://localhost:9300/91d87807-8a81-4f49-878c-a5604103b0a4"
})).ToString ();
Console.WriteLine ($"sending: {response}");
await context.Response.WriteAsync (response, new CancellationTokenSource ().Token);
} catch (Exception e) { Console.WriteLine (e); }
}
public async Task LaunchAndServe (ProcessStartInfo psi, HttpContext context, Func<string, string> extract_conn_url)
{
if (!context.WebSockets.IsWebSocketRequest) {
context.Response.StatusCode = 400;
return;
}
var tcs = new TaskCompletionSource<string> ();
var proc = Process.Start (psi);
try {
proc.ErrorDataReceived += (sender, e) => {
Console.WriteLine ($"stderr: {e.Data}");
var res = extract_conn_url (e.Data);
if (res != null)
tcs.TrySetResult (res);
};
proc.OutputDataReceived += (sender, e) => {
Console.WriteLine ($"stdout: {e.Data}");
};
proc.BeginErrorReadLine ();
proc.BeginOutputReadLine ();
if (await Task.WhenAny (tcs.Task, Task.Delay (2000)) != tcs.Task) {
Console.WriteLine ("Didnt get the con string after 2s.");
throw new Exception ("node.js timedout");
}
var con_str = await tcs.Task;
Console.WriteLine ($"lauching proxy for {con_str}");
var proxy = new MonoProxy ();
var browserUri = new Uri (con_str);
var ideSocket = await context.WebSockets.AcceptWebSocketAsync ();
await proxy.Run (browserUri, ideSocket);
Console.WriteLine("Proxy done");
} catch (Exception e) {
Console.WriteLine ("got exception {0}", e.GetType ().FullName);
} finally {
Console.WriteLine ("Proxy done");
proc.CancelErrorRead ();
proc.CancelOutputRead ();
proc.Kill ();
proc.WaitForExit ();
proc.Close ();
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure (IApplicationBuilder app, IHostingEnvironment env)
{
app.UseWebSockets ();
app.UseStaticFiles ();
var chromePath = configuration ["ChromePath"];
var filesPath = configuration ["AppPath"];
var pagePath = configuration ["PagePath"];
Console.WriteLine ("Chrome from: '{0}'", chromePath);
Console.WriteLine ("Files from: '{0}'", filesPath);
Console.WriteLine ("Using page : '{0}'", pagePath);
app.UseStaticFiles (new StaticFileOptions {
FileProvider = new PhysicalFileProvider (filesPath),
ServeUnknownFileTypes = true, //Cuz .wasm is not a known file type :cry:
RequestPath = ""
});
var psi = new ProcessStartInfo ();
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.Arguments = $"--headless --remote-debugging-port=9333 http://localhost:9300/{pagePath}";
psi.FileName = chromePath;
// psi.Arguments = $"--headless --disable-gpu --remote-debugging-port=9222 {appUrl}";
app.UseRouter (router => {
router.MapGet ("launch-chrome-and-connect", async context => {
Console.WriteLine ("New test request");
await LaunchAndServe (psi, context, str => {
//We wait for it as a signal that chrome finished launching
if (!str.StartsWith ("DevTools listening on ", StringComparison.Ordinal))
return null;
var client = new HttpClient ();
var res = client.GetStringAsync ("http://localhost:9333/json/list").Result;
// Console.WriteLine ("res is {0}", res);
var obj = JArray.Parse (res);
var wsURl = obj? [0]? ["webSocketDebuggerUrl"]?.Value<string> ();
// Console.WriteLine (">>> {0}", wsURl);
return wsURl;
});
});
});
if (configuration ["NodeApp"] != null) {
var nodeApp = configuration ["NodeApp"];
Console.WriteLine($"Doing the nodejs: {nodeApp}");
Console.WriteLine (Path.GetFullPath (nodeApp));
var nodeFullPath = Path.GetFullPath (nodeApp);
psi.Arguments = $"--inspect-brk=localhost:0 {nodeFullPath}";
psi.FileName = "node";
app.UseRouter (router => {
//Inspector API for using chrome devtools directly
router.MapGet ("json", SendNodeList);
router.MapGet ("json/list", SendNodeList);
router.MapGet ("json/version", SendNodeVersion);
router.MapGet ("launch-done-and-connect", async context => {
await LaunchAndServe (psi, context, str => {
if (str.StartsWith ("Debugger listening on", StringComparison.Ordinal))
return str.Substring (str.IndexOf ("ws://", StringComparison.Ordinal));
return null;
});
});
});
}
}
}
}
+33
View File
@@ -0,0 +1,33 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DebuggerTestSuite", "DebuggerTestSuite\DebuggerTestSuite.csproj", "{383A2AC1-C8F2-4366-B55C-A5DA6D46570D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProxyDriver", "ProxyDriver\ProxyDriver.csproj", "{8EDCAEE4-5BDB-4E90-BD5B-F28EAACFEAE1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.WebAssembly.DebuggerProxy", "Mono.WebAssembly.DebuggerProxy\Mono.WebAssembly.DebuggerProxy.csproj", "{BD275CF1-1196-438D-A4AD-C17316900165}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3CE8A3DB-ED03-4258-88CD-AD6B45A49294}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3CE8A3DB-ED03-4258-88CD-AD6B45A49294}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3CE8A3DB-ED03-4258-88CD-AD6B45A49294}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3CE8A3DB-ED03-4258-88CD-AD6B45A49294}.Release|Any CPU.Build.0 = Release|Any CPU
{383A2AC1-C8F2-4366-B55C-A5DA6D46570D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{383A2AC1-C8F2-4366-B55C-A5DA6D46570D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{383A2AC1-C8F2-4366-B55C-A5DA6D46570D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{383A2AC1-C8F2-4366-B55C-A5DA6D46570D}.Release|Any CPU.Build.0 = Release|Any CPU
{8EDCAEE4-5BDB-4E90-BD5B-F28EAACFEAE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8EDCAEE4-5BDB-4E90-BD5B-F28EAACFEAE1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8EDCAEE4-5BDB-4E90-BD5B-F28EAACFEAE1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8EDCAEE4-5BDB-4E90-BD5B-F28EAACFEAE1}.Release|Any CPU.Build.0 = Release|Any CPU
{BD275CF1-1196-438D-A4AD-C17316900165}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BD275CF1-1196-438D-A4AD-C17316900165}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BD275CF1-1196-438D-A4AD-C17316900165}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BD275CF1-1196-438D-A4AD-C17316900165}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
+12
View File
@@ -8,6 +8,7 @@
<textarea rows="10" cols="100" id="output"></textarea>
<br>
<button type="button" onclick="App.onClick()" id="button" disabled="true">SendEvent</button>
<button type="button" onclick="App.onClick2()" id="button2" disabled="true">SendEventAsync</button>
<br>
<script type='text/javascript'>
@@ -18,16 +19,27 @@
this.output.value = "res is " + res;
},
onClick2: function () {
this.output.value = "...";
var res = this.int_add_async (10, 20);
res.then (function(value) {
this.output.value = "res is " + value;
});
},
init: function () {
this.int_add = Module.mono_bind_static_method ("[sample] Math:IntAdd");
this.int_add_async = Module.mono_bind_static_method ("[sample] Math:AsyncAdd");
this.output = document.getElementById ("output");
this.button = document.getElementById ("button");
this.button2 = document.getElementById ("button2");
this.button.disabled = false;
this.button2.disabled = false;
console.log ("ready");
},
};
</script>
<script type="text/javascript" src="mono-config.js"></script>
<script type="text/javascript" src="runtime.js"></script>
<script async type="text/javascript" src="mono.js"></script>
</body>
+22
View File
@@ -0,0 +1,22 @@
<!doctype html>
<html lang="en-us">
<head>
</head>
<body>
<script type='text/javascript'>
var App = {
init: function () {
this.int_add = Module.mono_bind_static_method ("[debugger-test] Math:IntAdd");
console.log ("ready");
},
};
function invoke_add () {
return App.int_add (10, 20);
}
</script>
<script type="text/javascript" src="config.js"></script>
<script type="text/javascript" src="runtime.js"></script>
<script async type="text/javascript" src="mono.js"></script>
Stuff goes here
</body>
</html>
+23
View File
@@ -0,0 +1,23 @@
function inspect_object (o){
var r="";
for(var p in o) {
var t = typeof o[p];
r += "'" + p + "' => '" + t + "', ";
}
return r;
}
var App = {
init: function () {
console.log ("ready to run!");
var int_add = Module.mono_bind_static_method ("[debugger-test] Math:IntAdd");
var res = int_add (20, 30);
console.log("add is " + res);
}
};
var Module = require ("./mono.js");
var config = require ("./config.js")(Module);
require ("./runtime.js") (config, Module, App);
console.log ("done loading");
+17
View File
@@ -0,0 +1,17 @@
using System;
public class Math { //Only append content to this class as the test suite depends on line info
public static int IntAdd (int a, int b) {
int c = a + b;
int d = c + b;
int e = d + a;
return e;
}
public static int UseComplex () {
var complex = new Simple.Complex (10, "xx");
var res = complex.DoStuff ();
return res;
}
}
+19
View File
@@ -0,0 +1,19 @@
using System;
public class Misc { //Only append content to this class as the test suite depends on line info
public static int CreateObject (int foo, int bar) {
var f = new Fancy () {
Foo = foo,
Bar = bar,
};
Console.WriteLine ($"{f.Foo} {f.Bar}");
return f.Foo + f.Bar;
}
}
public class Fancy {
public int Foo;
public int Bar { get ; set; }
}
+8 -1
View File
@@ -4,7 +4,10 @@ namespace Simple {
public class Complex {
public int A { get; set; }
public string B { get; set; }
object c;
public object c;
private int zz;
public int D { get { return zz; }}
public int M { set { } }
public Complex (int a, string b) {
A = a;
@@ -31,4 +34,8 @@ namespace Simple {
return x;
}
}
public class Generic<T> {
int x;
T t;
}
}
+75 -3
View File
@@ -1,11 +1,17 @@
var MonoSupportLib = {
$MONO__postset: 'Module["pump_message"] = MONO.pump_message',
$MONO__postset: 'MONO.export_functions (Module);',
$MONO: {
pump_count: 0,
timeout_queue: [],
mono_wasm_runtime_is_ready : false,
pump_message: function () {
export_functions: function (module) {
module ["mono_pump_message"] = MONO.mono_pump_message.bind(MONO);
module ["mono_load_runtime_and_bcl"] = MONO.mono_load_runtime_and_bcl.bind(MONO);
},
mono_pump_message: function () {
if (!this.mono_background_exec)
this.mono_background_exec = Module.cwrap ("mono_background_exec", 'void', [ ]);
while (MONO.timeout_queue.length > 0) {
@@ -19,6 +25,7 @@ var MonoSupportLib = {
},
mono_wasm_get_call_stack: function() {
console.log(">>>mono_wasm_get_call_stack");
if (!this.mono_wasm_current_bp_id)
this.mono_wasm_current_bp_id = Module.cwrap ("mono_wasm_current_bp_id", 'number', [ ]);
if (!this.mono_wasm_enum_frames)
@@ -37,6 +44,7 @@ var MonoSupportLib = {
},
mono_wasm_get_variables: function(scope, var_list) {
console.log(">>>mono_wasm_get_variables " + scope);
if (!this.mono_wasm_get_var_info)
this.mono_wasm_get_var_info = Module.cwrap ("mono_wasm_get_var_info", 'void', [ 'number', 'number']);
@@ -51,6 +59,37 @@ var MonoSupportLib = {
return res;
},
mono_wasm_get_object_fields: function (object_id, requested_depth) {
console.log(">>>mono_wasm_get_object_fields id: " + object_id + " depth: " + requested_depth);
if (!this.mono_wasm_get_obj_info)
this.mono_wasm_get_obj_info = Module.cwrap ("mono_wasm_get_obj_info", 'void', [ 'number', 'number']);
this.var_info = [];
this.mono_wasm_get_obj_info (object_id, requested_depth);
var res = {
fqn: this.cur_obj_fqn,
fields: this.var_info
};
this.var_info = []
this.cur_obj_fqn = null;
return res;
},
mono_wasm_evaluate_property: function(object_id, requested_depth, property_name) {
console.log(">>>mono_wasm_evaluate_property id: " + object_id + " depth: " + requested_depth + " prop: '" + property_name + "'");
if (!this.mono_wasm_get_prop_value)
this.mono_wasm_get_prop_value = Module.cwrap ("mono_wasm_get_prop_value", 'void', [ 'number', 'number', 'string']);
this.var_info = [];
this.mono_wasm_get_prop_value (object_id, requested_depth, property_name);
var res = this.var_info;
this.var_info = []
return res;
},
mono_wasm_start_single_stepping: function (kind) {
console.log (">> mono_wasm_start_single_stepping " + kind);
if (!this.mono_wasm_setup_single_step)
@@ -66,6 +105,7 @@ var MonoSupportLib = {
},
mono_wasm_set_breakpoint: function (assembly, method_token, il_offset) {
console.log(">>>mono_wasm_set_breakpoint " + assembly + "::" + method_token + ":" + il_offset);
if (!this.mono_wasm_set_bp)
this.mono_wasm_set_bp = Module.cwrap ('mono_wasm_set_breakpoint', 'number', ['string', 'number', 'number']);
@@ -73,6 +113,7 @@ var MonoSupportLib = {
},
mono_wasm_remove_breakpoint: function (breakpoint_id) {
console.log(">>>mono_wasm_remove_breakpoint " + breakpoint_id);
if (!this.mono_wasm_del_bp)
this.mono_wasm_del_bp = Module.cwrap ('mono_wasm_remove_breakpoint', 'number', ['number']);
@@ -179,7 +220,8 @@ var MonoSupportLib = {
},
mono_wasm_clear_all_breakpoints: function() {
if (this.mono_clear_bps)
console.log(">>>mono_wasm_clear_all_breakpoints");
if (!this.mono_clear_bps)
this.mono_clear_bps = Module.cwrap ('mono_wasm_clear_all_breakpoints', 'void', [ ]);
this.mono_clear_bps ();
},
@@ -249,6 +291,36 @@ var MonoSupportLib = {
}
},
mono_wasm_set_last_var_name: function (var_name) {
MONO.var_info [MONO.var_info.length - 1]["name"] = Module.UTF8ToString (var_name);
},
mono_wasm_set_object_fqn: function (obj_fqn) {
MONO.cur_obj_fqn = Module.UTF8ToString (obj_fqn);
},
mono_wasm_begin_object: function (type_name, obj_id) {
if (!MONO.current_dbg_obj) {
MONO.current_dbg_obj = {
value: {
type: "object",
className: Module.UTF8ToString (type_name),
description: Module.UTF8ToString (type_name),
objectId: "dotnet:objid:" + obj_id,
}
};
} else {
throw "Can't handle nested objects!";
}
},
mono_wasm_end_object: function () {
if (!MONO.current_dbg_obj)
throw "Can't finish an object that is null!";
MONO.var_info.push (MONO.current_dbg_obj);
MONO.current_dbg_obj = null;
},
mono_wasm_add_frame: function(il, method, name) {
MONO.active_frames.push( {
+26 -11
View File
@@ -9,6 +9,7 @@ class Driver {
static bool enable_debug, enable_linker;
static string app_prefix, framework_prefix, bcl_prefix, bcl_facades_prefix, out_prefix;
static HashSet<string> asm_list = new HashSet<string> ();
static HashSet<string> assemblies_with_dbg_info = new HashSet<string> ();
static List<string> file_list = new List<string> ();
static List<string> assembly_names = new List<string> ();
@@ -114,7 +115,7 @@ class Driver {
throw new Exception ($"Could not resolve {asm_name}");
}
static void Import (string ra, AssemblyKind kind) {
void Import (string ra, AssemblyKind kind) {
ReaderParameters rp = new ReaderParameters();
bool add_pdb = enable_debug && File.Exists (Path.ChangeExtension (ra, "pdb"));
if (add_pdb) {
@@ -130,8 +131,10 @@ class Driver {
assembly_names.Add (image.Assembly.Name.Name);
Debug ($"Processing {ra} debug {add_pdb}");
if (add_pdb && kind == AssemblyKind.User)
if (add_pdb && kind == AssemblyKind.User) {
file_list.Add (Path.ChangeExtension (ra, "pdb"));
assemblies_with_dbg_info.Add (ra);
}
foreach (var ar in image.AssemblyReferences) {
var resolve = Resolve (ar.Name, out kind);
@@ -171,7 +174,6 @@ class Driver {
enum CopyType
{
Default,
Always,
IfNewer
}
@@ -194,8 +196,8 @@ class Driver {
var runtimeTemplate = "runtime.js";
var assets = new List<string> ();
var profilers = new List<string> ();
var copyTypeParm = "default";
var copyType = CopyType.Default;
var copyTypeParam = "";
var copyType = CopyType.IfNewer;
var p = new OptionSet () {
{ "debug", s => enable_debug = true },
@@ -213,7 +215,7 @@ class Driver {
{ "template=", s => runtimeTemplate = s },
{ "asset=", s => assets.Add(s) },
{ "profile=", s => profilers.Add (s) },
{ "copy=", s => copyTypeParm = s },
{ "copy=", s => copyTypeParam = s },
{ "help", s => print_usage = true },
};
@@ -227,7 +229,7 @@ class Driver {
return;
}
if (!Enum.TryParse(copyTypeParm, true, out copyType)) {
if (copyTypeParam.Length > 0 && !Enum.TryParse(copyTypeParam, true, out copyType)) {
Console.WriteLine("Invalid copy value");
Usage ();
return;
@@ -422,20 +424,34 @@ class Driver {
foreach (var assembly in asm_list) {
string filename = Path.GetFileName (assembly);
var filename_noext = Path.GetFileNameWithoutExtension (filename);
string filename_pdb = Path.ChangeExtension (filename, "pdb");
var source_file_path = Path.GetFullPath (assembly);
var source_file_path_pdb = Path.ChangeExtension (source_file_path, "pdb");
string infile = "";
string infile_pdb = "";
bool emit_pdb = assemblies_with_dbg_info.Contains (source_file_path);
if (enable_linker) {
linker_infiles += $" $builddir/linker-in/{filename}";
linker_ofiles += $" $builddir/linker-out/{filename}";
infile = $"$builddir/linker-out/{filename}";
ninja.WriteLine ($"build $builddir/linker-in/{filename}: cpifdiff {source_file_path}");
if (emit_pdb)
throw new Exception ("TODO");
} else {
infile = $"$builddir/{filename}";
ninja.WriteLine ($"build $builddir/{filename}: cpifdiff {source_file_path}");
if (emit_pdb) {
ninja.WriteLine ($"build $builddir/{filename_pdb}: cpifdiff {source_file_path_pdb}");
infile_pdb = $"$builddir/{filename_pdb}";
}
}
ninja.WriteLine ($"build $appdir/$deploy_prefix/{filename}: cpifdiff {infile}");
if (emit_pdb)
ninja.WriteLine ($"build $appdir/$deploy_prefix/{filename_pdb}: cpifdiff {infile_pdb}");
if (enable_aot) {
string mono_path = enable_linker ? "$builddir/linker-out" : "$builddir";
@@ -485,7 +501,7 @@ class Driver {
switch (copyType)
{
case CopyType.Always:
File.Copy(sourceFileName, destFileName, true);
File.Copy(sourceFileName, destFileName, overwrite: true);
break;
case CopyType.IfNewer:
if (!File.Exists(destFileName))
@@ -498,14 +514,13 @@ class Driver {
var dstInfo = new FileInfo (destFileName);
if (srcInfo.LastWriteTime.Ticks > dstInfo.LastWriteTime.Ticks || srcInfo.Length > dstInfo.Length)
File.Copy(sourceFileName, destFileName, true);
File.Copy(sourceFileName, destFileName, overwrite: true);
else
Console.WriteLine($" skipping: {sourceFileName}");
}
break;
default:
File.Copy(sourceFileName, destFileName);
break;
throw new Exception ($"Invalid CopyFile mode {copyType}");
}
}
+1 -1
View File
@@ -258,7 +258,7 @@ var App = {
if (res == "SUCCESS") {
while (send_message ("pump-test", testArguments [i]) != "DONE")
{
Module.pump_message ();
Module.mono_pump_message ();
print ("|");
}
print ("\nDONE")
+1 -1
View File
@@ -1,7 +1,7 @@
var Module = {
onRuntimeInitialized: function () {
MONO.mono_load_runtime_and_bcl (
Module.mono_load_runtime_and_bcl (
config.vfs_prefix,
config.deploy_prefix,
config.enable_debugging,
+45 -7
View File
@@ -2,27 +2,65 @@ using System;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using WebAssembly;
using WebAssembly.Net.Http.HttpClient;
public class Math {
public static int IntAdd (int a, int b) {
var cp = new Simple.Complex (10, "hello");
int c = a + b;
int d = c + b;
int e = d + a;
int f = b - 2;
e += cp.DoStuff ();
Func<int> x = () => {
int e = c + d;
return e;
};
return e;
int tmp = x ();
Func<int> y= () => {
int k = tmp + d + f;
return k;
};
return y ();
}
public int First (int[] x) {
return x.FirstOrDefault ();
public async Task<int> AsyncAdd (int a, int b) {
Console.WriteLine ("Begin2");
int c = a + b;
await Task.Delay (100);
Console.WriteLine ("Waited");
return c;
}
}
class Test: TestBase {
public int pubField = 123;
public object pubField2;
public int PubProperty { get; set; }
private int privField;
private object PrivProperty { get; set; }
public Test () {
PubProperty = 10;
privField = 20;
pubField = 30;
pubField2 = 40;
PrivProperty = "this is private";
}
public string ComputedProperty {
get => "This string is generated!";
}
}
class TestBase: BaseBase {
private int privBaseField;
}
class BaseBase {
public int field;
}
namespace GeoLocation
{
class Program