Compare commits

...
58 Commits
Author SHA1 Message Date
Ankit Jain 86b78b7d19 [3.2-wasm][wasm][debugger] Relocate tests (#19787)
* [wasm][debugger][tests] Move the test files to `tests/debugger`

- Also, rename `class Math` to `class SampleMath` in `sample.cs`,
to allow building sample.dll, with all the tests added.

* [wasm][debugger][tests] Add back missing dependency

* [wasm][debugger][tests] move *datetime-test.cs to `tests/debugger`

* [wasm][debugger][tests] Move CFO test to debugger-cfo-test.cs
2020-05-15 14:48:26 -04:00
Tammy Qiu d46a972c3b Merge pull request #19734 from tqiu8/locale-test
[wasm][debugger][tests] Add locale tests for datetime
2020-05-11 15:29:50 -04:00
monojenkinsandLarry Ewing 57dcba253c [3.2-wasm] [wasm][debugger] Only send resolved events on load (#19739)
* [wasm][debugger] Only send resolved events on load

* Add the request to the context after potentially loading the store

* improve the resolution logic

Co-authored-by: Larry Ewing <[email protected]>
2020-05-11 10:44:31 -05:00
tqiu8 e4acd81888 incorporate PR feedback & reference issue number for disabled locales 2020-05-08 12:00:47 -04:00
tqiu8 c6bd1ac7fa [wasm][debugger][tests] Add locale tests for datetime 2020-05-07 14:16:06 -04:00
Tammy Qiu 1a6e64a938 Merge pull request #19718 from tqiu8/breakpoint-tests
[wasm][debugger][tests] Add tests for multiple breakpoints inline
2020-05-05 18:14:54 -04:00
tqiu8 feb9163b26 [wasm][debugger][tests] Combine two tests in one using [Theory] 2020-05-05 18:14:25 -04:00
tqiu8 1b697209f5 [wasm][debugger][tests] More descriptive test name 2020-05-05 17:57:42 -04:00
tqiu8 40ca9b2f37 [wasm][debugger][tests] Update CheckBreakpoint with more descriptive name and use CheckLocation 2020-05-05 17:51:55 -04:00
tqiu8 0d532de801 [wasm][debugger][tests] add tests for multiple breakpoints 2020-05-05 17:28:25 -04:00
monojenkinsandLarry Ewing 7569ee7b36 [wasm][debugger] Add tests for floating common types (#19717)
Co-authored-by: Larry Ewing <[email protected]>
2020-05-05 13:56:00 -05:00
Larry Ewing fbc81c503e [3.2-wasm][wasm][debugger] Backport of #19688 (#19716)
* [wasm][debugger] Only choose the best match when mutiple locations are found

* OrderBy column just to be certain

* Add tests for the JS breakpoint behavior that we are duplicating

* remove accidentally disabled code
2020-05-05 13:55:15 -05:00
monojenkinsandBrzVlad 8bcfbc80f3 [interp] Move label outside of main loop (#19708)
Wasm has control flow limitations which don't go well with gotos. Move label outside of main loop because it translates to very poor wasm code. Other gotos don't seem to negatively impact instruction dispatch code, so leave them alone, for now ..

Co-authored-by: BrzVlad <[email protected]>
2020-05-05 12:36:08 -05:00
monojenkinsandAnkit Jain 5dc5126323 [3.2-wasm] [wasm][debugger][tests] Split tests into separate files (#19715)
* [wasm][debugger][tests] Move helper methods to base class

* [wasm][debugger][tests] Extract EvaluateOnCallFrame tests to new file

* [wasm][debugger][tests] Extract Array tests to a new file

* [wasm][debugger][tests] Extract CallFunctionOn tests to a new file

* [wasm][debugger][tests] Extract Delegate tests to a new file

* [wasm][debugger] Don't inherit from another test class

.. as that ends up running all the tests of the base class too.

* [wasm][debugger][tests] Improve retries in TestHarnessStartup

Sometimes `/json/list` seems to return an empty array (`[ ]`). Treat
that also as a case for retry.

* [wasm][debugger][tests] Bump timeout from 2s to 5s

* [wasm][debugger][tests] Launch chrome in incognito mode

* debugging

* [wasm][debugger] TestHarnessStartup - don't share `ProcessStartInfo`

.. instances. Instead, create one for every use.
We seem to run into cases where the `get_Environment` is modifying it's
`_environmentVariables` field, concurrently from multiple threads,
causing exceptions like:

```
System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.Diagnostics.Process.CreateEnvp(ProcessStartInfo psi)
   at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at WebAssembly.Net.Debugging.TestHarnessStartup.LaunchAndServe(ProcessStartInfo psi, HttpContext context, Func`2 extract_conn_url) in /Users/radical/dev/w1/sdks/wasm/ProxyDriver/TestHarnessStartup.cs:line 82
   at WebAssembly.Net.Debugging.TestHarnessStartup.<>c__DisplayClass10_0.<<Configure>b__1>d.MoveNext() in /Users/radical/dev/w1/sdks/wasm/ProxyDriver/TestHarnessStartup.cs:line 167
```

* [wasm][debugger] Fix regression in debug.html

Fixes https://github.com/mono/mono/issues/19653 .

Co-authored-by: Ankit Jain <[email protected]>
2020-05-05 12:24:46 -05:00
monojenkinsandLarry Ewing f6e60534ff [wasm][debugger] Fix type argument (#19710)
Co-authored-by: Larry Ewing <[email protected]>
2020-05-05 11:36:13 -05:00
Alexander Köplinger 6fd32d873a [3.2-wasm][ci] Run only wasm CI legs (#19711) 2020-05-05 17:57:24 +02:00
monojenkinsandAnkit Jain cc6d4bf6cf [3.2-wasm] [wasm][debugger] Fix evaluateOnCallFrame for valuetype locals (#19644)
* [wasm][debugger] Fix `evaluateOnCallFrame` for valuetype locals

.. including generic, and async methods.

* [wasm][debugger] Remove some debug spew

(cherry picked from commit 2e042925b95a2e3eba693525a5c1e495cca47f2f)

Co-authored-by: Ankit Jain <[email protected]>
2020-04-28 11:06:08 -05:00
Larry EwingandZoltan Varga c5f62a7e7d [3.2-wasm] Backport wasm index fix (#19636)
* [corlib] Fix String.Replace (..., StringComparison.InvariantCultureIgnoreCase).

Fixes https://github.com/mono/mono/issues/18978.

* Disable the test here

Co-authored-by: Zoltan Varga <[email protected]>
2020-04-22 17:32:04 -05:00
monojenkinsandZoltan Varga af98855016 [3.2-wasm] [wasm] Reenable the managed collation code, link it out by default, add a packager option to enable it. (#19608)
* [wasm] Reenable the managed collation code, link it out by default, add a packager option to enable it.

* Disable some xunit tests which fail because the test runner can't handle the [SkipOnTargetFramework(TargetFrameworkMonikers.Mono)] attribute.

* [csproj] Update project files

Co-authored-by: Zoltan Varga <[email protected]>
2020-04-22 14:20:34 -05:00
monojenkinsandMaxim Lipnin a0a972cabf [3.2-wasm] [wasm] Add throwing PNSE to where currently disabled tests throw something different (#19633)
* Add throwing PNSE to where currently disabled tests throw something different

* Add try-catch + PNSE to public SslStream ctor in case of WASM

Co-authored-by: Maxim Lipnin <[email protected]>
2020-04-22 13:47:27 -05:00
monojenkinsandAnkit Jain fe5a9ecec8 [3.2-wasm] [wasm][debugger] Fix enumerating for this on valuetypes (#19630)
* [wasm][debugger] `mono_wasm_call_function_on` - remove unncessary

.. parameter, since it is already present in the `args` object.

* [wasm] MonoProxy - convert cfo calls to MonoCommands

* [wasm][debugger] Fix enumerating `this` properties for a valuetype

* [wasm][debugger] `evaluateOnCallFrame` - fix `this` for valuetypes

* [wasm][debugger] Remove MonoCommands no longer used

* [wasm][debugger] Fix showing the name for generic methods

- We were using `method.Name` from Cecil, but that we want to the name
with the type arguments for the generic instance.

Co-authored-by: Ankit Jain <[email protected]>
2020-04-22 13:38:16 -05:00
monojenkinsandZoltan Varga 1bb2a7d171 Bump linker to the tip of mono-2020-02. (#19607)
Co-authored-by: Zoltan Varga <[email protected]>
2020-04-22 09:36:52 -05:00
Larry Ewing 70ff920a89 [wasm-3.2] Fix webdriver initialization (#19617) 2020-04-21 13:31:17 -05:00
monojenkinsandLarry Ewing 0122b3e0eb [3.2-wasm] [wasm][debugger] Fix command response handling (#19615)
* [wasm][debugger] send failed evaluations to the browser

Make sure that we allways either send a single result or return
false from Accept Command to ensure that we don't leave
messages spinning.

Co-authored-by: Larry Ewing <[email protected]>
2020-04-21 11:56:01 -05:00
7f581f1398 [3.2-wasm] [wasm][debugger] Support array expansion in VS via callFunctionOn (#19606)
* [wasm][debugger] Move `getProperties` implementation to `library_mono.js`,

.. from `MonoProxy.cs`. MonoProxy essentially just forwards the
request to `library_mono.js` now.

* [wasm][debugger] Add `length` info array details

- update tests to track the change

* [wasm][debugger][tests] Simplify some of the helper methods

* [wasm][debuggger] Implement `Runtime.callFunctionOn`

- This was prompted by vscode/vs requiring this for array expansion.
- It runs a given js function string, on a given object id.
- We handle the case for dotnet object ids.

Implementation:

- We build a proxy object that reflects the details of the real dotnet object/array
- And run the js function on that proxy object

- Then if `returnByValue` was requested, the result is returned as-is
- Else we cache that object, with a new special object id (`dotnet:cfo_res:..`),
  and return that id in the response.

- Subsequently, we would get `Runtime.getProperties` request on this new object id
- And a `Runtime.releaseObject` request, to free that function result.

- All this is handled currently

Tests:

- A few tests were added which invoke `callFunctionOn`, on JS objects, and checks the result
  - And the same checks are performed on equivalent dotnet objects, with the same js function
  - This should help stay in sync with what we think `callFunctionOn` should work as

  - These tests have an additional parameter - `roundtrip`, which calls a simple function

	`function () { return this; }`

    .. on a dotnet object, and gets the result object id. If `roundtrip == true`, then it
    runs that same function on the result object, and gets a new result object id. And the
    tests run their checks on that.

    - this helps to check that outside of the proxy, the result object behaves same as any
      other dotnet object.

- Also, most of the tests were modified to support an additional mode (`use_cfo`).
  - With this, whenever a test wants to run `Runtime.getProperties on an object, we pass that
    object through the earlier "identity" function, and then run `getProperties` on that
    resultant object.

  - This helps to take advantage most of the existing tests, and use them for `callFunctionOn`
    testing too, by ensuring that the results of CFO returns results same as any other object.

Fixes https://github.com/mono/mono/issues/19229, https://github.com/mono/mono/issues/19531

* Apply suggestions from code review

Applying suggestions to start CI

* Update sdks/wasm/src/library_mono.js

Co-authored-by: Ankit Jain <[email protected]>
Co-authored-by: Larry Ewing <[email protected]>
2020-04-21 11:32:04 -05:00
monojenkinsandLarry Ewing ae8e4b5b04 [3.2-wasm] [wasm][debugger] Add an option to clear navigator.webdriver on attach (#19592)
* [wasm][debugger] Add an option to clear navigator.webdriver on attach

* Pass the flag when it is useful

Co-authored-by: Larry Ewing <[email protected]>
2020-04-20 13:04:15 -05:00
monojenkinsandKenneth Pouncey c8cbcaad0d [wasm][sdk][nuget] Bump version. (#19585)
Co-authored-by: Kenneth Pouncey <[email protected]>
2020-04-18 00:50:30 -05:00
monojenkinsandLarry Ewing 91a8312033 [wasm][debugger] Add comment about embedded pdbs and fix old regression (#19582)
With embedded pdbs we have to try to load symbols even when the
pdb is missing then handle ArgumentException if there is no embedded
pdb.  This restores the intended error path and added an explanation
while still logging unexpected errors

Co-authored-by: Larry Ewing <[email protected]>
2020-04-17 17:42:57 -05:00
Larry EwingandAnkit Jain d76afcc147 [wasm][debugger] Show pointer type+address (#19537) (#19581)
* [wasm][debugger] Simplify the interface between debugger.c and

.. library_mono.js .

* [wasm][debugger] Show pointer type+address

* [wasm][debugger] Address review feedback

* [wasm][debugger] Small cleanups, from review feedback

* [wasm][debugger] declare mono_wasm_add_typed_value as extern

Co-authored-by: Ankit Jain <[email protected]>
2020-04-17 16:51:24 -05:00
Larry EwingandAnkit Jain fdf009e4d1 [wasm][debugger] Show signature for delegate, or target, if available… (#19535) (#19579)
* [wasm][debugger] Show signature for delegate, or target, if available (#19505)

* [wasm][debugger] Show signature for delegate, or target, if available

- As object properties, we return a `Target` which has the signature of
the delegate target.

Fixes https://github.com/mono/mono/issues/19382

* [wasm][debugger] Some tidying up

* [wasm][debugger] Remove unused `sig_desc`

* [wasm][debugger] Simplify code, avoid extra allocations

.. as suggested by @lewing

(cherry picked from commit 4eca12e794)

* [wasm][debugger] Fix tests broken because unused vars are not null

.. anymore, which is because we disabled optimizations in the
interpreter when debugging.

* [wasm][debugger][tests] Add tests to also check delegates in previous

.. frames.

* [wasm][debugger] Disable a test that tried to look at previous async

.. frames. This just happened to work. Currently, the trace has details
of the async machinery, instead of one reflecting what it might have
looked like for a non-async case. So, we can't reliably find the
previous method to inspect it's locals.

* [wasm][debugger] Fix test

Co-authored-by: Ankit Jain <[email protected]>
2020-04-17 16:31:08 -05:00
monojenkinsandLarry Ewing e630444dc6 [wasm][debugger] Always send the remove breakpoint command to the browser too (#19578)
Co-authored-by: Larry Ewing <[email protected]>
2020-04-17 16:09:18 -05:00
Larry Ewing f585a341d0 [wasm][debugger] Handle multi-doc methods and multiple results for breakpoints (#19449) (#19577)
* [wasm][debugger] Rework source loading

Add logic to support embedded sources and
add all the documents from multi-doc methods

Add logic to check source hashes against
pdb hash.

* [wasm][debugger] Fix breakpoints on delegates

Only add methods to a source once by RID

When column is != 0 specified the fronted only wants results
that match that column exactly.

* Allow checking pdb hash and remove source cache

* Fixup typesByName merge
2020-04-17 16:04:58 -05:00
Larry EwingandZoltan Varga 56ba392b3b [wasm] Debugger test improvements. (#19499) (#19573)
* Disable the Loaded: messages, they are not very useful.

* Add a Dotnet-test.setBreakpointByMethod protocol extensions to the proxy to set breakpoints in specific methods during testing.

* Add a new sample debugger test using the setBreakpointByMethod API.

* Remove some unrelated changes.

* Restore logging.

* Disable a log message which is printed when a pdb file is missing.

Co-authored-by: Zoltan Varga <[email protected]>
2020-04-17 00:49:36 -05:00
monojenkinsandLarry Ewing 1a6d1100c4 [wasm][debugger] Fix typo and silence output (#19567)
Co-authored-by: Larry Ewing <[email protected]>
2020-04-16 18:58:17 -05:00
monojenkinsandLarry Ewing 41a4f60bee Change OSPlatform for wasm to "BROWSER" rather than "WEBASSEMBLY" (#19568)
Following the guidance in https://github.com/dotnet/runtime/issues/33328
Change OSPlatform to BROWSER for wasm runtimeArchitecture.

Co-authored-by: Larry Ewing <[email protected]>
2020-04-16 18:58:01 -05:00
monojenkinsandvargaz c6fbfa6726 [wasm] Disable the AOT cache check on wasm as well. (#19553)
Co-authored-by: vargaz <[email protected]>
2020-04-16 14:27:34 -05:00
monojenkinsandLarry Ewing 84d12a33a0 [wasm] force set a local when running debugger tests (#19552)
Co-authored-by: Larry Ewing <[email protected]>
2020-04-15 14:45:24 -05:00
monojenkinsandLarry Ewing 4dba91e7f5 [wasm] Use browser style lang (#19551)
Co-authored-by: Larry Ewing <[email protected]>
2020-04-15 14:45:12 -05:00
monojenkinsandAnkit Jain c66e702ba5 [wasm][debugger] Show signature for delegate, or target, if available (#19505) (#19536)
* [wasm][debugger] Show signature for delegate, or target, if available

- As object properties, we return a `Target` which has the signature of
the delegate target.

Fixes https://github.com/mono/mono/issues/19382

* [wasm][debugger] Some tidying up

* [wasm][debugger] Remove unused `sig_desc`

* [wasm][debugger] Simplify code, avoid extra allocations

.. as suggested by @lewing

(cherry picked from commit 4eca12e794)

Co-authored-by: Ankit Jain <[email protected]>
2020-04-14 02:26:17 -04:00
monojenkinsandtqiu8 07d1f6452e [wasm] Add readme to package update scripts (#19533)
Co-authored-by: tqiu8 <[email protected]>
2020-04-13 19:59:42 -05:00
monojenkinsandAnkit Jain 3926eae609 [3.2-wasm] [wasm][debugger] Improve some valuetype visualization (#19532)
* [wasm][debugger] Fix up `value.description` for local vars too

- Local vars, when being enumerated in `mono_wasm_get_variables` don't
have an associated `name`, and so `_fixup_name_value_objects`
*incorrectly* ends up not fixing up the `value.description` field for
them.

* [wasm][debugger] For some types, use `ToString()` for their ..

.. `description`.

- `System.DateTime`
- `System.DateTimeOffset`
- `System.Decimal`
- `System.TimeSpan`
- `System.Guid`

* [wasm][debugger] Invoke all property getters, for some types

- `System.DateTime`
- `System.DateTimeOffset`
- `System.TimeSpan`

* [wasm][debugger] Show char symbol along with the code

Fixes https://github.com/mono/mono/issues/19381

* [wasm][debugger] Fix DateTime tests, don't use hardcoded strings for

.. description. Instead, use a `DateTime` object in the test to create
the expected string for the test. This should ensure that the expected
and actual were created in the same environment.

* [wasm][debugger] Special case `System.Guid` to use

.. `mono_guid_to_string`, instead of calling `ToString()` on it.

* [wasm][debugger] Don't box valuetypes for calling `ToString()`

Co-authored by @vargaz .

* [wasm][debugger] `System.Guid` is special-cased, so remove it from the

.. allowed list.

* [wasm][debugger] simple cleanup

Co-authored-by: Ankit Jain <[email protected]>
2020-04-13 19:59:15 -05:00
monojenkinsandLarry Ewing 4bfd29e820 [wasm][debugger] explicitly pass --lang=en_US for debugger tests (#19530)
Co-authored-by: Larry Ewing <[email protected]>
2020-04-13 17:37:49 -05:00
monojenkinsandMartin Baulig f2b7b0000d Bump CoreFX to pickup https://github.com/mono/corefx/pull/397. (#19526)
Co-authored-by: Martin Baulig <[email protected]>
2020-04-13 20:15:21 +02:00
monojenkinsandKenneth Pouncey 4f156f6e32 [wasm][browser][tests] Generate sdk version in global.json file automatically. (#19527)
Co-authored-by: Kenneth Pouncey <[email protected]>
2020-04-13 12:29:56 -05:00
monojenkinsandZoltan Varga 8b290302b2 [wasm] Remove .stamp-build-debugger-test-app, the app can always be built. (#19524)
Co-authored-by: Zoltan Varga <[email protected]>
2020-04-13 11:51:11 -05:00
monojenkinsandZoltan Varga 3b761deb75 [3.2-wasm] [wasm] Disable interpreter optimizations when debugging. (#19516)
* [wasm] Disable interpreter optimizations when debugging.

* Fix tests.

Co-authored-by: Zoltan Varga <[email protected]>
2020-04-11 03:10:31 -05:00
monojenkinsandtqiu8 37221f2c32 add powershell and bash scripts for replacing default webassembly nuget packages from link or path (#19515)
Co-authored-by: tqiu8 <[email protected]>
2020-04-11 03:05:11 -05:00
monojenkinsandKenneth Pouncey 31c66244bd [3.2-wasm] [wasm][bcl] Handle correctly backslash in file name (#19514)
* [wasm][bcl] Handle correctly backslash in file name

- Modify IO file to assign backslash to alternate directory separator by default
- Add tests for issue https://github.com/mono/mono/issues/18933

* [wasm][tests] Skip two tests for wasm

- After internal discussions decided to skip these two tests on wasm

   1. GetDirectories_Backslash
   1. GetFiles_Backslash

* [wasm][tests] PathIsRooted tests failing

- skip subtest #9 if WASM
- To fix issue https://github.com/mono/mono/issues/18933 we set the AltDirectorySeparatorChar as well.  This causes the `Assert.IsTrue (!Path.IsPathRooted ("\\"), "IsPathRooted #09");` to fail. Path.IsPathFullyQualified Method handles paths that use both the DirectorySeparatorChar and the AltDirectorySeparatorChar characters.

* [wasm][tests] PathIsRooted tests failing

- skip if WASM

Co-authored-by: Kenneth Pouncey <[email protected]>
2020-04-11 02:58:37 -05:00
monojenkinsandLarry Ewing f9771388ab [3.2-wasm] [wasm][debugger] Wasm debug log level (#19512)
* [wasm][debugging] pass enable_debugging as debug engine log level

enable_debugging was already an int, with this change log_level
will remain at 1 by default but passing -1 will disable the log
spew

* Change the default debug level of 'Failed to lookup sequence point'

Co-authored-by: Larry Ewing <[email protected]>
2020-04-10 18:13:56 -05:00
monojenkinsandKenneth Pouncey 2925dcdc83 [wasm][bcl][zoneinfo] Fix local zone info marshaling (#19511)
- Correctly marshal Intl.DateTimeFormat().resolvedOptions().timeZone information

Co-authored-by: Kenneth Pouncey <[email protected]>
2020-04-10 18:13:40 -05:00
Larry Ewing d351fa1cfe [3.2-wasm][ci] Use path not name (#19513) 2020-04-10 16:59:57 -05:00
Larry Ewing 7055ff9b78 [3.2-wasm][ci] Fix typo in groovy 2020-04-10 15:36:59 -05:00
monojenkinsandLarry Ewing 08481dc20b [wasm][ci] Always build and package wasm (#19509)
Co-authored-by: Larry Ewing <[email protected]>
2020-04-10 14:53:47 -05:00
Larry Ewing 72ac1d024d Upload the zip in sdks/wasm (#19506) 2020-04-10 12:30:26 -05:00
monojenkinsandZoltan Varga a475a78a71 [runtime] Fix Type.GetTypeCode () for generic enums. (#19471)
Fixes https://github.com/mono/mono/issues/17735.

Co-authored-by: Zoltan Varga <[email protected]>
2020-04-08 12:01:16 -05:00
monojenkinsandPranav K 92e0af1500 [3.2-wasm] Produce System.Net.Http.WebAssemblyHttpHandler (#19474)
* Produce System.Net.Http.WebAssemblyMessageHandler

* Branding changes for WebAssembly.Net.Http -> System.Net.Http.WebAssemblyMessageHandler

* Change how fetch options are configured

* Fixup tests

* More fixup

* Update submodule

Co-authored-by: Pranav K <[email protected]>
2020-04-08 10:58:30 -05:00
Larry EwingandThays Grazia 4598104765 [wasm][debugger] Improving evaluate expression implementation (#19444) (#19469)
* - Adding tests to evaluate expression
- Adding a cache to local vars and object properties
- Fixing evaluate expressions like "this.a"
- Fixing evaluate expressions like "d + d"

Co-authored-by: Thays Grazia <[email protected]>
2020-04-07 17:25:02 -05:00
Larry Ewing c68c7cebe3 [sdks] Disable all sdk builds for this 3.2-wasm release branch
Disable the other sdks and enable the wask sdk for this branch
2020-04-07 15:13:29 -05:00
88 changed files with 5433 additions and 2483 deletions

No files matched your search

+1 -1
+1 -1
+1 -1
View File
@@ -38,7 +38,7 @@ LIB_MCS_FLAGS += -d:XAMARIN_MODERN
endif
ifeq (wasm,$(PROFILE))
API_BIN_REFS := WebAssembly.Net.Http
API_BIN_REFS := System.Net.Http.WebAssemblyHttpHandler
endif
TEST_LIB_REFS = System System.Core
@@ -1407,9 +1407,9 @@
</Reference>
</ItemGroup>
<ItemGroup Condition=" '$(Platform)' == 'wasm' ">
<Reference Include="./../../../external/binary-reference-assemblies/build/monowasm/WebAssembly.Net.Http.dll">
<Reference Include="./../../../external/binary-reference-assemblies/build/monowasm/System.Net.Http.WebAssemblyHttpHandler.dll">
<SpecificVersion>False</SpecificVersion>
<HintPath>./../../../external/binary-reference-assemblies/build/monowasm/WebAssembly.Net.Http.dll</HintPath>
<HintPath>./../../../external/binary-reference-assemblies/build/monowasm/System.Net.Http.WebAssemblyHttpHandler.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
@@ -2,6 +2,6 @@ namespace System.Net.Http
{
public partial class HttpClient
{
static HttpMessageHandler CreateDefaultHandler () => new WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler ();
static HttpMessageHandler CreateDefaultHandler () => new System.Net.Http.WebAssemblyHttpHandler ();
}
}
@@ -13,11 +13,11 @@ namespace System.Net.Http
{
public class HttpClientHandler : HttpMessageHandler
{
WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler wasmHandler;
System.Net.Http.WebAssemblyHttpHandler wasmHandler;
public HttpClientHandler ()
{
wasmHandler = new WebAssembly.Net.Http.HttpClient.WasmHttpMessageHandler ();
wasmHandler = new System.Net.Http.WebAssemblyHttpHandler ();
}
protected override void Dispose (bool disposing)
@@ -120,7 +120,15 @@ namespace System.Net.Security
public SslStream (Stream innerStream, bool leaveInnerStreamOpen)
: base (innerStream, leaveInnerStreamOpen)
{
#if WASM
try {
provider = GetProvider ();
} catch (Exception ex) {
throw new PlatformNotSupportedException ("System.Net.Security.SslStream is not supported on the current platform.", ex);
}
#else
provider = GetProvider ();
#endif
settings = MonoTlsSettings.CopyDefaultSettings ();
impl = provider.CreateSslStream (this, innerStream, leaveInnerStreamOpen, settings);
}
@@ -133,7 +141,15 @@ namespace System.Net.Security
public SslStream (Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback, LocalCertificateSelectionCallback userCertificateSelectionCallback)
: base (innerStream, leaveInnerStreamOpen)
{
#if WASM
try {
provider = GetProvider ();
} catch (Exception ex) {
throw new PlatformNotSupportedException ("System.Net.Security.SslStream is not supported on the current platform.", ex);
}
#else
provider = GetProvider ();
#endif
settings = MonoTlsSettings.CopyDefaultSettings ();
SetAndVerifyValidationCallback (userCertificateValidationCallback);
SetAndVerifySelectionCallback (userCertificateSelectionCallback);
-5
View File
@@ -74,10 +74,6 @@ RESOURCE_STRINGS_FILES = --mscorlib-debug
RESOURCE_STRINGS = ../referencesource/mscorlib/mscorlib.txt
MODULE_DEPS = $(IL_REPLACE) LinkerDescriptor/mscorlib.xml
ifdef WASM
MANAGED_COLLATOR_RESOURCES_FILES =
else
MANAGED_COLLATOR_RESOURCES_FILES = \
resources/collation.core.bin \
resources/collation.tailoring.bin \
@@ -86,7 +82,6 @@ MANAGED_COLLATOR_RESOURCES_FILES = \
resources/collation.cjkJA.bin \
resources/collation.cjkKO.bin \
resources/collation.cjkKOlv2.bin
endif
ifdef MCS_MODE
UNICODECHARINFO = resources/charinfo.nlp
@@ -72,9 +72,6 @@ namespace System.Globalization
static bool managedCollation;
static bool managedCollationChecked;
#if WASM
const bool UseManagedCollation = false;
#else
static bool UseManagedCollation {
get {
if (!managedCollationChecked) {
@@ -85,13 +82,9 @@ namespace System.Globalization
return managedCollation;
}
}
#endif
ISimpleCollator GetCollator ()
{
#if WASM
return null;
#else
if (collator != null)
return collator;
@@ -107,7 +100,6 @@ namespace System.Globalization
}
return collator;
#endif
}
SortKey CreateSortKeyCore (string source, CompareOptions options)
@@ -284,56 +284,93 @@ namespace System.Diagnostics.Tracing
// [MonoTODO]
public event EventHandler<EventCommandEventArgs> EventCommandExecuted
{
#if WASM
add { throw new PlatformNotSupportedException (); }
remove { throw new PlatformNotSupportedException (); }
#else
add { throw new NotImplementedException (); }
remove { throw new NotImplementedException (); }
#endif
}
// [MonoTODO]
public static string GenerateManifest (Type eventSourceType, string assemblyPathToIncludeInManifest)
{
#if WASM
throw new PlatformNotSupportedException ();
#else
throw new NotImplementedException ();
#endif
}
// [MonoTODO]
public static string GenerateManifest (Type eventSourceType, string assemblyPathToIncludeInManifest, EventManifestOptions flags)
{
#if WASM
throw new PlatformNotSupportedException ();
#else
throw new NotImplementedException ();
#endif
}
// [MonoTODO]
public static Guid GetGuid (Type eventSourceType)
{
#if WASM
throw new PlatformNotSupportedException ();
#else
throw new NotImplementedException ();
#endif
}
// [MonoTODO]
public static string GetName (Type eventSourceType)
{
#if WASM
throw new PlatformNotSupportedException ();
#else
throw new NotImplementedException ();
#endif
}
// [MonoTODO]
public static IEnumerable<EventSource> GetSources ()
{
#if WASM
throw new PlatformNotSupportedException ();
#else
throw new NotImplementedException ();
#endif
}
// [MonoTODO]
public static void SendCommand (EventSource eventSource, EventCommand command, IDictionary<string, string> commandArguments)
{
#if WASM
throw new PlatformNotSupportedException ();
#else
throw new NotImplementedException ();
#endif
}
// [MonoTODO]
public static void SetCurrentThreadActivityId (Guid activityId)
{
#if WASM
throw new PlatformNotSupportedException ();
#else
throw new NotImplementedException ();
#endif
}
// [MonoTODO]
public static void SetCurrentThreadActivityId (Guid activityId, out Guid oldActivityThatWillContinue)
{
#if WASM
throw new PlatformNotSupportedException ();
#else
throw new NotImplementedException ();
#endif
}
}
}
@@ -66,6 +66,11 @@ namespace System.Runtime.InteropServices
_osArchitecture = Environment.Is64BitOperatingSystem ? Architecture.X64 : Architecture.X86;
_processArchitecture = Architecture.X64;
break;
case "wasm":
#if false
_osArchitecture = Architecture.Wasm;
_processArchitecture = Architecture.Wasm;
#endif
// upstream only has these values; try to pretend we're x86 if nothing matches
// want more? bug: https://github.com/dotnet/corefx/issues/30706
default:
@@ -107,7 +112,7 @@ namespace System.Runtime.InteropServices
_osPlatform = OSPlatform.Create ("HAIKU");
break;
case "wasm":
_osPlatform = OSPlatform.Create ("WEBASSEMBLY");
_osPlatform = OSPlatform.Create ("BROWSER");
break;
default:
_osPlatform = OSPlatform.Create ("UNKNOWN");
@@ -1499,6 +1499,7 @@ public class DirectoryTest
}
[Test] // bug #346123
[Category ("NotWasm")]
public void GetDirectories_Backslash ()
{
if (!RunningOnUnix)
@@ -1567,6 +1568,7 @@ public class DirectoryTest
}
[Test] // bug #346123
[Category ("NotWasm")]
public void GetFiles_Backslash ()
{
if (!RunningOnUnix)
@@ -977,9 +977,15 @@ namespace MonoTests.System.IO
Assert.IsTrue (Path.IsPathRooted ("\\"), "IsPathRooted #16");
Assert.IsTrue (Path.IsPathRooted ("\\\\"), "IsPathRooted #17");
} else {
// To fix issue https://github.com/mono/mono/issues/18933 we set the AltDirectorySeparatorChar as well.
// This causes the Assert.IsTrue (!Path.IsPathRooted ("\\"), "IsPathRooted #09"); to fail.
// Path.IsPathFullyQualified Method handles paths that use both the DirectorySeparatorChar
// and the AltDirectorySeparatorChar characters.
#if !WASM
Assert.IsTrue (!Path.IsPathRooted ("\\"), "IsPathRooted #09");
Assert.IsTrue (!Path.IsPathRooted ("\\\\"), "IsPathRooted #10");
Assert.IsTrue (!Path.IsPathRooted ("z:"), "IsPathRooted #11");
#endif
}
}
}
@@ -3221,6 +3221,9 @@ public class StringTest
// Test replacing null characters (bug #67395)
Assert.AreEqual ("is this ok ?", "is \0 ok ?".Replace ("\0", "this"), "should not strip content after nullchar");
// Disabling in 3.2-wasm for now
//Assert.AreEqual ("CBC", "ABC".Replace ("a", "C", StringComparison.InvariantCultureIgnoreCase));
}
[Test]
+6
View File
@@ -61,6 +61,11 @@ namespace MonoTests.System
C
};
class GenericEnum<T>
{
public enum TheEnum { A, B };
}
class SampleGeneric<T> where T : IFace1
{
}
@@ -2935,6 +2940,7 @@ namespace MonoTests.System
Assert.AreEqual (TypeCode.UInt16, Type.GetTypeCode (typeof (ushort)), "#16");
Assert.AreEqual (TypeCode.UInt32, Type.GetTypeCode (typeof (uint)), "#17");
Assert.AreEqual (TypeCode.UInt64, Type.GetTypeCode (typeof (ulong)), "#18");
Assert.AreEqual (TypeCode.Int32, Type.GetTypeCode (typeof (GenericEnum<int>.TheEnum)));
}
[Test]
+5 -3
View File
@@ -86,9 +86,11 @@ namespace System.Globalization
unsafe int IndexOfCore (string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
{
if (matchLengthPtr != null)
throw new NotImplementedException ();
return internal_index_switch (source, startIndex, count, target, options, true);
*matchLengthPtr = 0;
int res = internal_index_switch (source, startIndex, count, target, options, true);
if (res >= 0 && matchLengthPtr != null)
*matchLengthPtr = target.Length;
return res;
}
unsafe int IndexOfCore (ReadOnlySpan<char> source, ReadOnlySpan<char> target, CompareOptions options, int* matchLengthPtr)
+22 -15
View File
@@ -1301,6 +1301,7 @@
<Compile Include="Mono.Globalization.Unicode\MSCompatUnicodeTableUtil.cs" />
<Compile Include="Mono.Globalization.Unicode\Normalization.cs" />
<Compile Include="Mono.Globalization.Unicode\NormalizationTableUtil.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Globalization.Unicode\SortKey.cs" />
<Compile Include="Mono.Globalization.Unicode\SortKeyBuffer.cs" />
<Compile Include="Mono.Security.Cryptography\DSAManaged.cs" />
@@ -1986,7 +1987,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -2266,7 +2266,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -2600,7 +2599,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -2855,7 +2853,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -3176,7 +3173,6 @@
<Compile Include="..\referencesource\mscorlib\system\security\cryptography\sha384managed.cs" />
<Compile Include="..\referencesource\mscorlib\system\security\cryptography\sha512managed.cs" />
<Compile Include="..\referencesource\mscorlib\system\security\cryptography\tripledescryptoserviceprovider.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -3425,7 +3421,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -3681,7 +3676,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -3937,7 +3931,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -4185,7 +4178,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -4436,7 +4428,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -4687,7 +4678,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -4973,7 +4963,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -5223,7 +5212,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -5478,7 +5466,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -5733,7 +5720,6 @@
<Compile Include="Microsoft.Win32\UnixRegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32RegistryApi.cs" />
<Compile Include="Microsoft.Win32\Win32ResultCode.cs" />
<Compile Include="Mono.Globalization.Unicode\SimpleCollator.cs" />
<Compile Include="Mono.Interop\ComInteropProxy.cs" />
<Compile Include="Mono.Interop\IDispatch.cs" />
<Compile Include="Mono.Interop\IUnknown.cs" />
@@ -6423,6 +6409,27 @@
<EmbeddedResource Include="LinkerDescriptor/mscorlib.xml">
<LogicalName>mscorlib.xml</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="resources/collation.cjkCHS.bin">
<LogicalName>collation.cjkCHS.bin</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="resources/collation.cjkCHT.bin">
<LogicalName>collation.cjkCHT.bin</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="resources/collation.cjkJA.bin">
<LogicalName>collation.cjkJA.bin</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="resources/collation.cjkKO.bin">
<LogicalName>collation.cjkKO.bin</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="resources/collation.cjkKOlv2.bin">
<LogicalName>collation.cjkKOlv2.bin</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="resources/collation.core.bin">
<LogicalName>collation.core.bin</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="resources/collation.tailoring.bin">
<LogicalName>collation.tailoring.bin</LogicalName>
</EmbeddedResource>
</ItemGroup>
<!-- @ALL_RESOURCES@ -->
<PropertyGroup>
@@ -1,4 +1,2 @@
#include unix_build_corlib.dll.exclude.sources
#include testing_aot_common_corlib.dll.exclude.sources
Mono.Globalization.Unicode/SimpleCollator.cs
+1 -1
View File
@@ -205,7 +205,7 @@ ICALL_EXPORT gint32 ves_icall_System_IO_Compression_DeflateStreamNative_WriteZSt
#endif
#if defined(TARGET_WASM)
ICALL_EXPORT void ves_icall_System_TimeZoneInfo_mono_timezone_get_local_name (MonoString result);
ICALL_EXPORT void ves_icall_System_TimeZoneInfo_mono_timezone_get_local_name (MonoString **result);
#endif
#if defined(ENABLE_MONODROID)
+9 -6
View File
@@ -2000,13 +2000,12 @@ guint32
ves_icall_type_GetTypeCodeInternal (MonoReflectionTypeHandle ref_type, MonoError *error)
{
MonoType *type = MONO_HANDLE_GETVAL (ref_type, type);
int t = type->type;
if (type->byref)
return TYPECODE_OBJECT;
handle_enum:
switch (t) {
switch (type->type) {
case MONO_TYPE_VOID:
return TYPECODE_OBJECT;
case MONO_TYPE_BOOLEAN:
@@ -2041,7 +2040,7 @@ handle_enum:
MonoClass *klass = type->data.klass;
if (m_class_is_enumtype (klass)) {
t = mono_class_enum_basetype_internal (klass)->type;
type = mono_class_enum_basetype_internal (klass);
goto handle_enum;
} else if (mono_is_corlib_image (m_class_get_image (klass))) {
if (strcmp (m_class_get_name_space (klass), "System") == 0) {
@@ -2072,9 +2071,13 @@ handle_enum:
}
return TYPECODE_OBJECT;
case MONO_TYPE_GENERICINST:
if (m_class_is_enumtype (type->data.generic_class->container_class)) {
type = mono_class_enum_basetype_internal (type->data.generic_class->container_class);
goto handle_enum;
}
return TYPECODE_OBJECT;
default:
g_error ("type 0x%02x not handled in GetTypeCode()", t);
g_error ("type 0x%02x not handled in GetTypeCode()", type->type);
}
return 0;
}
@@ -8210,9 +8213,9 @@ ves_icall_System_IO_Compression_DeflateStreamNative_WriteZStream (gpointer strea
#endif
#if defined(TARGET_WASM)
G_EXTERN_C void mono_timezone_get_local_name (MonoString result);
G_EXTERN_C void mono_timezone_get_local_name (MonoString **result);
void
ves_icall_System_TimeZoneInfo_mono_timezone_get_local_name (MonoString result)
ves_icall_System_TimeZoneInfo_mono_timezone_get_local_name (MonoString **result)
{
// MONO_CROSS_COMPILE returns undefined symbol "_mono_timezone_get_local_name"
// The icall offsets will be generated and linked at build time
+4
View File
@@ -788,10 +788,14 @@ ves_icall_System_IO_MonoIO_get_DirectorySeparatorChar (void)
gunichar2
ves_icall_System_IO_MonoIO_get_AltDirectorySeparatorChar (void)
{
#if TARGET_WASM
return (gunichar2) '\\'; /* backslash issue https://github.com/mono/mono/issues/18933 */
#else
if (IS_PORTABILITY_SET)
return (gunichar2) '\\'; /* backslash */
else
return (gunichar2) '/'; /* forward slash */
#endif
}
gunichar2
+1 -1
View File
@@ -2191,7 +2191,7 @@ load_aot_module (MonoAssemblyLoadContext *alc, MonoAssembly *assembly, gpointer
}
g_free (aot_name);
}
#ifndef PLATFORM_ANDROID
#if !defined(PLATFORM_ANDROID) && !defined(TARGET_WASM)
if (!sofile) {
char *basename = g_path_get_basename (assembly->image->name);
aot_name = g_strdup_printf ("%s/mono/aot-cache/%s/%s%s", mono_assembly_getrootdir(), MONO_ARCHITECTURE, basename, MONO_SOLIB_EXT);
+1 -1
View File
@@ -3435,13 +3435,13 @@ interp_exec_method (InterpFrame *frame, ThreadContext *context, FrameClauseArgs
#if defined(ENABLE_HYBRID_SUSPEND) || defined(ENABLE_COOP_SUSPEND)
mono_threads_safepoint ();
#endif
main_loop:
/*
* using while (ip < end) may result in a 15% performance drop,
* but it may be useful for debug
*/
while (1) {
MintOpcode opcode;
main_loop:
/* g_assert (sp >= frame->stack); */
/* g_assert(vt_sp - vtalloc <= frame->imethod->vt_stack_size); */
DUMP_INSTR();
+248 -47
View File
@@ -39,21 +39,18 @@ EMSCRIPTEN_KEEPALIVE void mono_wasm_get_array_values (int object_id);
EMSCRIPTEN_KEEPALIVE void mono_wasm_get_array_value_expanded (int object_id, int idx);
//JS functions imported that we use
extern void mono_wasm_add_frame (int il_offset, int method_token, const char *assembly_name);
extern void mono_wasm_add_frame (int il_offset, int method_token, const char *assembly_name, const char *method_name);
extern void mono_wasm_fire_bp (void);
extern void mono_wasm_add_bool_var (gint8);
extern void mono_wasm_add_number_var (double);
extern void mono_wasm_add_string_var (const char*);
extern void mono_wasm_add_obj_var (const char*, guint64);
extern void mono_wasm_add_value_type_unexpanded_var (const char*);
extern void mono_wasm_begin_value_type_var (const char*);
extern void mono_wasm_add_obj_var (const char*, const char*, guint64);
extern void mono_wasm_add_value_type_unexpanded_var (const char*, const char*);
extern void mono_wasm_begin_value_type_var (const char*, const char*);
extern void mono_wasm_end_value_type_var (void);
extern void mono_wasm_add_enum_var (const char*, const char*, guint64);
extern void mono_wasm_add_func_var (const char*, guint64);
extern void mono_wasm_add_array_var (const char*, guint64);
extern void mono_wasm_add_func_var (const char*, const char*, guint64);
extern void mono_wasm_add_properties_var (const char*, gint32);
extern void mono_wasm_add_array_item (int);
extern void mono_wasm_set_is_async_method (guint64);
extern void mono_wasm_add_typed_value (const char *type, const char *str_value, double value);
G_END_DECLS
@@ -67,6 +64,21 @@ static GHashTable *objrefs;
static GHashTable *obj_to_objref;
static int objref_id = 0;
static const char*
all_getters_allowed_class_names[] = {
"System.DateTime",
"System.DateTimeOffset",
"System.TimeSpan"
};
static const char*
to_string_as_descr_names[] = {
"System.DateTime",
"System.DateTimeOffset",
"System.Decimal",
"System.TimeSpan"
};
#define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
static void
@@ -119,7 +131,7 @@ collect_frames (MonoStackFrameInfo *info, MonoContext *ctx, gpointer data)
DEBUG_PRINTF (2, "Reporting method %s native_offset %d\n", method->name, info->native_offset);
if (!mono_find_prev_seq_point_for_native_offset (mono_get_root_domain (), method, info->native_offset, NULL, &sp))
DEBUG_PRINTF (1, "Failed to lookup sequence point\n");
DEBUG_PRINTF (2, "Failed to lookup sequence point\n");
DbgEngineStackFrame *frame = g_new0 (DbgEngineStackFrame, 1);
@@ -335,7 +347,7 @@ mono_wasm_debugger_init (void)
mono_debug_init (MONO_DEBUG_FORMAT_MONO);
mono_de_init (&cbs);
mono_de_set_log_level (1, stdout);
mono_de_set_log_level (log_level, stdout);
mini_debug_options.gen_sdb_seq_points = TRUE;
mini_debug_options.mdb_optimizations = TRUE;
@@ -352,10 +364,11 @@ mono_wasm_debugger_init (void)
}
MONO_API void
mono_wasm_enable_debugging (void)
mono_wasm_enable_debugging (int debug_level)
{
DEBUG_PRINTF (1, "DEBUGGING ENABLED\n");
debugger_enabled = TRUE;
log_level = debug_level;
}
EMSCRIPTEN_KEEPALIVE int
@@ -363,7 +376,7 @@ mono_wasm_setup_single_step (int kind)
{
int nmodifiers = 1;
printf (">>>> mono_wasm_setup_single_step %d\n", kind);
DEBUG_PRINTF (2, ">>>> mono_wasm_setup_single_step %d\n", kind);
EventRequest *req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
req->id = ++event_request_id;
req->event_kind = EVENT_KIND_STEP;
@@ -507,7 +520,7 @@ mono_wasm_breakpoint_hit (void)
EMSCRIPTEN_KEEPALIVE int
mono_wasm_current_bp_id (void)
{
DEBUG_PRINTF (1, "COMPUTING breapoint ID\n");
DEBUG_PRINTF (2, "COMPUTING breakpoint ID\n");
//FIXME handle compiled case
/* Interpreter */
@@ -574,6 +587,7 @@ list_frames (MonoStackFrameInfo *info, MonoContext *ctx, gpointer data)
{
SeqPoint sp;
MonoMethod *method;
char *method_full_name;
//skip wrappers
if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP)
@@ -593,6 +607,7 @@ list_frames (MonoStackFrameInfo *info, MonoContext *ctx, gpointer data)
if (!mono_find_prev_seq_point_for_native_offset (mono_get_root_domain (), method, info->native_offset, NULL, &sp))
DEBUG_PRINTF (1, "Failed to lookup sequence point\n");
method_full_name = mono_method_full_name (method, FALSE);
while (method->is_inflated)
method = ((MonoMethodInflated*)method)->declaring;
@@ -601,7 +616,7 @@ list_frames (MonoStackFrameInfo *info, MonoContext *ctx, gpointer data)
if (method->wrapper_type == MONO_WRAPPER_NONE) {
DEBUG_PRINTF (2, "adding off %d token %d assembly name %s\n", sp.il_offset, mono_metadata_token_index (method->token), assembly_name);
mono_wasm_add_frame (sp.il_offset, mono_metadata_token_index (method->token), assembly_name);
mono_wasm_add_frame (sp.il_offset, mono_metadata_token_index (method->token), assembly_name, method_full_name);
}
g_free (assembly_name);
@@ -615,6 +630,72 @@ mono_wasm_enum_frames (void)
mono_walk_stack_with_ctx (list_frames, NULL, MONO_UNWIND_NONE, NULL);
}
static char*
invoke_to_string (const char *class_name, MonoClass *klass, gpointer addr)
{
MonoObject *exc;
MonoString *mstr;
char *ret_str;
ERROR_DECL (error);
MonoObject *obj;
// TODO: this is for a specific use case right now,
// (invoke ToString() get a preview/description for *some* types)
// and we don't want to report errors for that.
if (m_class_is_valuetype (klass)) {
MonoMethod *method;
MONO_STATIC_POINTER_INIT (MonoMethod, to_string)
to_string = mono_class_get_method_from_name_checked (mono_get_object_class (), "ToString", 0, METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_PUBLIC, error);
mono_error_assert_ok (error);
MONO_STATIC_POINTER_INIT_END (MonoMethod, to_string)
method = mono_class_get_virtual_method (klass, to_string, FALSE, error);
if (!method)
return NULL;
MonoString *mstr = (MonoString*) mono_runtime_try_invoke (method, addr , NULL, &exc, error);
if (exc || !is_ok (error)) {
DEBUG_PRINTF (1, "Failed to invoke ToString for %s\n", class_name);
return NULL;
}
return mono_string_to_utf8_checked_internal (mstr, error);
}
obj = *(MonoObject**)addr;
if (!obj)
return NULL;
mstr = mono_object_try_to_string (obj, &exc, error);
if (exc || !is_ok (error))
return NULL;
ret_str = mono_string_to_utf8_checked_internal (mstr, error);
if (!is_ok (error))
return NULL;
return ret_str;
}
static char*
get_to_string_description (const char* class_name, MonoClass *klass, gpointer addr)
{
if (!class_name || !klass || !addr)
return NULL;
if (strcmp (class_name, "System.Guid") == 0)
return mono_guid_to_string (addr);
for (int i = 0; i < G_N_ELEMENTS (to_string_as_descr_names); i ++) {
if (strcmp (to_string_as_descr_names [i], class_name) == 0) {
return invoke_to_string (class_name, klass, addr);
}
}
return NULL;
}
typedef struct {
int cur_frame;
int target_frame;
@@ -622,6 +703,28 @@ typedef struct {
int *pos;
} FrameDescData;
/*
* this returns a string formatted like
*
* <ret_type>:[<comma separated list of arg types>]:<method name>
*
* .. which is consumed by `mono_wasm_add_func_var`. It is used for
* generating this for the delegate, and it's target.
*/
static char*
mono_method_to_desc_for_js (MonoMethod *method, gboolean include_namespace)
{
MonoMethodSignature *sig = mono_method_signature_internal (method);
char *ret_desc = mono_type_full_name (sig->ret);
char *args_desc = mono_signature_get_desc (sig, include_namespace);
char *sig_desc = g_strdup_printf ("%s:%s:%s", ret_desc, args_desc, method->name);
g_free (ret_desc);
g_free (args_desc);
return sig_desc;
}
static guint64
read_enum_value (const char *mem, int type)
{
@@ -663,49 +766,64 @@ static gboolean describe_value(MonoType * type, gpointer addr, gboolean expandVa
ERROR_DECL (error);
switch (type->type) {
case MONO_TYPE_BOOLEAN:
mono_wasm_add_bool_var (*(gint8*)addr);
mono_wasm_add_typed_value ("bool", NULL, *(gint8*)addr);
break;
case MONO_TYPE_I1:
mono_wasm_add_number_var (*(gint8*)addr);
mono_wasm_add_typed_value ("number", NULL, *(gint8*)addr);
break;
case MONO_TYPE_U1:
mono_wasm_add_number_var (*(guint8*)addr);
mono_wasm_add_typed_value ("number", NULL, *(guint8*)addr);
break;
case MONO_TYPE_CHAR:
mono_wasm_add_typed_value ("char", NULL, *(guint16*)addr);
break;
case MONO_TYPE_U2:
mono_wasm_add_number_var (*(guint16*)addr);
mono_wasm_add_typed_value ("number", NULL, *(guint16*)addr);
break;
case MONO_TYPE_I2:
mono_wasm_add_number_var (*(gint16*)addr);
mono_wasm_add_typed_value ("number", NULL, *(gint16*)addr);
break;
case MONO_TYPE_I4:
case MONO_TYPE_I:
mono_wasm_add_number_var (*(gint32*)addr);
mono_wasm_add_typed_value ("number", NULL, *(gint32*)addr);
break;
case MONO_TYPE_U4:
case MONO_TYPE_U:
mono_wasm_add_number_var (*(guint32*)addr);
mono_wasm_add_typed_value ("number", NULL, *(guint32*)addr);
break;
case MONO_TYPE_I8:
mono_wasm_add_number_var (*(gint64*)addr);
mono_wasm_add_typed_value ("number", NULL, *(gint64*)addr);
break;
case MONO_TYPE_U8:
mono_wasm_add_number_var (*(guint64*)addr);
mono_wasm_add_typed_value ("number", NULL, *(guint64*)addr);
break;
case MONO_TYPE_R4:
mono_wasm_add_number_var (*(float*)addr);
mono_wasm_add_typed_value ("number", NULL, *(float*)addr);
break;
case MONO_TYPE_R8:
mono_wasm_add_number_var (*(double*)addr);
mono_wasm_add_typed_value ("number", NULL, *(double*)addr);
break;
case MONO_TYPE_PTR:
case MONO_TYPE_FNPTR: {
char *class_name = mono_type_full_name (type);
const void *val = *(const void **)addr;
char *val_str = g_strdup_printf ("(%s) %p", class_name, val);
mono_wasm_add_typed_value ("pointer", val_str, (guint32)val);
g_free (val_str);
g_free (class_name);
break;
}
case MONO_TYPE_STRING: {
MonoString *str_obj = *(MonoString **)addr;
if (!str_obj) {
mono_wasm_add_string_var (NULL);
mono_wasm_add_typed_value ("string", NULL, 0);
} else {
char *str = mono_string_to_utf8_checked_internal (str_obj, error);
mono_error_assert_ok (error); /* FIXME report error */
mono_wasm_add_string_var (str);
mono_wasm_add_typed_value ("string", str, 0);
g_free (str);
}
break;
@@ -728,12 +846,34 @@ static gboolean describe_value(MonoType * type, gpointer addr, gboolean expandVa
char *class_name = mono_type_full_name (type);
int obj_id = get_object_id (obj);
if (type->type == MONO_TYPE_SZARRAY || type->type == MONO_TYPE_ARRAY) {
mono_wasm_add_array_var (class_name, obj_id);
} else if (m_class_is_delegate (klass)) {
mono_wasm_add_func_var (class_name, obj_id);
if (type-> type == MONO_TYPE_ARRAY || type->type == MONO_TYPE_SZARRAY) {
MonoArray *array = (MonoArray *)obj;
EM_ASM ({
MONO.mono_wasm_add_typed_value ('array', $0, { objectId: $1, length: $2 });
}, class_name, obj_id, mono_array_length_internal (array));
} else if (m_class_is_delegate (klass) || (type->type == MONO_TYPE_GENERICINST && m_class_is_delegate (type->data.generic_class->container_class))) {
MonoMethod *method;
if (type->type == MONO_TYPE_GENERICINST)
klass = type->data.generic_class->container_class;
method = mono_get_delegate_invoke_internal (klass);
if (!method) {
DEBUG_PRINTF (2, "Could not get a method for the delegate for %s\n", class_name);
break;
}
MonoMethod *tm = ((MonoDelegate *)obj)->method;
char *tm_desc = NULL;
if (tm)
tm_desc = mono_method_to_desc_for_js (tm, FALSE);
mono_wasm_add_func_var (class_name, tm_desc, obj_id);
g_free (tm_desc);
} else {
mono_wasm_add_obj_var (class_name, obj_id);
char *to_string_val = get_to_string_description (class_name, klass, addr);
mono_wasm_add_obj_var (class_name, to_string_val, obj_id);
g_free (to_string_val);
}
g_free (class_name);
break;
@@ -778,12 +918,17 @@ static gboolean describe_value(MonoType * type, gpointer addr, gboolean expandVa
mono_wasm_add_enum_var (class_name, enum_members->str, value__);
g_string_free (enum_members, TRUE);
} else if (expandValueType) {
mono_wasm_begin_value_type_var (class_name);
char *to_string_val = get_to_string_description (class_name, klass, addr);
mono_wasm_begin_value_type_var (class_name, to_string_val);
g_free (to_string_val);
// FIXME: isAsyncLocalThis
describe_object_properties_for_klass ((MonoObject*)addr, klass, FALSE, expandValueType);
mono_wasm_end_value_type_var ();
} else {
mono_wasm_add_value_type_unexpanded_var (class_name);
char *to_string_val = get_to_string_description (class_name, klass, addr);
mono_wasm_add_value_type_unexpanded_var (class_name, to_string_val);
g_free (to_string_val);
}
g_free (class_name);
break;
@@ -791,7 +936,7 @@ static gboolean describe_value(MonoType * type, gpointer addr, gboolean expandVa
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);
mono_wasm_add_typed_value ("string", msg, 0);
g_free (msg);
g_free (type_name);
}
@@ -799,6 +944,17 @@ static gboolean describe_value(MonoType * type, gpointer addr, gboolean expandVa
return TRUE;
}
static gboolean
are_getters_allowed (const char *class_name)
{
for (int i = 0; i < G_N_ELEMENTS (all_getters_allowed_class_names); i ++) {
if (strcmp (class_name, all_getters_allowed_class_names [i]) == 0)
return TRUE;
}
return FALSE;
}
static void
describe_object_properties_for_klass (void *obj, MonoClass *klass, gboolean isAsyncLocalThis, gboolean expandValueType)
{
@@ -809,6 +965,8 @@ describe_object_properties_for_klass (void *obj, MonoClass *klass, gboolean isAs
ERROR_DECL (error);
gboolean is_valuetype;
int pnum;
char *klass_name;
gboolean getters_allowed;
g_assert (klass);
is_valuetype = m_class_is_valuetype(klass);
@@ -840,12 +998,17 @@ describe_object_properties_for_klass (void *obj, MonoClass *klass, gboolean isAs
describe_value (f->type, field_addr, is_valuetype | expandValueType);
}
klass_name = mono_class_full_name (klass);
getters_allowed = are_getters_allowed (klass_name);
iter = NULL;
pnum = 0;
while ((p = mono_class_get_properties (klass, &iter))) {
DEBUG_PRINTF (2, "mono_class_get_properties - %s - %s\n", p->name, p->get->name);
if (p->get->name) { //if get doesn't have name means that doesn't have a getter implemented and we don't want to show value, like VS debug
char *class_name;
MonoObject *res;
MonoObject *exc;
if (isAsyncLocalThis && (p->name[0] != '<' || (p->name[0] == '<' && p->name[1] == '>')))
continue;
@@ -853,14 +1016,18 @@ describe_object_properties_for_klass (void *obj, MonoClass *klass, gboolean isAs
sig = mono_method_signature_internal (p->get);
// automatic properties will get skipped
class_name = mono_class_full_name (mono_class_from_mono_type_internal (sig->ret));
mono_wasm_add_string_var (class_name);
g_free (class_name);
if (!getters_allowed) {
// not allowed to call the getter here
char *ret_class_name = mono_class_full_name (mono_class_from_mono_type_internal (sig->ret));
mono_wasm_add_typed_value ("getter", ret_class_name, 0);
g_free (ret_class_name);
continue;
}
#if false // Disabled for now, as we don't want to invoke getters
if (is_valuetype && mono_class_from_mono_type_internal (sig->ret) == klass) {
// Property of the same valuetype, avoid endlessly recursion!
mono_wasm_add_string_var (mono_class_full_name (klass));
mono_wasm_add_typed_value ("getter", klass_name, 0);
continue;
}
@@ -873,12 +1040,33 @@ describe_object_properties_for_klass (void *obj, MonoClass *klass, gboolean isAs
describe_value (sig->ret, &res, TRUE);
else
describe_value (sig->ret, mono_object_unbox_internal (res), TRUE);
#endif
}
pnum ++;
}
}
/*
* We return a `Target` property only for now.
* In future, we could add a `MethodInfo` too.
*/
static gboolean
describe_delegate_properties (MonoObject *obj)
{
MonoClass *klass = mono_object_class(obj);
if (!m_class_is_delegate (klass))
return FALSE;
// Target, like in VS - what is this field supposed to be, anyway??
MonoMethod *tm = ((MonoDelegate *)obj)->method;
char * sig_desc = mono_method_to_desc_for_js (tm, FALSE);
mono_wasm_add_properties_var ("Target", -1);
mono_wasm_add_func_var (NULL, sig_desc, -1);
g_free (sig_desc);
return TRUE;
}
static gboolean
describe_object_properties (guint64 objectId, gboolean isAsyncLocalThis, gboolean expandValueType)
{
@@ -895,7 +1083,13 @@ describe_object_properties (guint64 objectId, gboolean isAsyncLocalThis, gboolea
return FALSE;
}
describe_object_properties_for_klass (obj, obj->vtable->klass, isAsyncLocalThis, expandValueType);
if (m_class_is_delegate (mono_object_class (obj))) {
// delegates get the same id format as regular objects
describe_delegate_properties (obj);
} else {
describe_object_properties_for_klass (obj, obj->vtable->klass, isAsyncLocalThis, expandValueType);
}
return TRUE;
}
@@ -971,11 +1165,18 @@ describe_non_async_this (InterpFrame *frame, MonoMethod *method)
if (mono_method_signature_internal (method)->hasthis) {
addr = mini_get_interp_callbacks ()->frame_get_this (frame);
MonoObject *obj = *(MonoObject**)addr;
char *class_name = mono_class_full_name (obj->vtable->klass);
MonoClass *klass = method->klass;
MonoType *type = m_class_get_byval_arg (method->klass);
mono_wasm_add_properties_var ("this", -1);
mono_wasm_add_obj_var (class_name, get_object_id(obj));
g_free (class_name);
if (m_class_is_valuetype (klass)) {
describe_value (type, obj, TRUE);
} else {
// this is an object, and we can retrieve the valuetypes in it later
// through the object id
describe_value (type, addr, FALSE);
}
}
}
+1 -1
View File
@@ -104,7 +104,7 @@ typedef struct {
void mono_wasm_debugger_init (void);
// sdks/wasm/driver.c is C and uses this
G_EXTERN_C void mono_wasm_enable_debugging (void);
G_EXTERN_C void mono_wasm_enable_debugging (int log_level);
void mono_wasm_breakpoint_hit (void);
void mono_wasm_set_timeout (int timeout, int id);
+6 -55
View File
@@ -15,60 +15,7 @@ if (monoBranch == 'master') {
}
parallel (
"Android Darwin (Debug)": {
throttle(['provisions-android-toolchain']) {
node ("osx-devices") {
archive ("android", "debug", "Darwin")
}
}
},
"Android Darwin (Release)": {
throttle(['provisions-android-toolchain']) {
node ("osx-devices") {
archive ("android", "release", "Darwin")
}
}
},
"Android Windows (Release)": {
throttle(['provisions-android-toolchain']) {
node ("w64") {
archive ("android", "release", "Windows")
}
}
},
"Android Linux (Debug)": {
throttle(['provisions-android-toolchain']) {
node ("debian-10-amd64-exclusive") {
archive ("android", "debug", "Linux", "debian-10-amd64multiarchi386-preview", "g++-mingw-w64 gcc-mingw-w64 lib32stdc++6 lib32z1 libz-mingw-w64-dev linux-libc-dev:i386 zlib1g-dev zlib1g-dev:i386 zulu-8 rsync python3-pip", "/mnt/scratch")
}
}
},
"Android Linux (Release)": {
throttle(['provisions-android-toolchain']) {
node ("debian-10-amd64-exclusive") {
archive ("android", "release", "Linux", "debian-10-amd64multiarchi386-preview", "g++-mingw-w64 gcc-mingw-w64 lib32stdc++6 lib32z1 libz-mingw-w64-dev linux-libc-dev:i386 zlib1g-dev zlib1g-dev:i386 zulu-8 rsync python3-pip", "/mnt/scratch")
}
}
},
"iOS (Xcode 11.3)": {
throttle(['provisions-ios-toolchain']) {
node ("xcode113") {
archive ("ios", "release", "Darwin", "", "", "", "xcode113")
}
}
},
"Mac (Xcode 11.3)": {
throttle(['provisions-mac-toolchain']) {
node ("xcode113") {
archive ("mac", "release", "Darwin", "", "", "", "xcode113")
}
}
},
"WASM Linux": {
if (monoBranch != 'master') {
echo "Skipping WASM build on non-master branch."
return
}
throttle(['provisions-wasm-toolchain']) {
node ("ubuntu-1804-amd64") {
archive ("wasm", "release", "Linux", "ubuntu-1804-amd64-preview", "npm dotnet-sdk-2.1 nuget openjdk-8-jre python3-pip")
@@ -80,6 +27,8 @@ parallel (
def archive (product, configuration, platform, chrootname = "", chrootadditionalpackages = "", chrootBindMounts = "", xcodeVersion = "") {
def packageFileName = null
def packageFileSha1 = null
def sdkPackageFileName = null
def sdkPackageFileSha1 = null
def commitHash = null
def commitContext = (xcodeVersion == "" ? "Archive-${product}-${configuration}-${platform}" : "Archive-${product}-${configuration}-${platform}-${xcodeVersion}")
def azureArtifactUrl = null
@@ -137,10 +86,12 @@ def archive (product, configuration, platform, chrootname = "", chrootadditional
}
// find Archive in the workspace root
packageFileName = findFiles (glob: "${product}-${configuration}-${platform}-${commitHash}.*")[0].name
sdkPackageFileName = findFiles (glob: "sdks/${product}/*.zip")[0].path
// compute SHA1 of the Archive
packageFileSha1 = sha1 (packageFileName)
writeFile (file: "${packageFileName}.sha1", text: "${packageFileSha1}")
sdkPackageFileSha1 = sha1 (sdkPackageFileName);
writeFile (file: "${sdkPackageFileName}.sha1", text: "${sdkPackageFileSha1}")
// include xcode version in virtual path if necessary
if (xcodeVersion == "") {
@@ -156,7 +107,7 @@ def archive (product, configuration, platform, chrootname = "", chrootadditional
storageType: "blobstorage",
containerName: azureContainerName,
virtualPath: azureVirtualPath,
filesPath: "${packageFileName},${packageFileName}.sha1",
filesPath: "${packageFileName},${packageFileName}.sha1,${sdkPackageFileName},${sdkPackageFileName}.sha1",
allowAnonymousAccess: true,
pubAccessible: true,
doNotWaitForPreviousBuild: true,
+4 -3
View File
@@ -36,7 +36,7 @@ if [[ ${CI_TAGS} == *'pull-request'* ]]; then
skip_step="CI provisioning scripts"
skip=true
fi
if ! grep -q -v a/sdks/wasm pr-files.txt; then
if [ ! grep -q -v a/sdks/wasm pr-files.txt ] || [ "${ghprbTargetBranch}" == "3.2-wasm" ]; then
if [[ ${CI_TAGS} == *'webassembly'* ]] || [[ ${CI_TAGS} == *'wasm'* ]]; then
true
else
@@ -345,8 +345,10 @@ if [[ ${CI_TAGS} == *'webassembly'* ]] || [[ ${CI_TAGS} == *'wasm'* ]];
${TESTCMD} --label=build --timeout=180m --fatal $gnumake -j ${CI_CPU_COUNT} --output-sync=recurse --trace -C sdks/builds build-wasm NINJA=
${TESTCMD} --label=archive --timeout=180m --fatal $gnumake -j ${CI_CPU_COUNT} --output-sync=recurse --trace -C sdks/builds archive-wasm NINJA=
${TESTCMD} --label=wasm-build --timeout=20m --fatal $gnumake -j ${CI_CPU_COUNT} -C sdks/wasm build
${TESTCMD} --label=package --timeout=20m $gnumake -C sdks/wasm package
if [[ ${CI_TAGS} != *'no-tests'* ]]; then
${TESTCMD} --label=wasm-build --timeout=20m --fatal $gnumake -j ${CI_CPU_COUNT} -C sdks/wasm build
${TESTCMD} --label=mini --timeout=20m $gnumake -C sdks/wasm run-all-mini
${TESTCMD} --label=v8-corlib --timeout=20m $gnu$gnumake -C sdks/wasm run-v8-corlib
${TESTCMD} --label=mini-system --timeout=60m $gnu$gnumake -C sdks/wasm run-all-System
@@ -367,7 +369,6 @@ if [[ ${CI_TAGS} == *'webassembly'* ]] || [[ ${CI_TAGS} == *'wasm'* ]];
# Requires a net 3.0 sdk
#${TESTCMD} --label=netcore --timeout=20m $gnumake -j ${CI_CPU_COUNT} -C sdks/wasm run-hello-netcore
#${TESTCMD} --label=check-aot --timeout=20m $gnumake -C sdks/wasm check-aot
${TESTCMD} --label=package --timeout=20m $gnumake -C sdks/wasm package
fi
exit 0
fi
+556
View File
@@ -0,0 +1,556 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Xunit;
using WebAssembly.Net.Debugging;
namespace DebuggerTests
{
public class ArrayTests : DebuggerTestBase {
[Theory]
[InlineData (16, 2, "PrimitiveTypeLocals", false, 0, false)]
[InlineData (16, 2, "PrimitiveTypeLocals", false, 0, true)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, false)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, true)]
public async Task InspectPrimitiveTypeArrayLocals (int line, int col, string method_name, bool test_prev_frame, int frame_idx, bool use_cfo)
=> await TestSimpleArrayLocals (
line, col,
entry_method_name: "[debugger-test] DebuggerTests.ArrayTestsClass:PrimitiveTypeLocals",
method_name: method_name,
etype_name: "int",
local_var_name_prefix: "int",
array: new [] { TNumber (4), TNumber (70), TNumber (1) },
array_elements: null,
test_prev_frame: test_prev_frame,
frame_idx: frame_idx,
use_cfo: use_cfo);
[Theory]
[InlineData (32, 2, "ValueTypeLocals", false, 0, false)]
[InlineData (32, 2, "ValueTypeLocals", false, 0, true)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, false)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, true)]
public async Task InspectValueTypeArrayLocals (int line, int col, string method_name, bool test_prev_frame, int frame_idx, bool use_cfo)
=> await TestSimpleArrayLocals (
line, col,
entry_method_name: "[debugger-test] DebuggerTests.ArrayTestsClass:ValueTypeLocals",
method_name: method_name,
etype_name: "DebuggerTests.Point",
local_var_name_prefix: "point",
array: new [] {
TValueType ("DebuggerTests.Point"),
TValueType ("DebuggerTests.Point"),
},
array_elements: new [] {
TPoint (5, -2, "point_arr#Id#0", "Green"),
TPoint (123, 0, "point_arr#Id#1", "Blue")
},
test_prev_frame: test_prev_frame,
frame_idx: frame_idx,
use_cfo: use_cfo);
[Theory]
[InlineData (49, 2, "ObjectTypeLocals", false, 0, false)]
[InlineData (49, 2, "ObjectTypeLocals", false, 0, true)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, false)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, true)]
public async Task InspectObjectArrayLocals (int line, int col, string method_name, bool test_prev_frame, int frame_idx, bool use_cfo)
=> await TestSimpleArrayLocals (
line, col,
entry_method_name: "[debugger-test] DebuggerTests.ArrayTestsClass:ObjectTypeLocals",
method_name: method_name,
etype_name: "DebuggerTests.SimpleClass",
local_var_name_prefix: "class",
array: new [] {
TObject ("DebuggerTests.SimpleClass"),
TObject ("DebuggerTests.SimpleClass", is_null: true),
TObject ("DebuggerTests.SimpleClass")
},
array_elements: new [] {
TSimpleClass (5, -2, "class_arr#Id#0", "Green"),
null, // Element is null
TSimpleClass (123, 0, "class_arr#Id#2", "Blue") },
test_prev_frame: test_prev_frame,
frame_idx: frame_idx,
use_cfo: use_cfo);
[Theory]
[InlineData (66, 2, "GenericTypeLocals", false, 0, false)]
[InlineData (66, 2, "GenericTypeLocals", false, 0, true)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, false)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, true)]
public async Task InspectGenericTypeArrayLocals (int line, int col, string method_name, bool test_prev_frame, int frame_idx, bool use_cfo)
=> await TestSimpleArrayLocals (
line, col,
entry_method_name: "[debugger-test] DebuggerTests.ArrayTestsClass:GenericTypeLocals",
method_name: method_name,
etype_name: "DebuggerTests.GenericClass<int>",
local_var_name_prefix: "gclass",
array: new [] {
TObject ("DebuggerTests.GenericClass<int>", is_null: true),
TObject ("DebuggerTests.GenericClass<int>"),
TObject ("DebuggerTests.GenericClass<int>")
},
array_elements: new [] {
null, // Element is null
new {
Id = TString ("gclass_arr#1#Id"),
Color = TEnum ("DebuggerTests.RGB", "Red"),
Value = TNumber (5)
},
new {
Id = TString ("gclass_arr#2#Id"),
Color = TEnum ("DebuggerTests.RGB", "Blue"),
Value = TNumber (-12)
}
},
test_prev_frame: test_prev_frame,
frame_idx: frame_idx,
use_cfo: use_cfo);
[Theory]
[InlineData (82, 2, "GenericValueTypeLocals", false, 0, false)]
[InlineData (82, 2, "GenericValueTypeLocals", false, 0, true)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, false)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, true)]
public async Task InspectGenericValueTypeArrayLocals (int line, int col, string method_name, bool test_prev_frame, int frame_idx, bool use_cfo)
=> await TestSimpleArrayLocals (
line, col,
entry_method_name: "[debugger-test] DebuggerTests.ArrayTestsClass:GenericValueTypeLocals",
method_name: method_name,
etype_name: "DebuggerTests.SimpleGenericStruct<DebuggerTests.Point>",
local_var_name_prefix: "gvclass",
array: new [] {
TValueType ("DebuggerTests.SimpleGenericStruct<DebuggerTests.Point>"),
TValueType ("DebuggerTests.SimpleGenericStruct<DebuggerTests.Point>")
},
array_elements: new [] {
new {
Id = TString ("gvclass_arr#1#Id"),
Color = TEnum ("DebuggerTests.RGB", "Red"),
Value = TPoint (100, 200, "gvclass_arr#1#Value#Id", "Red")
},
new {
Id = TString ("gvclass_arr#2#Id"),
Color = TEnum ("DebuggerTests.RGB", "Blue"),
Value = TPoint (10, 20, "gvclass_arr#2#Value#Id", "Green")
}
},
test_prev_frame: test_prev_frame,
frame_idx: frame_idx,
use_cfo: use_cfo);
[Theory]
[InlineData (191, 2, "GenericValueTypeLocals2", false, 0, false)]
[InlineData (191, 2, "GenericValueTypeLocals2", false, 0, true)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, false)]
[InlineData (93, 2, "YetAnotherMethod", true, 2, true)]
public async Task InspectGenericValueTypeArrayLocals2 (int line, int col, string method_name, bool test_prev_frame, int frame_idx, bool use_cfo)
=> await TestSimpleArrayLocals (
line, col,
entry_method_name: "[debugger-test] DebuggerTests.ArrayTestsClass:GenericValueTypeLocals2",
method_name: method_name,
etype_name: "DebuggerTests.SimpleGenericStruct<DebuggerTests.Point[]>",
local_var_name_prefix: "gvclass",
array: new [] {
TValueType ("DebuggerTests.SimpleGenericStruct<DebuggerTests.Point[]>"),
TValueType ("DebuggerTests.SimpleGenericStruct<DebuggerTests.Point[]>")
},
array_elements: new [] {
new {
Id = TString ("gvclass_arr#0#Id"),
Color = TEnum ("DebuggerTests.RGB", "Red"),
Value = new [] {
TPoint (100, 200, "gvclass_arr#0#0#Value#Id", "Red"),
TPoint (100, 200, "gvclass_arr#0#1#Value#Id", "Green")
}
},
new {
Id = TString ("gvclass_arr#1#Id"),
Color = TEnum ("DebuggerTests.RGB", "Blue"),
Value = new [] {
TPoint (100, 200, "gvclass_arr#1#0#Value#Id", "Green"),
TPoint (100, 200, "gvclass_arr#1#1#Value#Id", "Blue")
}
}
},
test_prev_frame: test_prev_frame,
frame_idx: frame_idx,
use_cfo: use_cfo);
async Task TestSimpleArrayLocals (int line, int col, string entry_method_name, string method_name, string etype_name,
string local_var_name_prefix, object[] array, object[] array_elements,
bool test_prev_frame=false, int frame_idx=0, bool use_cfo = false)
{
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await Ready();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
var debugger_test_loc = "dotnet://debugger-test.dll/debugger-array-test.cs";
ctx.UseCallFunctionOnBeforeGetProperties = use_cfo;
await SetBreakpoint (debugger_test_loc, line, col);
var eval_expr = "window.setTimeout(function() { invoke_static_method ("
+ $"'{entry_method_name}', { (test_prev_frame ? "true" : "false") }"
+ "); }, 1);";
var pause_location = await EvaluateAndCheck (eval_expr, debugger_test_loc, line, col, method_name);
var locals = await GetProperties (pause_location ["callFrames"][frame_idx]["callFrameId"].Value<string> ());
Assert.Equal (4, locals.Count ());
CheckArray (locals, $"{local_var_name_prefix}_arr", $"{etype_name}[]");
CheckArray (locals, $"{local_var_name_prefix}_arr_empty", $"{etype_name}[]");
CheckObject (locals, $"{local_var_name_prefix}_arr_null", $"{etype_name}[]", is_null: true);
CheckBool (locals, "call_other", test_prev_frame);
var local_arr_name = $"{local_var_name_prefix}_arr";
JToken prefix_arr;
if (use_cfo) { // Use `Runtime.callFunctionOn` to get the properties
var frame = pause_location ["callFrames"][frame_idx];
var name = local_arr_name;
var fl = await GetProperties (frame ["callFrameId"].Value<string> ());
var l_obj = GetAndAssertObjectWithName (locals, name);
var l_objectId = l_obj ["value"]["objectId"]?.Value<string> ();
Assert.True (!String.IsNullOrEmpty (l_objectId), $"No objectId found for {name}");
prefix_arr = await GetObjectWithCFO (l_objectId);
} else {
prefix_arr = await GetObjectOnFrame (pause_location ["callFrames"][frame_idx], local_arr_name);
}
await CheckProps (prefix_arr, array, local_arr_name);
if (array_elements?.Length > 0) {
for (int i = 0; i < array_elements.Length; i ++) {
var i_str = i.ToString ();
var label = $"{local_var_name_prefix}_arr[{i}]";
if (array_elements [i] == null) {
var act_i = prefix_arr.FirstOrDefault (jt => jt ["name"]?.Value<string> () == i_str);
Assert.True (act_i != null, $"[{label}] Couldn't find array element [{i_str}]");
await CheckValue (act_i ["value"], TObject (etype_name, is_null: true), label);
} else {
await CompareObjectPropertiesFor (prefix_arr, i_str, array_elements [i], label: label);
}
}
}
var props = await GetObjectOnFrame (pause_location ["callFrames"][frame_idx], $"{local_var_name_prefix}_arr_empty");
await CheckProps (props, new object[0], "${local_var_name_prefix}_arr_empty");
});
async Task<JToken> GetObjectWithCFO (string objectId, JObject fn_args = null)
{
var fn_decl = "function () { return this; }";
var cfo_args = JObject.FromObject (new {
functionDeclaration = fn_decl,
objectId = objectId
});
if (fn_args != null)
cfo_args ["arguments"] = fn_args;
// callFunctionOn
var result = await ctx.cli.SendCommand ("Runtime.callFunctionOn", cfo_args, ctx.token);
return await GetProperties (result.Value ["result"]["objectId"]?.Value<string> (), fn_args);
}
}
[Theory]
[InlineData (false)]
[InlineData (true)]
public async Task InspectObjectArrayMembers (bool use_cfo)
{
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
int line = 205;
int col = 3;
string entry_method_name = "[debugger-test] DebuggerTests.ArrayTestsClass:ObjectArrayMembers";
string method_name = "PlaceholderMethod";
int frame_idx = 1;
await Ready();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
ctx.UseCallFunctionOnBeforeGetProperties = use_cfo;
var debugger_test_loc = "dotnet://debugger-test.dll/debugger-array-test.cs";
await SetBreakpoint (debugger_test_loc, line, col);
var eval_expr = "window.setTimeout(function() { invoke_static_method ("
+ $"'{entry_method_name}'"
+ "); }, 1);";
var pause_location = await EvaluateAndCheck (eval_expr, debugger_test_loc, line, col, method_name);
var locals = await GetProperties (pause_location ["callFrames"][frame_idx]["callFrameId"].Value<string> ());
Assert.Single (locals);
CheckObject (locals, "c", "DebuggerTests.Container");
var c_props = await GetObjectOnFrame (pause_location ["callFrames"][frame_idx], "c");
await CheckProps (c_props, new {
id = TString ("c#id"),
ClassArrayProperty = TArray ("DebuggerTests.SimpleClass[]", 3),
ClassArrayField = TArray ("DebuggerTests.SimpleClass[]", 3),
PointsProperty = TArray ("DebuggerTests.Point[]", 2),
PointsField = TArray ("DebuggerTests.Point[]", 2)
},
"c"
);
await CompareObjectPropertiesFor (c_props, "ClassArrayProperty",
new [] {
TSimpleClass (5, -2, "ClassArrayProperty#Id#0", "Green"),
TSimpleClass (30, 1293, "ClassArrayProperty#Id#1", "Green"),
TObject ("DebuggerTests.SimpleClass", is_null: true)
},
label: "InspectLocalsWithStructsStaticAsync");
await CompareObjectPropertiesFor (c_props, "ClassArrayField",
new [] {
TObject ("DebuggerTests.SimpleClass", is_null: true),
TSimpleClass (5, -2, "ClassArrayField#Id#1", "Blue"),
TSimpleClass (30, 1293, "ClassArrayField#Id#2", "Green")
},
label: "c#ClassArrayField");
await CompareObjectPropertiesFor (c_props, "PointsProperty",
new [] {
TPoint (5, -2, "PointsProperty#Id#0", "Green"),
TPoint (123, 0, "PointsProperty#Id#1", "Blue"),
},
label: "c#PointsProperty");
await CompareObjectPropertiesFor (c_props, "PointsField",
new [] {
TPoint (5, -2, "PointsField#Id#0", "Green"),
TPoint (123, 0, "PointsField#Id#1", "Blue"),
},
label: "c#PointsField");
});
}
[Theory]
[InlineData (false)]
[InlineData (true)]
public async Task InspectValueTypeArrayLocalsStaticAsync (bool use_cfo)
{
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
int line = 143;
int col = 3;
string entry_method_name = "[debugger-test] DebuggerTests.ArrayTestsClass:ValueTypeLocalsAsync";
string method_name = "MoveNext"; // BUG: this should be ValueTypeLocalsAsync
int frame_idx = 0;
await Ready();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
ctx.UseCallFunctionOnBeforeGetProperties = use_cfo;
var debugger_test_loc = "dotnet://debugger-test.dll/debugger-array-test.cs";
await SetBreakpoint (debugger_test_loc, line, col);
var eval_expr = "window.setTimeout(function() { invoke_static_method_async ("
+ $"'{entry_method_name}', false" // *false* here keeps us only in the static method
+ "); }, 1);";
var pause_location = await EvaluateAndCheck (eval_expr, debugger_test_loc, line, col, method_name);
var frame_locals = await GetProperties (pause_location ["callFrames"][frame_idx]["callFrameId"].Value<string> ());
await CheckProps (frame_locals, new {
call_other = TBool (false),
gvclass_arr = TArray ("DebuggerTests.SimpleGenericStruct<DebuggerTests.Point>[]", 2),
gvclass_arr_empty = TArray ("DebuggerTests.SimpleGenericStruct<DebuggerTests.Point>[]"),
gvclass_arr_null = TObject ("DebuggerTests.SimpleGenericStruct<DebuggerTests.Point>[]", is_null: true),
gvclass = TValueType ("DebuggerTests.SimpleGenericStruct<DebuggerTests.Point>"),
// BUG: this shouldn't be null!
points = TObject ("DebuggerTests.Point[]", is_null: true)
}, "ValueTypeLocalsAsync#locals");
var local_var_name_prefix = "gvclass";
await CompareObjectPropertiesFor (frame_locals, local_var_name_prefix, new {
Id = TString (null),
Color = TEnum ("DebuggerTests.RGB", "Red"),
Value = TPoint (0, 0, null, "Red")
});
await CompareObjectPropertiesFor (frame_locals, $"{local_var_name_prefix}_arr",
new [] {
new {
Id = TString ("gvclass_arr#1#Id"),
Color = TEnum ("DebuggerTests.RGB", "Red"),
Value = TPoint (100, 200, "gvclass_arr#1#Value#Id", "Red")
},
new {
Id = TString ("gvclass_arr#2#Id"),
Color = TEnum ("DebuggerTests.RGB", "Blue"),
Value = TPoint (10, 20, "gvclass_arr#2#Value#Id", "Green")
}
}
);
await CompareObjectPropertiesFor (frame_locals, $"{local_var_name_prefix}_arr_empty",
new object[0]);
});
}
// TODO: Check previous frame too
[Theory]
[InlineData (false)]
[InlineData (true)]
public async Task InspectValueTypeArrayLocalsInstanceAsync (bool use_cfo)
{
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
int line = 155;
int col = 3;
string entry_method_name = "[debugger-test] DebuggerTests.ArrayTestsClass:ValueTypeLocalsAsync";
int frame_idx = 0;
await Ready();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
ctx.UseCallFunctionOnBeforeGetProperties = use_cfo;
var debugger_test_loc = "dotnet://debugger-test.dll/debugger-array-test.cs";
await SetBreakpoint (debugger_test_loc, line, col);
var eval_expr = "window.setTimeout(function() { invoke_static_method_async ("
+ $"'{entry_method_name}', true"
+ "); }, 1);";
// BUG: Should be InspectValueTypeArrayLocalsInstanceAsync
var pause_location = await EvaluateAndCheck (eval_expr, debugger_test_loc, line, col, "MoveNext");
var frame_locals = await GetProperties (pause_location ["callFrames"][frame_idx]["callFrameId"].Value<string> ());
await CheckProps (frame_locals, new {
t1 = TObject ("DebuggerTests.SimpleGenericStruct<DebuggerTests.Point>"),
@this = TObject ("DebuggerTests.ArrayTestsClass"),
point_arr = TArray ("DebuggerTests.Point[]", 2),
point = TValueType ("DebuggerTests.Point")
}, "InspectValueTypeArrayLocalsInstanceAsync#locals");
await CompareObjectPropertiesFor (frame_locals, "t1",
new {
Id = TString ("gvclass_arr#1#Id"),
Color = TEnum ("DebuggerTests.RGB", "Red"),
Value = TPoint (100, 200, "gvclass_arr#1#Value#Id", "Red")
});
await CompareObjectPropertiesFor (frame_locals, "point_arr",
new [] {
TPoint (5, -2, "point_arr#Id#0", "Red"),
TPoint (123, 0, "point_arr#Id#1", "Blue"),
}
);
await CompareObjectPropertiesFor (frame_locals, "point",
TPoint (45, 51, "point#Id", "Green"));
});
}
[Theory]
[InlineData (false)]
[InlineData (true)]
public async Task InspectValueTypeArrayLocalsInAsyncStaticStructMethod (bool use_cfo)
{
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
int line = 222;
int col = 3;
string entry_method_name = "[debugger-test] DebuggerTests.ArrayTestsClass:EntryPointForStructMethod";
int frame_idx = 0;
await Ready();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
ctx.UseCallFunctionOnBeforeGetProperties = use_cfo;
var debugger_test_loc = "dotnet://debugger-test.dll/debugger-array-test.cs";
await SetBreakpoint (debugger_test_loc, line, col);
//await SetBreakpoint (debugger_test_loc, 143, 3);
var eval_expr = "window.setTimeout(function() { invoke_static_method_async ("
+ $"'{entry_method_name}', false"
+ "); }, 1);";
// BUG: Should be InspectValueTypeArrayLocalsInstanceAsync
var pause_location = await EvaluateAndCheck (eval_expr, debugger_test_loc, line, col, "MoveNext");
var frame_locals = await GetProperties (pause_location ["callFrames"][frame_idx]["callFrameId"].Value<string> ());
await CheckProps (frame_locals, new {
call_other = TBool (false),
local_i = TNumber (5),
sc = TSimpleClass (10, 45, "sc#Id", "Blue")
}, "InspectValueTypeArrayLocalsInAsyncStaticStructMethod#locals");
});
}
[Theory]
[InlineData (false)]
[InlineData (true)]
public async Task InspectValueTypeArrayLocalsInAsyncInstanceStructMethod (bool use_cfo)
{
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
int line = 229;
int col = 3;
string entry_method_name = "[debugger-test] DebuggerTests.ArrayTestsClass:EntryPointForStructMethod";
int frame_idx = 0;
await Ready();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
ctx.UseCallFunctionOnBeforeGetProperties = use_cfo;
var debugger_test_loc = "dotnet://debugger-test.dll/debugger-array-test.cs";
await SetBreakpoint (debugger_test_loc, line, col);
var eval_expr = "window.setTimeout(function() { invoke_static_method_async ("
+ $"'{entry_method_name}', true"
+ "); }, 1);";
// BUG: Should be InspectValueTypeArrayLocalsInstanceAsync
var pause_location = await EvaluateAndCheck (eval_expr, debugger_test_loc, line, col, "MoveNext");
var frame_locals = await GetProperties (pause_location ["callFrames"][frame_idx]["callFrameId"].Value<string> ());
await CheckProps (frame_locals, new {
sc_arg = TObject ("DebuggerTests.SimpleClass"),
@this = TValueType ("DebuggerTests.Point"),
local_gs = TValueType ("DebuggerTests.SimpleGenericStruct<int>")
},
"locals#0");
await CompareObjectPropertiesFor (frame_locals, "local_gs",
new {
Id = TString ("local_gs#Id"),
Color = TEnum ("DebuggerTests.RGB", "Green"),
Value = TNumber (4)
},
label: "local_gs#0");
await CompareObjectPropertiesFor (frame_locals, "sc_arg",
TSimpleClass (10, 45, "sc_arg#Id", "Blue"),
label: "sc_arg#0");
await CompareObjectPropertiesFor (frame_locals, "this",
TPoint (90, -4, "point#Id", "Green"),
label: "this#0");
});
}
}
}
@@ -0,0 +1,522 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Xunit;
using WebAssembly.Net.Debugging;
namespace DebuggerTests
{
public class CallFunctionOnTests : DebuggerTestBase {
// This tests `callFunctionOn` with a function that the vscode-js-debug extension uses
// Using this here as a non-trivial test case
[Theory]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, 10, false)]
[InlineData ("big_array_js_test (0);", "/other.js", 5, 1, 0, true)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, 10, false)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 0);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, 0, true)]
public async Task CheckVSCodeTestFunction1 (string eval_fn, string bp_loc, int line, int col, int len, bool roundtrip)
{
string vscode_fn0 = "function(){const e={__proto__:this.__proto__},t=Object.getOwnPropertyNames(this);for(let r=0;r<t.length;++r){const n=t[r],i=n>>>0;if(String(i>>>0)===n&&i>>>0!=4294967295)continue;const a=Object.getOwnPropertyDescriptor(this,n);a&&Object.defineProperty(e,n,a)}return e}";
await RunCallFunctionOn (eval_fn, vscode_fn0, "big", bp_loc, line, col, res_array_len: len, roundtrip: roundtrip,
test_fn: async (result) => {
var is_js = bp_loc.EndsWith (".js", StringComparison.Ordinal);
var obj_accessors = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = true,
ownProperties = false
}), ctx.token);
if (is_js)
await CheckProps (obj_accessors.Value ["result"], new { __proto__ = TIgnore () }, "obj_accessors");
else
AssertEqual (0, obj_accessors.Value ["result"]?.Count (), "obj_accessors-count");
// Check for a __proto__ object
// isOwn = true, accessorPropertiesOnly = false
var obj_own = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = false,
ownProperties = true
}), ctx.token);
await CheckProps (obj_own.Value ["result"], new {
length = TNumber (len),
// __proto__ = TArray (type, 0) // Is this one really required?
}, $"obj_own", num_fields: is_js ? 2 : 1);
});
}
void CheckJFunction (JToken actual, string className, string label)
{
AssertEqual ("function", actual ["type"]?.Value<string> (), $"{label}-type");
AssertEqual (className, actual ["className"]?.Value<string> (), $"{label}-className");
}
// This tests `callFunctionOn` with a function that the vscode-js-debug extension uses
// Using this here as a non-trivial test case
[Theory]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, 10)]
[InlineData ("big_array_js_test (0);", "/other.js", 5, 1, 0)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, 10)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 0);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, 0)]
public async Task CheckVSCodeTestFunction2 (string eval_fn, string bp_loc, int line, int col, int len)
{
var fetch_start_idx = 2;
var num_elems_fetch = 3;
string vscode_fn1 = "function(e,t){const r={},n=-1===e?0:e,i=-1===t?this.length:e+t;for(let e=n;e<i&&e<this.length;++e){const t=Object.getOwnPropertyDescriptor(this,e);t&&Object.defineProperty(r,e,t)}return r}";
await RunCallFunctionOn (eval_fn, vscode_fn1, "big", bp_loc, line, col,
fn_args: JArray.FromObject (new [] {
new { @value = fetch_start_idx },
new { @value = num_elems_fetch }
}),
test_fn: async (result) => {
var is_js = bp_loc.EndsWith (".js", StringComparison.Ordinal);
// isOwn = false, accessorPropertiesOnly = true
var obj_accessors = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = true,
ownProperties = false
}), ctx.token);
if (is_js)
await CheckProps (obj_accessors.Value ["result"], new { __proto__ = TIgnore () }, "obj_accessors");
else
AssertEqual (0, obj_accessors.Value ["result"]?.Count (), "obj_accessors-count");
// Ignoring the __proto__ property
// isOwn = true, accessorPropertiesOnly = false
var obj_own = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = false,
ownProperties = true
}), ctx.token);
var obj_own_val = obj_own.Value ["result"];
var num_elems_recd = len == 0 ? 0 : num_elems_fetch;
AssertEqual (is_js ? num_elems_recd + 1 : num_elems_recd, obj_own_val.Count (), $"obj_own-count");
if (is_js)
CheckObject (obj_own_val, "__proto__", "Object");
for (int i = fetch_start_idx; i < fetch_start_idx + num_elems_recd; i ++)
CheckNumber (obj_own_val, i.ToString (), 1000 + i);
});
}
[Theory]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, false)]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, true)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, false)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, true)]
public async Task RunOnArrayReturnEmptyArray (string eval_fn, string bp_loc, int line, int col, bool roundtrip)
{
var ret_len = 0;
await RunCallFunctionOn (eval_fn,
"function () { return []; }",
"big", bp_loc, line, col,
res_array_len: ret_len,
roundtrip: roundtrip,
test_fn: async (result) => {
var is_js = bp_loc.EndsWith (".js", StringComparison.Ordinal);
// getProperties (isOwn = false, accessorPropertiesOnly = true)
var obj_accessors = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = true,
ownProperties = false
}), ctx.token);
if (is_js)
await CheckProps (obj_accessors.Value ["result"], new { __proto__ = TIgnore () }, "obj_accessors");
else
AssertEqual (0, obj_accessors.Value ["result"]?.Count (), "obj_accessors-count");
// getProperties (isOwn = true, accessorPropertiesOnly = false)
var obj_own = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = false,
ownProperties = true
}), ctx.token);
await CheckProps (obj_own.Value ["result"], new {
length = TNumber (ret_len),
// __proto__ returned by js
}, $"obj_own", num_fields: is_js ? 2 : 1);
});
}
[Theory]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, false)]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, true)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, false)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, true)]
public async Task RunOnArrayReturnArray (string eval_fn, string bp_loc, int line, int col, bool roundtrip)
{
var ret_len = 5;
await RunCallFunctionOn (eval_fn,
"function (m) { return Object.values (this).filter ((k, i) => i%m == 0); }",
"big", bp_loc, line, col,
fn_args: JArray.FromObject (new [] { new { value = 2 } }),
res_array_len: ret_len,
roundtrip: roundtrip,
test_fn: async (result) => {
var is_js = bp_loc.EndsWith (".js");
// getProperties (own=false)
var obj_accessors = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = true,
ownProperties = false
}), ctx.token);
if (is_js)
await CheckProps (obj_accessors.Value ["result"], new { __proto__ = TIgnore () }, "obj_accessors");
else
AssertEqual (0, obj_accessors.Value ["result"]?.Count (), "obj_accessors-count");
// getProperties (own=true)
// isOwn = true, accessorPropertiesOnly = false
var obj_own = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = false,
ownProperties = true
}), ctx.token);
// AssertEqual (2, obj_own.Value ["result"].Count (), $"{label}-obj_own.count");
var obj_own_val = obj_own.Value ["result"];
await CheckProps (obj_own_val, new {
length = TNumber (ret_len),
// __proto__ returned by JS
}, $"obj_own", num_fields: (is_js ? ret_len + 2 : ret_len + 1));
for (int i = 0; i < ret_len; i ++)
CheckNumber (obj_own_val, i.ToString (), i*2 + 1000);
});
}
[Theory]
[InlineData (false)]
[InlineData (true)]
public async Task RunOnVTArray (bool roundtrip)
=> await RunCallFunctionOn (
"invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);",
"function (m) { return Object.values (this).filter ((k, i) => i%m == 0); }",
"ss_arr",
"dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3,
fn_args: JArray.FromObject (new [] { new { value = 2 } }),
res_array_len: 5,
roundtrip: roundtrip,
test_fn: async (result) => {
var ret_len = 5;
// getProperties (own=false)
var obj_accessors = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = true,
ownProperties = false
}), ctx.token);
AssertEqual (0, obj_accessors.Value ["result"]?.Count (), "obj_accessors-count");
// getProperties (own=true)
// isOwn = true, accessorPropertiesOnly = false
var obj_own = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = false,
ownProperties = true
}), ctx.token);
var obj_own_val = obj_own.Value ["result"];
await CheckProps (obj_own_val, new {
length = TNumber (ret_len),
// __proto__ returned by JS
}, "obj_own", num_fields: ret_len + 1);
for (int i = 0; i < ret_len; i ++) {
var act_i = CheckValueType (obj_own_val, i.ToString (), "Math.SimpleStruct");
// Valuetypes can get sent as part of the container's getProperties, so ensure that we can access it
var act_i_props = await GetProperties (act_i ["value"]["objectId"]?.Value<string> ());
await CheckProps (act_i_props, new {
dt = TValueType ("System.DateTime", new DateTime (2020 + (i*2), 1, 2, 3, 4, 5).ToString ()),
gs = TValueType ("Math.GenericStruct<System.DateTime>")
}, "obj_own ss_arr[{i}]");
var gs_props = await GetObjectOnLocals (act_i_props, "gs");
await CheckProps (gs_props, new {
List = TObject ("System.Collections.Generic.List<System.DateTime>", is_null: true),
StringField = TString ($"ss_arr # {i*2} # gs # StringField")
}, "obj_own ss_arr[{i}].gs");
}
});
[Theory]
[InlineData (false)]
[InlineData (true)]
public async Task RunOnCFOValueTypeResult (bool roundtrip)
=> await RunCallFunctionOn (
eval_fn: "invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);",
fn_decl: "function () { return this; }",
local_name: "simple_struct",
bp_loc: "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3,
roundtrip: roundtrip,
test_fn: async (result) => {
// getProperties (own=false)
var obj_accessors = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = true,
ownProperties = false
}), ctx.token);
AssertEqual (0, obj_accessors.Value ["result"].Count (), "obj_accessors-count");
// getProperties (own=true)
// isOwn = true, accessorPropertiesOnly = false
var obj_own = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = false,
ownProperties = true
}), ctx.token);
var obj_own_val = obj_own.Value ["result"];
var dt = new DateTime (2020, 1, 2, 3, 4, 5);
await CheckProps (obj_own_val, new {
dt = TValueType ("System.DateTime", dt.ToString ()),
gs = TValueType ("Math.GenericStruct<System.DateTime>")
}, $"obj_own-props");
await CheckDateTime (obj_own_val, "dt", dt);
var gs_props = await GetObjectOnLocals (obj_own_val, "gs");
await CheckProps (gs_props, new {
List = TObject ("System.Collections.Generic.List<System.DateTime>", is_null: true),
StringField = TString ($"simple_struct # gs # StringField")
}, "simple_struct.gs-props");
});
[Theory]
[InlineData (false)]
[InlineData (true)]
public async Task RunOnJSObject (bool roundtrip)
=> await RunCallFunctionOn (
"object_js_test ();",
"function () { return this; }",
"obj", "/other.js", 14, 1,
fn_args: JArray.FromObject (new [] { new { value = 2 } }),
roundtrip: roundtrip,
test_fn: async (result) => {
// getProperties (own=false)
var obj_accessors = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = true,
ownProperties = false
}), ctx.token);
await CheckProps (obj_accessors.Value ["result"], new { __proto__ = TIgnore () }, "obj_accessors");
// getProperties (own=true)
// isOwn = true, accessorPropertiesOnly = false
var obj_own = await ctx.cli.SendCommand ("Runtime.getProperties", JObject.FromObject (new {
objectId = result.Value ["result"]["objectId"].Value<string> (),
accessorPropertiesOnly = false,
ownProperties = true
}), ctx.token);
var obj_own_val = obj_own.Value ["result"];
await CheckProps (obj_own_val, new {
a_obj = TObject ("Object"),
b_arr = TArray ("Array", 2)
}, "obj_own", num_fields: 3);
});
[Theory]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, false)]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, true)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, false)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, true)]
public async Task RunOnArrayReturnObjectArrayByValue (string eval_fn, string bp_loc, int line, int col, bool roundtrip)
{
var ret_len = 5;
await RunCallFunctionOn (eval_fn,
"function () { return Object.values (this).filter ((k, i) => i%2 == 0); }",
"big", bp_loc, line, col, returnByValue: true, roundtrip: roundtrip,
test_fn: async (result) => {
// Check cfo result
AssertEqual ("object", result.Value ["result"]["type"]?.Value<string> (), "cfo-res-type");
AssertEqual (1, result.Value.Values ().Count (), "cfo-res-value-count");
var actual = result.Value ["result"]?["value"].Values<JToken> ().ToArray ();
for (int i = 0; i < ret_len; i ++) {
var exp_num = i*2 + 1000;
if (bp_loc.EndsWith (".js", StringComparison.Ordinal))
AssertEqual (exp_num, actual [i].Value<int> (), $"[{i}]");
else {
AssertEqual ("number", actual [i]?["type"]?.Value<string> (), $"[{i}]-type");
AssertEqual (exp_num.ToString (), actual [i]?["description"]?.Value<string> (), $"[{i}]-description");
AssertEqual (exp_num, actual [i]?["value"]?.Value<int> (), $"[{i}]-value");
}
}
await Task.CompletedTask;
});
}
[Theory]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, false)]
[InlineData ("big_array_js_test (10);", "/other.js", 5, 1, true)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, false)]
[InlineData ("invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10);", "dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3, true)]
public async Task RunOnArrayReturnArrayByValue (string eval_fn, string bp_loc, int line, int col, bool roundtrip)
=> await RunCallFunctionOn (eval_fn,
"function () { return Object.getOwnPropertyNames (this); }",
"big", bp_loc, line, col, returnByValue: true,
roundtrip: roundtrip,
test_fn: async (result) => {
// Check cfo result
AssertEqual ("object", result.Value ["result"]["type"]?.Value<string> (), "cfo-res-type");
var exp = new JArray ();
for (int i = 0; i < 10; i ++)
exp.Add (i.ToString ());
exp.Add ("length");
var actual = result.Value ["result"]?["value"];
if (!JObject.DeepEquals (exp, actual)) {
Assert.True (false, $"Results don't match.\nExpected: {exp}\nActual: {actual}");
}
await Task.CompletedTask;
});
[Theory]
[InlineData (null)]
[InlineData (false)]
[InlineData (true)]
public async Task CheckErrorsWithSilent (bool? silent)
{
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await Ready();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
await SetBreakpoint ("dotnet://debugger-test.dll/debugger-cfo-test.cs", 19, 3);
// callFunctionOn
var eval_expr = "window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.CallFunctionOnTest:LocalsTest', 10); }, 1);";
var result = await ctx.cli.SendCommand ("Runtime.evaluate", JObject.FromObject (new { expression = eval_expr }), ctx.token);
var pause_location = await ctx.insp.WaitFor (Inspector.PAUSE);
// Check the object at the bp
var cfo_args = JObject.FromObject (new {
functionDeclaration = "function () { throw Error ('test error'); }",
objectId = "dotnet:object:xyasd",
});
if (silent.HasValue)
cfo_args ["silent"] = silent;
// callFunctionOn
result = await ctx.cli.SendCommand ("Runtime.callFunctionOn", cfo_args, ctx.token);
Assert.True ((silent ?? false) == result.IsOk);
});
}
/*
* 1. runs `Runtime.callFunctionOn` on the objectId,
* if @roundtrip == false, then
* -> calls @test_fn for that result (new objectId)
* else
* -> runs it again on the *result's* objectId.
* -> calls @test_fn on the *new* result objectId
*
* Returns: result of `Runtime.callFunctionOn`
*/
async Task RunCallFunctionOn (string eval_fn, string fn_decl, string local_name, string bp_loc, int line, int col, int res_array_len = -1,
Func<Result, Task> test_fn = null, bool returnByValue = false, JArray fn_args = null, bool roundtrip = false)
{
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await Ready();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
await SetBreakpoint (bp_loc, line, col);
// callFunctionOn
var eval_expr = $"window.setTimeout(function() {{ {eval_fn} }}, 1);";
var result = await ctx.cli.SendCommand ("Runtime.evaluate", JObject.FromObject (new { expression = eval_expr }), ctx.token);
var pause_location = await ctx.insp.WaitFor (Inspector.PAUSE);
// Um for js we get "scriptId": "6"
// CheckLocation (bp_loc, line, col, ctx.scripts, pause_location ["callFrames"][0]["location"]);
// Check the object at the bp
var frame_locals = await GetProperties (pause_location ["callFrames"][0]["scopeChain"][0]["object"]["objectId"].Value<string> ());
var obj = GetAndAssertObjectWithName (frame_locals, local_name);
var obj_id = obj ["value"]["objectId"].Value<string> ();
var cfo_args = JObject.FromObject (new {
functionDeclaration = fn_decl,
objectId = obj_id
});
if (fn_args != null)
cfo_args ["arguments"] = fn_args;
if (returnByValue)
cfo_args ["returnByValue"] = returnByValue;
// callFunctionOn
result = await ctx.cli.SendCommand ("Runtime.callFunctionOn", cfo_args, ctx.token);
await CheckCFOResult (result);
// If it wasn't `returnByValue`, then try to run a new function
// on that *returned* object
// This second function, just returns the object as-is, so the same
// test_fn is re-usable.
if (!returnByValue && roundtrip) {
cfo_args = JObject.FromObject (new {
functionDeclaration = "function () { return this; }",
objectId = result.Value ["result"]["objectId"]?.Value<string> ()
});
if (fn_args != null)
cfo_args ["arguments"] = fn_args;
result = await ctx.cli.SendCommand ("Runtime.callFunctionOn", cfo_args, ctx.token);
await CheckCFOResult (result);
}
if (test_fn != null)
await test_fn (result);
return;
async Task CheckCFOResult (Result result)
{
if (returnByValue)
return;
if (res_array_len < 0)
await CheckValue (result.Value ["result"], TObject ("Object"), $"cfo-res");
else
await CheckValue (result.Value ["result"], TArray ("Array", res_array_len), $"cfo-res");
}
});
}
}
}
@@ -0,0 +1,61 @@
using System;
using System.Threading.Tasks;
using Xunit;
using System.Globalization;
namespace DebuggerTests
{
public class DateTimeList : DebuggerTestBase {
[Theory]
[InlineData ("en-US")]
[InlineData ("de-DE")]
[InlineData ("ka-GE")]
[InlineData ("hu-HU")]
// Currently not passing tests. Issue #19743
// [InlineData ("ja-JP")]
// [InlineData ("es-ES")]
public async Task CheckDateTimeLocale (string locale) {
var insp = new Inspector ();
var scripts = SubscribeToScripts(insp);
await Ready();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
var debugger_test_loc = "dotnet://debugger-test.dll/debugger-datetime-test.cs";
await SetBreakpoint (debugger_test_loc, 20, 3);
var pause_location = await EvaluateAndCheck (
"window.setTimeout(function() { invoke_static_method ('[debugger-test] DebuggerTests.DateTimeTest:LocaleTest',"
+ $"'{locale}'); }}, 1);",
debugger_test_loc, 20, 3, "LocaleTest",
locals_fn: (locals) => {
DateTimeFormatInfo dtfi = CultureInfo.GetCultureInfo(locale).DateTimeFormat;
CultureInfo.CurrentCulture = new CultureInfo (locale, false);
DateTime dt = new DateTime (2020, 1, 2, 3, 4, 5);
string dt_str = dt.ToString();
var fdtp = dtfi.FullDateTimePattern;
var ldp = dtfi.LongDatePattern;
var ltp = dtfi.LongTimePattern;
var sdp = dtfi.ShortDatePattern;
var stp = dtfi.ShortTimePattern;
CheckString(locals, "fdtp", fdtp);
CheckString(locals, "ldp", ldp);
CheckString(locals, "ltp", ltp);
CheckString(locals, "sdp", sdp);
CheckString(locals, "stp", stp);
CheckDateTime(locals, "dt", dt);
CheckString(locals, "dt_str", dt_str);
}
);
});
}
}
}
@@ -0,0 +1,284 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Xunit;
using WebAssembly.Net.Debugging;
namespace DebuggerTests
{
public class DelegateTests : DebuggerTestBase {
[Theory]
[InlineData (0, 45, 2, "DelegatesTest", false)]
[InlineData (0, 45, 2, "DelegatesTest", true)]
[InlineData (2, 90, 2, "InnerMethod2", false)]
[InlineData (2, 90, 2, "InnerMethod2", true)]
public async Task InspectLocalsWithDelegatesAtBreakpointSite (int frame, int line, int col, string method_name, bool use_cfo) =>
await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-test.cs", line, col, method_name,
"window.setTimeout(function() { invoke_delegates_test (); }, 1);",
use_cfo: use_cfo,
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties(pause_location["callFrames"][frame]["callFrameId"].Value<string>());
await CheckProps (locals, new {
fn_func = TDelegate ("System.Func<Math, bool>", "bool <DelegatesTest>|(Math)"),
fn_func_null = TObject ("System.Func<Math, bool>", is_null: true),
fn_func_arr = TArray ("System.Func<Math, bool>[]", 1),
fn_del = TDelegate ("Math.IsMathNull", "bool IsMathNullDelegateTarget (Math)"),
fn_del_null = TObject ("Math.IsMathNull", is_null: true),
fn_del_arr = TArray ("Math.IsMathNull[]", 1),
// Unused locals
fn_func_unused = TDelegate ("System.Func<Math, bool>", "bool <DelegatesTest>|(Math)"),
fn_func_null_unused = TObject ("System.Func<Math, bool>", is_null: true),
fn_func_arr_unused = TArray ("System.Func<Math, bool>[]", 1),
fn_del_unused = TDelegate ("Math.IsMathNull", "bool IsMathNullDelegateTarget (Math)"),
fn_del_null_unused = TObject ("Math.IsMathNull", is_null: true),
fn_del_arr_unused = TArray ("Math.IsMathNull[]", 1),
res = TBool (false),
m_obj = TObject ("Math")
}, "locals");
await CompareObjectPropertiesFor (locals, "fn_func_arr", new [] {
TDelegate (
"System.Func<Math, bool>",
"bool <DelegatesTest>|(Math)")
}, "locals#fn_func_arr");
await CompareObjectPropertiesFor (locals, "fn_del_arr", new [] {
TDelegate (
"Math.IsMathNull",
"bool IsMathNullDelegateTarget (Math)")
}, "locals#fn_del_arr");
await CompareObjectPropertiesFor (locals, "fn_func_arr_unused", new [] {
TDelegate (
"System.Func<Math, bool>",
"bool <DelegatesTest>|(Math)")
}, "locals#fn_func_arr_unused");
await CompareObjectPropertiesFor (locals, "fn_del_arr_unused", new [] {
TDelegate (
"Math.IsMathNull",
"bool IsMathNullDelegateTarget (Math)")
}, "locals#fn_del_arr_unused");
}
);
[Theory]
[InlineData (0, 190, 2, "DelegatesSignatureTest", false)]
[InlineData (0, 190, 2, "DelegatesSignatureTest", true)]
[InlineData (2, 90, 2, "InnerMethod2", false)]
[InlineData (2, 90, 2, "InnerMethod2", true)]
public async Task InspectDelegateSignaturesWithFunc (int frame, int line, int col, string bp_method, bool use_cfo)
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-test.cs",
line, col,
bp_method,
"window.setTimeout (function () { invoke_static_method ('[debugger-test] Math:DelegatesSignatureTest'); }, 1)",
use_cfo: use_cfo,
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][frame]["callFrameId"].Value<string>());
await CheckProps (locals, new {
fn_func = TDelegate ("System.Func<Math, Math.GenericStruct<Math.GenericStruct<int[]>>, Math.GenericStruct<bool[]>>",
"Math.GenericStruct<bool[]> <DelegatesSignatureTest>|(Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
fn_func_del = TDelegate ("System.Func<Math, Math.GenericStruct<Math.GenericStruct<int[]>>, Math.GenericStruct<bool[]>>",
"Math.GenericStruct<bool[]> DelegateTargetForSignatureTest (Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
fn_func_null = TObject ("System.Func<Math, Math.GenericStruct<Math.GenericStruct<int[]>>, Math.GenericStruct<bool[]>>", is_null: true),
fn_func_only_ret= TDelegate ("System.Func<bool>", "bool <DelegatesSignatureTest>|()"),
fn_func_arr = TArray ("System.Func<Math, Math.GenericStruct<Math.GenericStruct<int[]>>, Math.GenericStruct<bool[]>>[]", 1),
fn_del = TDelegate ("Math.DelegateForSignatureTest",
"Math.GenericStruct<bool[]> DelegateTargetForSignatureTest (Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
fn_del_l = TDelegate ("Math.DelegateForSignatureTest",
"Math.GenericStruct<bool[]> <DelegatesSignatureTest>|(Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
fn_del_null = TObject ("Math.DelegateForSignatureTest", is_null: true),
fn_del_arr = TArray ("Math.DelegateForSignatureTest[]", 2),
m_obj = TObject ("Math"),
gs_gs = TValueType ("Math.GenericStruct<Math.GenericStruct<int[]>>"),
fn_void_del = TDelegate ("Math.DelegateWithVoidReturn",
"void DelegateTargetWithVoidReturn (Math.GenericStruct<int[]>)"),
fn_void_del_arr = TArray ("Math.DelegateWithVoidReturn[]", 1),
fn_void_del_null= TObject ("Math.DelegateWithVoidReturn", is_null: true),
gs = TValueType ("Math.GenericStruct<int[]>"),
rets = TArray ("Math.GenericStruct<bool[]>[]", 6)
}, "locals");
await CompareObjectPropertiesFor (locals, "fn_func_arr", new [] {
TDelegate (
"System.Func<Math, Math.GenericStruct<Math.GenericStruct<int[]>>, Math.GenericStruct<bool[]>>",
"Math.GenericStruct<bool[]> <DelegatesSignatureTest>|(Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
}, "locals#fn_func_arr");
await CompareObjectPropertiesFor (locals, "fn_del_arr", new [] {
TDelegate (
"Math.DelegateForSignatureTest",
"Math.GenericStruct<bool[]> DelegateTargetForSignatureTest (Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
TDelegate (
"Math.DelegateForSignatureTest",
"Math.GenericStruct<bool[]> <DelegatesSignatureTest>|(Math,Math.GenericStruct<Math.GenericStruct<int[]>>)")
}, "locals#fn_del_arr");
await CompareObjectPropertiesFor (locals, "fn_void_del_arr", new [] {
TDelegate (
"Math.DelegateWithVoidReturn",
"void DelegateTargetWithVoidReturn (Math.GenericStruct<int[]>)")
}, "locals#fn_void_del_arr");
});
[Theory]
[InlineData (0, 211, 2, "ActionTSignatureTest", false)]
[InlineData (0, 211, 2, "ActionTSignatureTest", true)]
[InlineData (2, 90, 2, "InnerMethod2", false)]
[InlineData (2, 90, 2, "InnerMethod2", true)]
public async Task ActionTSignatureTest (int frame, int line, int col, string bp_method, bool use_cfo)
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-test.cs", line, col,
bp_method,
"window.setTimeout (function () { invoke_static_method ('[debugger-test] Math:ActionTSignatureTest'); }, 1)",
use_cfo: use_cfo,
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][frame]["callFrameId"].Value<string>());
await CheckProps (locals, new
{
fn_action = TDelegate ("System.Action<Math.GenericStruct<int[]>>",
"void <ActionTSignatureTest>|(Math.GenericStruct<int[]>)"),
fn_action_del = TDelegate ("System.Action<Math.GenericStruct<int[]>>",
"void DelegateTargetWithVoidReturn (Math.GenericStruct<int[]>)"),
fn_action_bare = TDelegate ("System.Action",
"void|()"),
fn_action_null = TObject ("System.Action<Math.GenericStruct<int[]>>", is_null: true),
fn_action_arr = TArray ("System.Action<Math.GenericStruct<int[]>>[]", 3),
gs = TValueType ("Math.GenericStruct<int[]>"),
}, "locals");
await CompareObjectPropertiesFor (locals, "fn_action_arr", new [] {
TDelegate (
"System.Action<Math.GenericStruct<int[]>>",
"void <ActionTSignatureTest>|(Math.GenericStruct<int[]>)"),
TDelegate (
"System.Action<Math.GenericStruct<int[]>>",
"void DelegateTargetWithVoidReturn (Math.GenericStruct<int[]>)"),
TObject ("System.Action<Math.GenericStruct<int[]>>", is_null: true)
}, "locals#fn_action_arr");
});
[Theory]
[InlineData (0, 228, 2, "NestedDelegatesTest", false)]
[InlineData (0, 228, 2, "NestedDelegatesTest", true)]
[InlineData (2, 90, 2, "InnerMethod2", false)]
[InlineData (2, 90, 2, "InnerMethod2", true)]
public async Task NestedDelegatesTest (int frame, int line, int col, string bp_method, bool use_cfo)
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-test.cs", line, col,
bp_method,
"window.setTimeout (function () { invoke_static_method ('[debugger-test] Math:NestedDelegatesTest'); }, 1)",
use_cfo: use_cfo,
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][frame]["callFrameId"].Value<string>());
await CheckProps (locals, new {
fn_func = TDelegate ("System.Func<System.Func<int, bool>, bool>",
"bool <NestedDelegatesTest>|(Func<int, bool>)"),
fn_func_null = TObject ("System.Func<System.Func<int, bool>, bool>", is_null: true),
fn_func_arr = TArray ("System.Func<System.Func<int, bool>, bool>[]", 1),
fn_del_arr = TArray ("System.Func<System.Func<int, bool>, bool>[]", 1),
m_obj = TObject ("Math"),
fn_del_null = TObject ("System.Func<System.Func<int, bool>, bool>", is_null: true),
fs = TDelegate ("System.Func<int, bool>",
"bool <NestedDelegatesTest>|(int)")
}, "locals");
await CompareObjectPropertiesFor (locals, "fn_func_arr", new [] {
TDelegate (
"System.Func<System.Func<int, bool>, bool>",
"bool <NestedDelegatesTest>|(System.Func<int, bool>)")
}, "locals#fn_func_arr");
await CompareObjectPropertiesFor (locals, "fn_del_arr", new [] {
TDelegate (
"System.Func<System.Func<int, bool>, bool>",
"bool DelegateTargetForNestedFunc (Func<int, bool>)")
}, "locals#fn_del_arr");
});
[Theory]
[InlineData (0, 247, 2, "MethodWithDelegateArgs", false)]
[InlineData (0, 247, 2, "MethodWithDelegateArgs", true)]
[InlineData (2, 90, 2, "InnerMethod2", false)]
[InlineData (2, 90, 2, "InnerMethod2", true)]
public async Task DelegatesAsMethodArgsTest (int frame, int line, int col, string bp_method, bool use_cfo)
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-test.cs", line, col,
bp_method,
"window.setTimeout (function () { invoke_static_method ('[debugger-test] Math:DelegatesAsMethodArgsTest'); }, 1)",
use_cfo: use_cfo,
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][frame]["callFrameId"].Value<string>());
await CheckProps (locals, new {
@this = TObject ("Math"),
dst_arr = TArray ("Math.DelegateForSignatureTest[]", 2),
fn_func = TDelegate ("System.Func<char[], bool>",
"bool <DelegatesAsMethodArgsTest>|(char[])"),
fn_action = TDelegate ("System.Action<Math.GenericStruct<int>[]>",
"void <DelegatesAsMethodArgsTest>|(Math.GenericStruct<int>[])")
}, "locals");
await CompareObjectPropertiesFor (locals, "dst_arr", new [] {
TDelegate ("Math.DelegateForSignatureTest",
"Math.GenericStruct<bool[]> DelegateTargetForSignatureTest (Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
TDelegate ("Math.DelegateForSignatureTest",
"Math.GenericStruct<bool[]> <DelegatesAsMethodArgsTest>|(Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
}, "locals#dst_arr");
});
[Theory]
[InlineData (false)]
[InlineData (true)]
public async Task MethodWithDelegatesAsyncTest (bool use_cfo)
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-test.cs", 265, 2,
"MoveNext", //"DelegatesAsMethodArgsTestAsync"
"window.setTimeout (function () { invoke_static_method_async ('[debugger-test] Math:MethodWithDelegatesAsyncTest'); }, 1)",
use_cfo: use_cfo,
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][0]["callFrameId"].Value<string>());
await CheckProps (locals, new {
@this = TObject ("Math"),
_dst_arr = TArray ("Math.DelegateForSignatureTest[]", 2),
_fn_func = TDelegate ("System.Func<char[], bool>",
"bool <MethodWithDelegatesAsync>|(char[])"),
_fn_action = TDelegate ("System.Action<Math.GenericStruct<int>[]>",
"void <MethodWithDelegatesAsync>|(Math.GenericStruct<int>[])")
}, "locals");
await CompareObjectPropertiesFor (locals, "_dst_arr", new [] {
TDelegate (
"Math.DelegateForSignatureTest",
"Math.GenericStruct<bool[]> DelegateTargetForSignatureTest (Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
TDelegate (
"Math.DelegateForSignatureTest",
"Math.GenericStruct<bool[]> <MethodWithDelegatesAsync>|(Math,Math.GenericStruct<Math.GenericStruct<int[]>>)"),
}, "locals#dst_arr");
});
}
}
@@ -0,0 +1,204 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Xunit;
using WebAssembly.Net.Debugging;
namespace DebuggerTests
{
public class EvaluateOnCallFrameTests : DebuggerTestBase {
[Fact]
public async Task EvaluateThisProperties ()
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-evaluate-test.cs", 20, 16,
"run",
"window.setTimeout(function() { invoke_static_method_async ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })",
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][0] ["callFrameId"].Value<string> ());
var evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "a");
CheckContentValue (evaluate, "1");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "b");
CheckContentValue (evaluate, "2");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "c");
CheckContentValue (evaluate, "3");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "dt");
await CheckDateTimeValue (evaluate, new DateTime (2000, 5, 4, 3, 2, 1));
});
[Theory]
[InlineData (58, 3, "EvaluateTestsStructInstanceMethod")]
[InlineData (74, 3, "GenericInstanceMethodOnStruct<int>")]
[InlineData (97, 3, "EvaluateTestsGenericStructInstanceMethod")]
public async Task EvaluateThisPropertiesOnStruct (int line, int col, string method_name)
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-evaluate-test.cs", line, col,
method_name,
"window.setTimeout(function() { invoke_static_method_async ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })",
wait_for_event_fn: async (pause_location) => {
var evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "a");
CheckContentValue (evaluate, "1");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "b");
CheckContentValue (evaluate, "2");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "c");
CheckContentValue (evaluate, "3");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "dateTime");
await CheckDateTimeValue (evaluate, new DateTime (2020, 1, 2, 3, 4, 5));
});
[Fact]
public async Task EvaluateParameters ()
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-evaluate-test.cs", 20, 16,
"run",
"window.setTimeout(function() { invoke_static_method_async ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })",
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][0] ["callFrameId"].Value<string> ());
var evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "g");
CheckContentValue (evaluate, "100");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "h");
CheckContentValue (evaluate, "200");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "valString");
CheckContentValue (evaluate, "test");
});
[Fact]
public async Task EvaluateLocals ()
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-evaluate-test.cs", 20, 16,
"run",
"window.setTimeout(function() { invoke_static_method_async ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })",
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][0] ["callFrameId"].Value<string> ());
var evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "d");
CheckContentValue (evaluate, "101");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "e");
CheckContentValue (evaluate, "102");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "f");
CheckContentValue (evaluate, "103");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "local_dt");
await CheckDateTimeValue (evaluate, new DateTime (2010, 9, 8, 7, 6, 5));
});
[Fact]
public async Task EvaluateLocalsAsync ()
{
var bp_loc = "dotnet://debugger-test.dll/debugger-array-test.cs";
int line = 227; int col = 3;
var function_name = "MoveNext";
await CheckInspectLocalsAtBreakpointSite (
bp_loc, line, col,
function_name,
"window.setTimeout(function() { invoke_static_method_async ('[debugger-test] DebuggerTests.ArrayTestsClass:EntryPointForStructMethod', true); })",
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][0] ["callFrameId"].Value<string> ());
// sc_arg
{
var sc_arg = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "sc_arg");
await CheckValue (sc_arg, TObject ("DebuggerTests.SimpleClass"), "sc_arg#1");
var sc_arg_props = await GetProperties (sc_arg ["objectId"]?.Value<string> ());
await CheckProps (sc_arg_props, new {
X = TNumber (10),
Y = TNumber (45),
Id = TString ("sc#Id"),
Color = TEnum ("DebuggerTests.RGB", "Blue"),
PointWithCustomGetter = TSymbol ("DebuggerTests.Point { get; }")
}, "sc_arg_props#1");
}
// local_gs
{
var local_gs = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "local_gs");
await CheckValue (local_gs, TValueType ("DebuggerTests.SimpleGenericStruct<int>"), "local_gs#1");
var local_gs_props = await GetProperties (local_gs ["objectId"]?.Value<string> ());
await CheckProps (local_gs_props, new {
Id = TObject ("string", is_null: true),
Color = TEnum ("DebuggerTests.RGB", "Red"),
Value = TNumber (0)
}, "local_gs_props#1");
}
// step, check local_gs
pause_location = await StepAndCheck (StepKind.Over, bp_loc, line + 1, col, function_name);
{
var local_gs = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "local_gs");
await CheckValue (local_gs, TValueType ("DebuggerTests.SimpleGenericStruct<int>"), "local_gs#2");
var local_gs_props = await GetProperties (local_gs ["objectId"]?.Value<string> ());
await CheckProps (local_gs_props, new {
Id = TString ("local_gs#Id"),
Color = TEnum ("DebuggerTests.RGB", "Green"),
Value = TNumber (4)
}, "local_gs_props#2");
}
// step check sc_arg.Id
pause_location = await StepAndCheck (StepKind.Over, bp_loc, line + 2, col, function_name);
{
var sc_arg = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "sc_arg");
await CheckValue (sc_arg, TObject ("DebuggerTests.SimpleClass"), "sc_arg#2");
var sc_arg_props = await GetProperties (sc_arg ["objectId"]?.Value<string> ());
await CheckProps (sc_arg_props, new {
X = TNumber (10),
Y = TNumber (45),
Id = TString ("sc_arg#Id"), // <------- This changed
Color = TEnum ("DebuggerTests.RGB", "Blue"),
PointWithCustomGetter = TSymbol ("DebuggerTests.Point { get; }")
}, "sc_arg_props#2");
}
});
}
[Fact]
public async Task EvaluateExpressions ()
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-evaluate-test.cs", 20, 16,
"run",
"window.setTimeout(function() { invoke_static_method_async ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })",
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][0] ["callFrameId"].Value<string> ());
var evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "d + e");
CheckContentValue (evaluate, "203");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "e + 10");
CheckContentValue (evaluate, "112");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "a + a");
CheckContentValue (evaluate, "2");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "this.a + this.b");
CheckContentValue (evaluate, "3");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "\"test\" + \"test\"");
CheckContentValue (evaluate, "testtest");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "5 + 5");
CheckContentValue (evaluate, "10");
});
[Fact]
public async Task EvaluateThisExpressions ()
=> await CheckInspectLocalsAtBreakpointSite (
"dotnet://debugger-test.dll/debugger-evaluate-test.cs", 20, 16,
"run",
"window.setTimeout(function() { invoke_static_method_async ('[debugger-test] DebuggerTests.EvaluateTestsClass:EvaluateLocals'); })",
wait_for_event_fn: async (pause_location) => {
var locals = await GetProperties (pause_location ["callFrames"][0] ["callFrameId"].Value<string> ());
var evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "this.a");
CheckContentValue (evaluate, "1");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "this.b");
CheckContentValue (evaluate, "2");
evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "this.c");
CheckContentValue (evaluate, "3");
// FIXME: not supported yet
// evaluate = await EvaluateOnCallFrame (pause_location ["callFrames"][0] ["callFrameId"].Value<string> (), "this.dt");
// await CheckDateTimeValue (evaluate, new DateTime (2000, 5, 4, 3, 2, 1));
});
}
}
+673
View File
@@ -150,5 +150,678 @@ namespace DebuggerTests
public Task Ready ()
=> startTask;
internal DebugTestContext ctx;
internal Dictionary<string, string> dicScriptsIdToUrl;
internal Dictionary<string, string> dicFileToUrl;
internal Dictionary<string, string> SubscribeToScripts (Inspector insp) {
dicScriptsIdToUrl = new Dictionary<string, string> ();
dicFileToUrl = 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://"))
{
var dbgUrl = args["dotNetUrl"]?.Value<string>();
var arrStr = dbgUrl.Split("/");
dbgUrl = arrStr[0] + "/" + arrStr[1] + "/" + arrStr[2] + "/" + arrStr[arrStr.Length - 1];
dicScriptsIdToUrl[script_id] = dbgUrl;
dicFileToUrl[dbgUrl] = args["url"]?.Value<string>();
} else if (!String.IsNullOrEmpty (url)) {
dicFileToUrl[new Uri (url).AbsolutePath] = url;
}
await Task.FromResult (0);
});
return dicScriptsIdToUrl;
}
internal async Task CheckInspectLocalsAtBreakpointSite (string url_key, int line, int column, string function_name, string eval_expression,
Action<JToken> test_fn = null, Func<JObject, Task> wait_for_event_fn = null, bool use_cfo = false)
{
var insp = new Inspector ();
//Collect events
var scripts = SubscribeToScripts(insp);
await Ready ();
await insp.Ready (async (cli, token) => {
ctx = new DebugTestContext (cli, insp, token, scripts);
ctx.UseCallFunctionOnBeforeGetProperties = use_cfo;
var bp = await SetBreakpoint (url_key, line, column);
await EvaluateAndCheck (
eval_expression, url_key, line, column,
function_name,
wait_for_event_fn: async (pause_location) => {
//make sure we're on the right bp
Assert.Equal (bp.Value ["breakpointId"]?.ToString (), 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"]);
if (wait_for_event_fn != null)
await wait_for_event_fn(pause_location);
else
await Task.CompletedTask;
},
locals_fn: (locals) => {
if (test_fn != null)
test_fn (locals);
}
);
});
}
internal void CheckLocation (string script_loc, int line, int column, Dictionary<string, string> scripts, JToken location)
{
var loc_str = $"{ scripts[location["scriptId"].Value<string>()] }"
+ $"#{ location ["lineNumber"].Value<int> () }"
+ $"#{ location ["columnNumber"].Value<int> () }";
var expected_loc_str = $"{script_loc}#{line}#{column}";
Assert.Equal (expected_loc_str, loc_str);
}
internal void CheckNumber<T> (JToken locals, string name, T 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 <T> ());
return;
}
Assert.True(false, $"Could not find variable '{name}'");
}
internal void CheckString (JToken locals, string name, string value) {
foreach (var l in locals) {
if (name != l["name"]?.Value<string> ())
continue;
var val = l["value"];
if (value == null) {
Assert.Equal ("object", val ["type"]?.Value<string> ());
Assert.Equal ("null", val["subtype"]?.Value<string> ());
} else {
Assert.Equal ("string", val ["type"]?.Value<string> ());
Assert.Equal (value, val["value"]?.Value <string> ());
}
return;
}
Assert.True(false, $"Could not find variable '{name}'");
}
internal JToken CheckSymbol (JToken locals, string name, string value)
{
var l = GetAndAssertObjectWithName (locals, name);
var val = l["value"];
Assert.Equal ("symbol", val ["type"]?.Value<string> ());
Assert.Equal (value, val ["value"]?.Value<string> ());
return l;
}
internal JToken CheckObject (JToken locals, string name, string class_name, string subtype=null, bool is_null=false) {
var l = GetAndAssertObjectWithName (locals, name);
var val = l["value"];
Assert.Equal ("object", val ["type"]?.Value<string> ());
Assert.True (val ["isValueType"] == null || !val ["isValueType"].Value<bool> ());
Assert.Equal (class_name, val ["className"]?.Value<string> ());
var has_null_subtype = val ["subtype"] != null && val ["subtype"]?.Value<string> () == "null";
Assert.Equal (is_null, has_null_subtype);
if (subtype != null)
Assert.Equal (subtype, val ["subtype"]?.Value<string> ());
return l;
}
internal async Task CheckDateTime (JToken locals, string name, DateTime expected)
{
var obj = GetAndAssertObjectWithName(locals, name);
await CheckDateTimeValue (obj ["value"], expected);
}
internal async Task CheckDateTimeValue (JToken value, DateTime expected)
{
AssertEqual ("System.DateTime", value ["className"]?.Value<string> (), "className");
AssertEqual (expected.ToString (), value ["description"]?.Value<string> (), "className");
var members = await GetProperties (value ["objectId"]?.Value<string> ());
// not checking everything
CheckNumber (members, "Year", expected.Year);
CheckNumber (members, "Month", expected.Month);
CheckNumber (members, "Day", expected.Day);
CheckNumber (members, "Hour", expected.Hour);
CheckNumber (members, "Minute", expected.Minute);
CheckNumber (members, "Second", expected.Second);
// FIXME: check some float properties too
}
internal JToken CheckBool (JToken locals, string name, bool expected)
{
var l = GetAndAssertObjectWithName (locals, name);
var val = l["value"];
Assert.Equal ("boolean", val ["type"]?.Value<string> ());
if (val ["value"] == null)
Assert.True (false, "expected bool value not found for variable named {name}");
Assert.Equal (expected, val ["value"]?.Value<bool> ());
return l;
}
internal void CheckContentValue (JToken token, string value) {
var val = token["value"].Value<string> ();
Assert.Equal (value, val);
}
internal JToken CheckValueType (JToken locals, string name, string class_name) {
var l = GetAndAssertObjectWithName (locals, name);
var val = l["value"];
Assert.Equal ("object", val ["type"]?.Value<string> ());
Assert.True (val ["isValueType"] != null && val ["isValueType"].Value<bool> ());
Assert.Equal (class_name, val ["className"]?.Value<string> ());
return l;
}
internal JToken CheckEnum (JToken locals, string name, string class_name, string descr) {
var l = GetAndAssertObjectWithName (locals, name);
var val = l["value"];
Assert.Equal ("object", val ["type"]?.Value<string> ());
Assert.True (val ["isEnum"] != null && val ["isEnum"].Value<bool> ());
Assert.Equal (class_name, val ["className"]?.Value<string> ());
Assert.Equal (descr, val ["description"]?.Value<string> ());
return l;
}
internal void CheckArray (JToken locals, string name, string class_name) {
foreach (var l in locals) {
if (name != l["name"]?.Value<string> ())
continue;
var val = l["value"];
Assert.Equal ("object", val ["type"]?.Value<string> ());
Assert.Equal ("array", val ["subtype"]?.Value<string> ());
Assert.Equal (class_name, val ["className"]?.Value<string> ());
//FIXME: elements?
return;
}
Assert.True(false, $"Could not find variable '{name}'");
}
internal JToken GetAndAssertObjectWithName (JToken obj, string name)
{
var l = obj.FirstOrDefault (jt => jt ["name"]?.Value<string> () == name);
if (l == null)
Assert.True (false, $"Could not find variable '{name}'");
return l;
}
internal async Task<Result> SendCommand (string method, JObject args) {
var res = await ctx.cli.SendCommand (method, args, ctx.token);
if (!res.IsOk) {
Console.WriteLine ($"Failed to run command {method} with args: {args?.ToString ()}\nresult: {res.Error.ToString ()}");
Assert.True (false, $"SendCommand for {method} failed with {res.Error.ToString ()}");
}
return res;
}
internal async Task<Result> Evaluate (string expression) {
return await SendCommand ("Runtime.evaluate", JObject.FromObject (new { expression = expression }));
}
internal void AssertLocation (JObject args, string methodName) {
Assert.Equal (methodName, args ["callFrames"]?[0]?["functionName"]?.Value<string> ());
}
// Place a breakpoint in the given method and run until its hit
// Return the Debugger.paused data
internal async Task<JObject> RunUntil (string methodName) {
await SetBreakpointInMethod ("debugger-test", "DebuggerTest", methodName);
// This will run all the tests until it hits the bp
await Evaluate ("window.setTimeout(function() { invoke_run_all (); }, 1);");
var wait_res = await ctx.insp.WaitFor (Inspector.PAUSE);
AssertLocation (wait_res, "locals_inner");
return wait_res;
}
internal async Task<JObject> StepAndCheck (StepKind kind, string script_loc, int line, int column, string function_name,
Func<JObject, Task> wait_for_event_fn = null, Action<JToken> locals_fn = null, int times=1)
{
for (int i = 0; i < times - 1; i ++) {
await SendCommandAndCheck (null, $"Debugger.step{kind.ToString ()}", null, -1, -1, null);
}
// Check for method/line etc only at the last step
return await SendCommandAndCheck (
null, $"Debugger.step{kind.ToString ()}", script_loc, line, column, function_name,
wait_for_event_fn: wait_for_event_fn,
locals_fn: locals_fn);
}
internal async Task<JObject> EvaluateAndCheck (string expression, string script_loc, int line, int column, string function_name,
Func<JObject, Task> wait_for_event_fn = null, Action<JToken> locals_fn = null)
=> await SendCommandAndCheck (
JObject.FromObject (new { expression = expression }),
"Runtime.evaluate", script_loc, line, column, function_name,
wait_for_event_fn: wait_for_event_fn,
locals_fn: locals_fn);
internal async Task<JObject> SendCommandAndCheck (JObject args, string method, string script_loc, int line, int column, string function_name,
Func<JObject, Task> wait_for_event_fn = null, Action<JToken> locals_fn = null, string waitForEvent = Inspector.PAUSE)
{
var res = await ctx.cli.SendCommand (method, args, ctx.token);
if (!res.IsOk) {
Console.WriteLine ($"Failed to run command {method} with args: {args?.ToString ()}\nresult: {res.Error.ToString ()}");
Assert.True (false, $"SendCommand for {method} failed with {res.Error.ToString ()}");
}
var wait_res = await ctx.insp.WaitFor(waitForEvent);
if (function_name != null)
Assert.Equal (function_name, wait_res ["callFrames"]?[0]?["functionName"]?.Value<string> ());
if (script_loc != null)
CheckLocation (script_loc, line, column, ctx.scripts, wait_res ["callFrames"][0]["location"]);
if (wait_for_event_fn != null)
await wait_for_event_fn (wait_res);
if (locals_fn != null) {
var locals = await GetProperties (wait_res ["callFrames"][0]["callFrameId"].Value<string> ());
locals_fn (locals);
}
return wait_res;
}
internal async Task CheckDelegate (JToken locals, string name, string className, string target)
{
var l = GetAndAssertObjectWithName (locals, name);
var val = l["value"];
await CheckDelegate (l, TDelegate (className, target), name);
}
internal async Task CheckDelegate (JToken actual_val, JToken exp_val, string label)
{
AssertEqual ("object", actual_val["type"]?.Value<string>(), $"{label}-type");
AssertEqual (exp_val ["className"]?.Value<string> (), actual_val ["className"]?.Value<string>(), $"{label}-className");
var actual_target = actual_val["description"]?.Value<string>();
Assert.True(actual_target != null, $"${label}-description");
var exp_target = exp_val["target"].Value<string>();
CheckDelegateTarget (actual_target, exp_target);
var del_props = await GetProperties(actual_val["objectId"]?.Value<string>());
AssertEqual (1, del_props.Count(), $"${label}-delegate-properties-count");
var obj = del_props.Where (jt => jt ["name"]?.Value<string> () == "Target").FirstOrDefault ();
Assert.True (obj != null, $"[{label}] Property named 'Target' found found in delegate properties");
AssertEqual("symbol", obj ["value"]?["type"]?.Value<string>(), $"{label}#Target#type");
CheckDelegateTarget(obj ["value"]?["value"]?.Value<string>(), exp_target);
return;
void CheckDelegateTarget(string actual_target, string exp_target)
{
var parts = exp_target.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 1) {
// not a generated method
AssertEqual(exp_target, actual_target, $"{label}-description");
} else {
bool prefix = actual_target.StartsWith(parts[0], StringComparison.Ordinal);
Assert.True(prefix, $"{label}-description, Expected target to start with '{parts[0]}'. Actual: '{actual_target}'");
var remaining = actual_target.Substring(parts[0].Length);
bool suffix = remaining.EndsWith(parts[1], StringComparison.Ordinal);
Assert.True(prefix, $"{label}-description, Expected target to end with '{parts[1]}'. Actual: '{remaining}'");
}
}
}
internal async Task CheckCustomType (JToken actual_val, JToken exp_val, string label)
{
var ctype = exp_val["__custom_type"].Value<string>();
switch (ctype) {
case "delegate":
await CheckDelegate (actual_val, exp_val, label);
break;
case "pointer": {
AssertEqual ("symbol", actual_val ["type"]?.Value<string>(), $"{label}-type");
if (exp_val ["is_null"]?.Value<bool>() == false) {
var exp_prefix = $"({exp_val ["type_name"]?.Value<string>()})";
AssertStartsWith (exp_prefix, actual_val ["value"]?.Value<string> (), $"{label}-type_name");
AssertStartsWith (exp_prefix, actual_val ["description"]?.Value<string> (), $"{label}-description");
} else {
var exp_prefix = $"({exp_val ["type_name"]?.Value<string>()}) 0";
AssertEqual (exp_prefix, actual_val ["value"]?.Value<string> (), $"{label}-type_name");
AssertEqual (exp_prefix, actual_val ["description"]?.Value<string> (), $"{label}-description");
}
break;
}
case "ignore_me":
// nothing to check ;)
break;
default:
throw new ArgumentException($"{ctype} not supported");
}
}
internal async Task CheckProps (JToken actual, object exp_o, string label, int num_fields=-1)
{
if (exp_o.GetType ().IsArray || exp_o is JArray) {
if (! (actual is JArray actual_arr)) {
Assert.True (false, $"[{label}] Expected to get an array here but got {actual}");
return;
}
var exp_v_arr = JArray.FromObject (exp_o);
AssertEqual (exp_v_arr.Count, actual_arr.Count (), $"{label}-count");
for (int i = 0; i < exp_v_arr.Count; i ++) {
var exp_i = exp_v_arr [i];
var act_i = actual_arr [i];
AssertEqual (i.ToString (), act_i ["name"]?.Value<string> (), $"{label}-[{i}].name");
await CheckValue (act_i["value"], exp_i, $"{label}-{i}th value");
}
return;
}
// Not an array
var exp = exp_o as JObject;
if (exp == null)
exp = JObject.FromObject(exp_o);
num_fields = num_fields < 0 ? exp.Values<JToken>().Count() : num_fields;
Assert.True(num_fields == actual.Count(), $"[{label}] Number of fields don't match, Expected: {num_fields}, Actual: {actual.Count()}");
foreach (var kvp in exp) {
var exp_name = kvp.Key;
var exp_val = kvp.Value;
var actual_obj = actual.FirstOrDefault(jt => jt["name"]?.Value<string>() == exp_name);
if (actual_obj == null) {
Console.WriteLine($"actual: {actual}, exp_name: {exp_name}, exp_val: {exp_val}");
Assert.True(actual_obj != null, $"[{label}] Could not find property named '{exp_name}'");
}
var actual_val = actual_obj["value"];
Assert.True(actual_obj != null, $"[{label}] not value found for property named '{exp_name}'");
if (exp_val.Type == JTokenType.Array) {
var actual_props = await GetProperties(actual_val["objectId"]?.Value<string>());
await CheckProps (actual_props, exp_val, $"{label}-{exp_name}");
} else {
await CheckValue (actual_val, exp_val, $"{label}#{exp_name}");
}
}
}
internal async Task CheckValue (JToken actual_val, JToken exp_val, string label)
{
if (exp_val ["__custom_type"] != null) {
await CheckCustomType (actual_val, exp_val, label);
return;
}
if (exp_val ["type"] == null && actual_val ["objectId"] != null) {
var new_val = await GetProperties (actual_val ["objectId"].Value<string> ());
await CheckProps (new_val, exp_val, $"{label}-{actual_val["objectId"]?.Value<string>()}");
return;
}
foreach (var jp in exp_val.Values<JProperty> ()) {
if (jp.Value.Type == JTokenType.Object) {
var new_val = await GetProperties (actual_val ["objectId"].Value<string> ());
await CheckProps (new_val, jp.Value, $"{label}-{actual_val["objectId"]?.Value<string>()}");
continue;
}
var exp_val_str = jp.Value.Value<string> ();
bool null_or_empty_exp_val = String.IsNullOrEmpty (exp_val_str);
var actual_field_val = actual_val.Values<JProperty> ().FirstOrDefault (a_jp => a_jp.Name == jp.Name);
var actual_field_val_str = actual_field_val?.Value?.Value<string> ();
if (null_or_empty_exp_val && String.IsNullOrEmpty (actual_field_val_str))
continue;
Assert.True (actual_field_val != null, $"[{label}] Could not find value field named {jp.Name}");
Assert.True (exp_val_str == actual_field_val_str,
$"[{label}] Value for json property named {jp.Name} didn't match.\n" +
$"Expected: {jp.Value.Value<string> ()}\n" +
$"Actual: {actual_field_val.Value.Value<string> ()}");
}
}
internal async Task<JToken> GetLocalsForFrame (JToken frame, string script_loc, int line, int column, string function_name)
{
CheckLocation (script_loc, line, column, ctx.scripts, frame ["location"]);
Assert.Equal (function_name, frame ["functionName"].Value<string> ());
return await GetProperties (frame ["callFrameId"].Value<string> ());
}
internal async Task<JToken> GetObjectOnFrame (JToken frame, string name)
{
var locals = await GetProperties (frame ["callFrameId"].Value<string> ());
return await GetObjectOnLocals (locals, name);
}
// Find an object with @name, *fetch* the object, and check against @o
internal async Task<JToken> CompareObjectPropertiesFor (JToken locals, string name, object o, string label = null, int num_fields = -1)
{
if (label == null)
label = name;
var props = await GetObjectOnLocals (locals, name);
try {
if (o != null)
await CheckProps (props, o, label, num_fields);
return props;
} catch {
throw;
}
}
internal async Task<JToken> GetObjectOnLocals (JToken locals, string name)
{
var obj = GetAndAssertObjectWithName (locals, name);
var objectId = obj ["value"]["objectId"]?.Value<string> ();
Assert.True (!String.IsNullOrEmpty (objectId), $"No objectId found for {name}");
return await GetProperties (objectId);
}
/* @fn_args is for use with `Runtime.callFunctionOn` only */
internal async Task<JToken> GetProperties (string id, JToken fn_args = null)
{
if (ctx.UseCallFunctionOnBeforeGetProperties && !id.StartsWith ("dotnet:scope:")) {
var fn_decl = "function () { return this; }";
var cfo_args = JObject.FromObject (new {
functionDeclaration = fn_decl,
objectId = id
});
if (fn_args != null)
cfo_args ["arguments"] = fn_args;
var result = await ctx.cli.SendCommand ("Runtime.callFunctionOn", cfo_args, ctx.token);
AssertEqual (true, result.IsOk, $"Runtime.getProperties failed for {cfo_args.ToString ()}, with Result: {result}");
id = result.Value ["result"]?["objectId"]?.Value<string> ();
}
var get_prop_req = JObject.FromObject (new {
objectId = id
});
var frame_props = await ctx.cli.SendCommand ("Runtime.getProperties", get_prop_req, ctx.token);
if (!frame_props.IsOk)
Assert.True (false, $"Runtime.getProperties failed for {get_prop_req.ToString ()}, with Result: {frame_props}");
var locals = frame_props.Value ["result"];
// FIXME: Should be done when generating the list in library_mono.js, but not sure yet
// whether to remove it, and how to do it correctly.
if (locals is JArray) {
foreach (var p in locals) {
if (p ["name"]?.Value<string> () == "length" && p ["enumerable"]?.Value<bool> () != true) {
p.Remove ();
break;
}
}
}
return locals;
}
internal async Task<JToken> EvaluateOnCallFrame (string id, string expression)
{
var evaluate_req = JObject.FromObject (new {
callFrameId = id,
expression = expression
});
var frame_evaluate = await ctx.cli.SendCommand ("Debugger.evaluateOnCallFrame", evaluate_req, ctx.token);
if (!frame_evaluate.IsOk)
Assert.True (false, $"Debugger.evaluateOnCallFrame failed for {evaluate_req.ToString ()}, with Result: {frame_evaluate}");
var evaluate_result = frame_evaluate.Value ["result"];
return evaluate_result;
}
internal async Task<Result> SetBreakpoint (string url_key, int line, int column, bool expect_ok=true, bool use_regex = false)
{
var bp1_req = !use_regex ?
JObject.FromObject(new { lineNumber = line, columnNumber = column, url = dicFileToUrl[url_key],}) :
JObject.FromObject(new { lineNumber = line, columnNumber = column, urlRegex = url_key, });
var bp1_res = await ctx.cli.SendCommand ("Debugger.setBreakpointByUrl", bp1_req, ctx.token);
Assert.True (expect_ok ? bp1_res.IsOk : bp1_res.IsErr);
return bp1_res;
}
internal async Task<Result> SetBreakpointInMethod (string assembly, string type, string method) {
var req = JObject.FromObject (new { assemblyName = assembly, typeName = type, methodName = method });
// Protocol extension
var res = await ctx.cli.SendCommand ("Dotnet-test.setBreakpointByMethod", req, ctx.token);
Assert.True (res.IsOk);
return res;
}
internal void AssertEqual (object expected, object actual, string label)
=> Assert.True (expected?.Equals (actual),
$"[{label}]\n" +
$"Expected: {expected?.ToString()}\n" +
$"Actual: {actual?.ToString()}\n");
internal void AssertStartsWith (string expected, string actual, string label)
=> Assert.True(actual?.StartsWith (expected), $"[{label}] Does not start with the expected string\nExpected: {expected}\nActual: {actual}");
internal static Func<int, int, string, string, object> TSimpleClass = (X, Y, Id, Color) => new {
X = TNumber (X),
Y = TNumber (Y),
Id = TString (Id),
Color = TEnum ("DebuggerTests.RGB", Color),
//PointWithCustomGetter = TValueType ("DebuggerTests.Point")
// only automatic properties are supported currently!
PointWithCustomGetter = TSymbol ("DebuggerTests.Point { get; }")
};
internal static Func<int, int, string, string, object> TPoint = (X, Y, Id, Color) => new {
X = TNumber (X),
Y = TNumber (Y),
Id = TString (Id),
Color = TEnum ("DebuggerTests.RGB", Color),
};
//FIXME: um maybe we don't need to convert jobject right here!
internal static JObject TString (string value) =>
value == null
? TObject ("string", is_null: true)
: JObject.FromObject (new { type = "string", value = @value, description = @value });
internal static JObject TNumber (int value) =>
JObject.FromObject (new { type = "number", value = @value.ToString (), description = value.ToString () });
internal static JObject TValueType (string className, string description = null, object members = null) =>
JObject.FromObject (new { type = "object", isValueType = true, className = className, description = description ?? className });
internal static JObject TEnum (string className, string descr, object members = null) =>
JObject.FromObject (new { type = "object", isEnum = true, className = className, description = descr });
internal static JObject TObject (string className, string description = null, bool is_null = false) =>
is_null
? JObject.FromObject (new { type = "object", className = className, description = description ?? className, subtype = is_null ? "null" : null })
: JObject.FromObject (new { type = "object", className = className, description = description ?? className });
internal static JObject TArray (string className, int length = 0)
=> JObject.FromObject (new { type = "object", className = className, description = $"{className}({length})", subtype = "array" });
internal static JObject TBool (bool value)
=> JObject.FromObject (new { type = "boolean", value = @value, description = @value ? "true" : "false" });
internal static JObject TSymbol (string value)
=> JObject.FromObject (new { type = "symbol", value = @value, description = @value });
/*
For target names with generated method names like
`void <ActionTSignatureTest>b__11_0 (Math.GenericStruct<int[]>)`
.. pass target "as `target: "void <ActionTSignatureTest>|(Math.GenericStruct<int[]>)"`
*/
internal static JObject TDelegate(string className, string target)
=> JObject.FromObject(new {
__custom_type = "delegate",
className = className,
target = target
});
internal static JObject TPointer (string type_name, bool is_null = false)
=> JObject.FromObject (new { __custom_type = "pointer", type_name = type_name, is_null = is_null });
internal static JObject TIgnore ()
=> JObject.FromObject (new { __custom_type = "ignore_me" });
}
class DebugTestContext
{
public InspectorClient cli;
public Inspector insp;
public CancellationToken token;
public Dictionary<string, string> scripts;
public bool UseCallFunctionOnBeforeGetProperties;
public DebugTestContext (InspectorClient cli, Inspector insp, CancellationToken token, Dictionary<string, string> scripts)
{
this.cli = cli;
this.insp = insp;
this.token = token;
this.scripts = scripts;
}
}
enum StepKind
{
Into,
Over,
Out
}
}
File diff suppressed because it is too large. Load diff
+13 -13
View File
@@ -68,7 +68,7 @@ MINI_TEST_SOURCES = $(patsubst %,$(MINI_PATH)/%,$(MINI_TEST_FILES))
WASM_FRAMEWORK=$(TOP)/sdks/wasm/framework
WASM_FRAMEWORK_SOURCE=$(TOP)/sdks/wasm/framework/src
WASM_FRAMEWORK_SOURCES=$(WASM_FRAMEWORK_SOURCE)/**/*
WASM_FRAMEWORK_DEPS=/r:$(WASM_FRAMEWORK)/WebAssembly.Bindings.dll /r:$(WASM_FRAMEWORK)/WebAssembly.Net.Http.dll /r:$(WASM_FRAMEWORK)/WebAssembly.Net.WebSockets.dll
WASM_FRAMEWORK_DEPS=/r:$(WASM_FRAMEWORK)/WebAssembly.Bindings.dll /r:$(WASM_FRAMEWORK)/System.Net.Http.WebAssemblyHttpHandler.dll /r:$(WASM_FRAMEWORK)/WebAssembly.Net.WebSockets.dll
BROWSER_TEST=$(TOP)/sdks/wasm/tests/browser
BROWSER_TEST_THREADS=$(TOP)/sdks/wasm/tests/browser
@@ -374,11 +374,11 @@ $(WASM_FRAMEWORK)/.stamp-framework: $(WASM_FRAMEWORK_SOURCES)
Simple.Dependency.dll: dependency.cs $(WASM_FRAMEWORK)/.stamp-framework
$(CSC) $(CSC_FLAGS) /target:library -out:$@ $(BCL_DEPS) dependency.cs
sample.dll: Simple.Dependency.dll sample.cs $(WASM_FRAMEWORK)/.stamp-framework debugger-valuetypes-test.cs
$(CSC) $(CSC_FLAGS) /target:library -out:$@ /r:Simple.Dependency.dll $(BCL_DEPS) $(WASM_FRAMEWORK_DEPS) sample.cs debugger-valuetypes-test.cs
sample.dll: Simple.Dependency.dll sample.cs $(WASM_FRAMEWORK)/.stamp-framework tests/debugger/*.cs
$(CSC) $(CSC_FLAGS) /target:library -out:$@ /r:Simple.Dependency.dll /unsafe $(BCL_DEPS) $(WASM_FRAMEWORK_DEPS) sample.cs tests/debugger/*.cs
debugger-test.dll: debugger-test.cs debugger-test2.cs debugger-valuetypes-test.cs Simple.Dependency.dll debugger-array-test.cs
$(CSC) $(CSC_FLAGS) /target:library -out:$@ /r:$(WASM_BCL_DIR)/mscorlib.dll /r:Simple.Dependency.dll debugger-test.cs debugger-test2.cs debugger-valuetypes-test.cs debugger-array-test.cs
debugger-test.dll: tests/debugger/*.cs Simple.Dependency.dll
$(CSC) $(CSC_FLAGS) /target:library -out:$@ /r:$(WASM_BCL_DIR)/mscorlib.dll /r:Simple.Dependency.dll /unsafe tests/debugger/*.cs
OPTIONS_CS = $(TOP)/mcs/class/Mono.Options/Mono.Options/Options.cs
@@ -461,8 +461,8 @@ $(BROWSER_TEST_DYNAMIC)/.stamp-browser-test-dynamic-suite: packager.exe $(WASM_F
(cd $(BROWSER_TEST) && $(NPM) install)
touch $@
.stamp-build-debugger-test-app: packager.exe binding_tests.dll debugger-test.dll debugger-driver.html
$(PACKAGER) --copy=always -debugrt -debug --template=runtime.js --builddir=obj/debugger-test-suite --appdir=bin/debugger-test-suite --asset=debugger-driver.html debugger-test.dll
bin/debugger-test-suite/dotnet.wasm: packager.exe binding_tests.dll debugger-test.dll tests/debugger/debugger-driver.html other.js builds/debug/dotnet.js
$(PACKAGER) --copy=always -debugrt -debug --template=runtime.js --builddir=obj/debugger-test-suite --appdir=bin/debugger-test-suite --asset=tests/debugger/debugger-driver.html --asset=other.js debugger-test.dll
ninja -v -C obj/debugger-test-suite
touch $@
@@ -665,7 +665,7 @@ run-aot-all: build-aot-all
rebuild-debug-sample: clean-debug-sample build-debug-sample
build-debugger-test-app: .stamp-build-debugger-test-app
build-debugger-test-app: bin/debugger-test-suite/dotnet.wasm
build-managed: build-debug-sample build-test-suite
build-dbg-proxy:
@@ -705,9 +705,9 @@ run-all-%:
run-debugger-tests: build-debugger-test-app build-dbg-testsuite
if [ ! -z "$(TEST_FILTER)" ]; then \
dotnet test DebuggerTestSuite --filter FullyQualifiedName~$(TEST_FILTER); \
LC_ALL=en_US.UTF-8 dotnet test DebuggerTestSuite --filter FullyQualifiedName~$(TEST_FILTER); \
else \
dotnet test DebuggerTestSuite $(TEST_ARGS); \
LC_ALL=en_US.UTF-8 dotnet test DebuggerTestSuite $(TEST_ARGS); \
fi
run-browser-tests: build-browser-test-suite
@@ -766,9 +766,9 @@ package: build build-sdk build-dbg-proxy
cp framework/WebAssembly.Bindings.dll tmp/framework
cp framework/WebAssembly.Bindings.pdb tmp/framework
cp framework/WebAssembly.Bindings.xml tmp/framework
cp framework/WebAssembly.Net.Http.dll tmp/framework
cp framework/WebAssembly.Net.Http.pdb tmp/framework
cp framework/WebAssembly.Net.Http.xml tmp/framework
cp framework/System.Net.Http.WebAssemblyHttpHandler.dll tmp/framework
cp framework/System.Net.Http.WebAssemblyHttpHandler.pdb tmp/framework
cp framework/System.Net.Http.WebAssemblyHttpHandler.xml tmp/framework
cp framework/WebAssembly.Net.WebSockets.dll tmp/framework
cp framework/WebAssembly.Net.WebSockets.pdb tmp/framework
cp framework/WebAssembly.Net.WebSockets.xml tmp/framework
@@ -13,6 +13,7 @@ using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.Logging;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
namespace WebAssembly.Net.Debugging {
internal class BreakpointRequest {
@@ -21,26 +22,35 @@ namespace WebAssembly.Net.Debugging {
public string File { get; private set; }
public int Line { get; private set; }
public int Column { get; private set; }
public MethodInfo Method { get; private set; }
JObject request;
public bool IsResolved => Assembly != null;
public List<Breakpoint> Locations { get; } = new List<Breakpoint> ();
public override string ToString () {
return $"BreakpointRequest Assembly: {Assembly} File: {File} Line: {Line} Column: {Column}";
public override string ToString ()
=> $"BreakpointRequest Assembly: {Assembly} File: {File} Line: {Line} Column: {Column}";
public object AsSetBreakpointByUrlResponse (IEnumerable<object> jsloc)
=> new { breakpointId = Id, locations = Locations.Select(l => l.Location.AsLocation ()).Concat (jsloc) };
public BreakpointRequest () {
}
public object AsSetBreakpointByUrlResponse ()
=> new { breakpointId = Id, locations = Locations.Select(l => l.Location.AsLocation ()) };
public BreakpointRequest (string id, MethodInfo method) {
Id = id;
Method = method;
}
public BreakpointRequest (string id, JObject request) {
Id = id;
this.request = request;
}
public static BreakpointRequest Parse (string id, JObject args)
{
var breakRequest = new BreakpointRequest () {
Id = id,
request = args
};
return breakRequest;
return new BreakpointRequest (id, args);
}
public BreakpointRequest Clone ()
@@ -83,18 +93,6 @@ namespace WebAssembly.Net.Debugging {
return store.AllSources().FirstOrDefault (source => TryResolve (source)) != null;
}
static (string Assembly, string DocumentPath) ParseDocumentUrl (string url)
{
if (Uri.TryCreate (url, UriKind.Absolute, out var docUri) && docUri.Scheme == "dotnet") {
return (
docUri.Host,
docUri.PathAndQuery.Substring (1)
);
} else {
return (null, null);
}
}
}
internal class VarInfo {
@@ -110,13 +108,11 @@ namespace WebAssembly.Net.Debugging {
this.Index = (p.Index + 1) * -1;
}
public string Name { get; private set; }
public int Index { get; private set; }
public string Name { get; }
public int Index { get; }
public override string ToString ()
{
return $"(var-info [{Index}] '{Name}')";
}
=> $"(var-info [{Index}] '{Name}')";
}
internal class CliLocation {
@@ -126,8 +122,8 @@ namespace WebAssembly.Net.Debugging {
Offset = offset;
}
public MethodInfo Method { get; private set; }
public int Offset { get; private set; }
public MethodInfo Method { get; }
public int Offset { get; }
}
internal class SourceLocation {
@@ -157,9 +153,7 @@ namespace WebAssembly.Net.Debugging {
public CliLocation CliLocation => this.cliLoc;
public override string ToString ()
{
return $"{id}:{Line}:{Column}";
}
=> $"{id}:{Line}:{Column}";
public static SourceLocation Parse (JObject obj)
{
@@ -177,6 +171,28 @@ namespace WebAssembly.Net.Debugging {
return new SourceLocation (id, line.Value, column.Value);
}
internal class LocationComparer : EqualityComparer<SourceLocation>
{
public override bool Equals (SourceLocation l1, SourceLocation l2)
{
if (l1 == null && l2 == null)
return true;
else if (l1 == null || l2 == null)
return false;
return (l1.Line == l2.Line &&
l1.Column == l2.Column &&
l1.Id == l2.Id);
}
public override int GetHashCode (SourceLocation loc)
{
int hCode = loc.Line ^ loc.Column;
return loc.Id.GetHashCode () ^ hCode.GetHashCode ();
}
}
internal object AsLocation ()
=> new {
scriptId = id.ToString (),
@@ -235,9 +251,7 @@ namespace WebAssembly.Net.Debugging {
}
public override string ToString ()
{
return $"{Scheme}{assembly}_{document}";
}
=> $"{Scheme}{assembly}_{document}";
public override bool Equals (object obj)
{
@@ -248,44 +262,36 @@ namespace WebAssembly.Net.Debugging {
}
public override int GetHashCode ()
{
return this.assembly.GetHashCode () ^ this.document.GetHashCode ();
}
=> assembly.GetHashCode () ^ document.GetHashCode ();
public static bool operator == (SourceId a, SourceId b)
{
if ((object)a == null)
return (object)b == null;
return a.Equals (b);
}
=> ((object)a == null) ? (object)b == null : a.Equals (b);
public static bool operator != (SourceId a, SourceId b)
{
return !a.Equals (b);
}
=> !a.Equals (b);
}
internal class MethodInfo {
AssemblyInfo assembly;
internal MethodDefinition methodDef;
MethodDefinition methodDef;
SourceFile source;
public SourceId SourceId => source.SourceId;
public string Name => methodDef.Name;
public MethodDebugInformation DebugInformation => methodDef.DebugInformation;
public SourceLocation StartLocation { get; private set; }
public SourceLocation EndLocation { get; private set; }
public AssemblyInfo Assembly => assembly;
public int Token => (int)methodDef.MetadataToken.RID;
public SourceLocation StartLocation { get; }
public SourceLocation EndLocation { get; }
public AssemblyInfo Assembly { get; }
public uint Token => methodDef.MetadataToken.RID;
public MethodInfo (AssemblyInfo assembly, MethodDefinition methodDef, SourceFile source)
{
this.assembly = assembly;
this.Assembly = assembly;
this.methodDef = methodDef;
this.source = source;
var sps = methodDef.DebugInformation.SequencePoints;
var sps = DebugInformation.SequencePoints;
if (sps == null || sps.Count() < 1)
return;
@@ -311,7 +317,7 @@ namespace WebAssembly.Net.Debugging {
public SourceLocation GetLocationByIl (int pos)
{
SequencePoint prev = null;
foreach (var sp in methodDef.DebugInformation.SequencePoints) {
foreach (var sp in DebugInformation.SequencePoints) {
if (sp.Offset > pos)
break;
prev = sp;
@@ -328,7 +334,6 @@ namespace WebAssembly.Net.Debugging {
var res = new List<VarInfo> ();
res.AddRange (methodDef.Parameters.Select (p => new VarInfo (p)));
res.AddRange (methodDef.DebugInformation.GetScopes ()
.Where (s => s.Start.Offset <= offset && (s.End.IsEndOfMethod || s.End.Offset > offset))
.SelectMany (s => s.Variables)
@@ -337,17 +342,38 @@ namespace WebAssembly.Net.Debugging {
return res.ToArray ();
}
public override string ToString () => "MethodInfo(" + methodDef.FullName + ")";
}
internal class AssemblyInfo {
internal class TypeInfo {
AssemblyInfo assembly;
TypeDefinition type;
List<MethodInfo> methods;
public TypeInfo (AssemblyInfo assembly, TypeDefinition type) {
this.assembly = assembly;
this.type = type;
methods = new List<MethodInfo> ();
}
public string Name => type.Name;
public string FullName => type.FullName;
public List<MethodInfo> Methods => methods;
public override string ToString () => "TypeInfo('" + FullName + "')";
}
class AssemblyInfo {
static int next_id;
ModuleDefinition image;
readonly int id;
readonly ILogger logger;
Dictionary<int, MethodInfo> methods = new Dictionary<int, MethodInfo> ();
Dictionary<uint, MethodInfo> methods = new Dictionary<uint, MethodInfo> ();
Dictionary<string, string> sourceLinkMappings = new Dictionary<string, string>();
Dictionary<string, TypeInfo> typesByName = new Dictionary<string, TypeInfo> ();
readonly List<SourceFile> sources = new List<SourceFile>();
internal string Url { get; private set; }
internal string Url { get; }
public AssemblyInfo (string url, byte[] assembly, byte[] pdb)
{
@@ -356,18 +382,23 @@ namespace WebAssembly.Net.Debugging {
try {
Url = url;
ReaderParameters rp = new ReaderParameters (/*ReadingMode.Immediate*/);
// set ReadSymbols = true unconditionally in case there
// is an embedded pdb then handle ArgumentException
// and assume that if pdb == null that is the cause
rp.ReadSymbols = true;
rp.SymbolReaderProvider = new PdbReaderProvider ();
if (pdb != null)
rp.SymbolStream = new MemoryStream (pdb);
rp.ReadingMode = ReadingMode.Immediate;
rp.InMemory = true;
this.image = ModuleDefinition.ReadModule (new MemoryStream (assembly), rp);
} catch (BadImageFormatException ex) {
logger.LogWarning ($"Failed to read assembly as portable PDB: {ex.Message}");
} catch (ArgumentNullException) {
} catch (ArgumentException) {
// if pdb == null this is expected and we
// read the assembly without symbols below
if (pdb != null)
throw;
}
@@ -396,45 +427,38 @@ namespace WebAssembly.Net.Debugging {
void Populate ()
{
ProcessSourceLink();
ProcessSourceLink();
var d2s = new Dictionary<Document, SourceFile> ();
Func<Document, SourceFile> get_src = (doc) => {
SourceFile FindSource (Document doc)
{
if (doc == null)
return null;
if (d2s.ContainsKey (doc))
return d2s [doc];
if (d2s.TryGetValue (doc, out var source))
return source;
var src = new SourceFile (this, sources.Count, doc, GetSourceLinkUrl (doc.Url));
sources.Add (src);
d2s [doc] = src;
return src;
};
foreach (var m in image.GetTypes().SelectMany(t => t.Methods)) {
Document first_doc = null;
foreach (var sp in m.DebugInformation.SequencePoints) {
if (first_doc == null && !sp.Document.Url.EndsWith (".g.cs", StringComparison.OrdinalIgnoreCase)) {
first_doc = sp.Document;
foreach (var type in image.GetTypes()) {
var typeInfo = new TypeInfo (this, type);
typesByName [type.FullName] = typeInfo;
foreach (var method in type.Methods) {
foreach (var sp in method.DebugInformation.SequencePoints) {
var source = FindSource (sp.Document);
var methodInfo = new MethodInfo (this, method, source);
methods [method.MetadataToken.RID] = methodInfo;
if (source != null)
source.AddMethod (methodInfo);
typeInfo.Methods.Add (methodInfo);
}
// else if (first_doc != sp.Document) {
// //FIXME this is needed for (c)ctors in corlib
// throw new Exception ($"Cant handle multi-doc methods in {m}");
//}
}
if (first_doc == null) {
// all generated files
first_doc = m.DebugInformation.SequencePoints.FirstOrDefault ()?.Document;
}
if (first_doc != null) {
var src = get_src (first_doc);
var mi = new MethodInfo (this, m, src);
int mt = (int)m.MetadataToken.RID;
this.methods [mt] = mi;
if (src != null)
src.AddMethod (mi);
}
}
}
@@ -455,9 +479,8 @@ namespace WebAssembly.Net.Debugging {
private Uri GetSourceLinkUrl (string document)
{
if (sourceLinkMappings.TryGetValue (document, out string url)) {
if (sourceLinkMappings.TryGetValue (document, out string url))
return new Uri (url);
}
foreach (var sourceLinkDocument in sourceLinkMappings) {
string key = sourceLinkDocument.Key;
@@ -477,7 +500,7 @@ namespace WebAssembly.Net.Debugging {
return null;
}
private string GetRelativePath (string relativeTo, string path)
private static string GetRelativePath (string relativeTo, string path)
{
var uri = new Uri (relativeTo, UriKind.RelativeOrAbsolute);
var rel = Uri.UnescapeDataString (uri.MakeRelativeUri (new Uri (path, UriKind.RelativeOrAbsolute)).ToString ()).Replace (Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
@@ -487,9 +510,8 @@ namespace WebAssembly.Net.Debugging {
return rel;
}
public IEnumerable<SourceFile> Sources {
get { return this.sources; }
}
public IEnumerable<SourceFile> Sources
=> this.sources;
public int Id => id;
public string Name => image.Name;
@@ -499,22 +521,27 @@ namespace WebAssembly.Net.Debugging {
return sources.FirstOrDefault (s => s.SourceId.Document == document);
}
public MethodInfo GetMethodByToken (int token)
public MethodInfo GetMethodByToken (uint token)
{
methods.TryGetValue (token, out var value);
return value;
}
public TypeInfo GetTypeByName (string name) {
typesByName.TryGetValue (name, out var res);
return res;
}
}
internal class SourceFile {
HashSet<MethodInfo> methods;
Dictionary<uint, MethodInfo> methods;
AssemblyInfo assembly;
int id;
Document doc;
internal SourceFile (AssemblyInfo assembly, int id, Document doc, Uri sourceLinkUri)
{
this.methods = new HashSet<MethodInfo> ();
this.methods = new Dictionary<uint, MethodInfo> ();
this.SourceLinkUri = sourceLinkUri;
this.assembly = assembly;
this.id = id;
@@ -531,7 +558,8 @@ namespace WebAssembly.Net.Debugging {
internal void AddMethod (MethodInfo mi)
{
this.methods.Add (mi);
if (!this.methods.ContainsKey (mi.Token))
this.methods [mi.Token] = mi;
}
public string DebuggerFileName { get; }
@@ -543,25 +571,93 @@ namespace WebAssembly.Net.Debugging {
public Uri SourceLinkUri { get; }
public Uri SourceUri { get; }
public IEnumerable<MethodInfo> Methods => this.methods;
public byte[] EmbeddedSource => doc.EmbeddedSource;
public IEnumerable<MethodInfo> Methods => this.methods.Values;
public string DocUrl => doc.Url;
public (int startLine, int startColumn, int endLine, int endColumn) GetExtents ()
{
var start = methods.OrderBy (m => m.StartLocation.Line).ThenBy (m => m.StartLocation.Column).First ();
var end = methods.OrderByDescending (m => m.EndLocation.Line).ThenByDescending (m => m.EndLocation.Column).First ();
var start = Methods.OrderBy (m => m.StartLocation.Line).ThenBy (m => m.StartLocation.Column).First ();
var end = Methods.OrderByDescending (m => m.EndLocation.Line).ThenByDescending (m => m.EndLocation.Column).First ();
return (start.StartLocation.Line, start.StartLocation.Column, end.EndLocation.Line, end.EndLocation.Column);
}
public async Task<byte[]> LoadSource ()
async Task<MemoryStream> GetDataAsync (Uri uri, CancellationToken token)
{
if (EmbeddedSource.Length > 0)
return await Task.FromResult (EmbeddedSource);
var mem = new MemoryStream ();
try {
if (uri.IsFile && File.Exists (uri.LocalPath)) {
using (var file = File.Open (SourceUri.LocalPath, FileMode.Open)) {
await file.CopyToAsync (mem, token);
mem.Position = 0;
}
} else if (uri.Scheme == "http" || uri.Scheme == "https") {
var client = new HttpClient ();
using (var stream = await client.GetStreamAsync (uri)) {
await stream.CopyToAsync (mem, token);
mem.Position = 0;
}
}
} catch (Exception) {
return null;
}
return mem;
}
static HashAlgorithm GetHashAlgorithm (DocumentHashAlgorithm algorithm)
{
switch (algorithm) {
case DocumentHashAlgorithm.SHA1: return SHA1.Create ();
case DocumentHashAlgorithm.SHA256: return SHA256.Create ();
case DocumentHashAlgorithm.MD5: return MD5.Create ();
}
return null;
}
bool CheckPdbHash (byte [] computedHash)
{
if (computedHash.Length != doc.Hash.Length)
return false;
for (var i = 0; i < computedHash.Length; i++)
if (computedHash[i] != doc.Hash[i])
return false;
return true;
}
byte[] ComputePdbHash (Stream sourceStream)
{
var algorithm = GetHashAlgorithm (doc.HashAlgorithm);
if (algorithm != null)
using (algorithm)
return algorithm.ComputeHash (sourceStream);
return Array.Empty<byte> ();
}
public async Task<Stream> GetSourceAsync (bool checkHash, CancellationToken token = default(CancellationToken))
{
if (doc.EmbeddedSource.Length > 0)
return new MemoryStream (doc.EmbeddedSource, false);
MemoryStream mem;
mem = await GetDataAsync (SourceUri, token);
if (mem != null && (!checkHash || CheckPdbHash (ComputePdbHash (mem)))) {
mem.Position = 0;
return mem;
}
mem = await GetDataAsync (SourceLinkUri, token);
if (mem != null && (!checkHash || CheckPdbHash (ComputePdbHash (mem)))) {
mem.Position = 0;
return mem;
}
return MemoryStream.Null;
}
public object ToScriptSource (int executionContextId, object executionContextAuxData)
{
return new {
@@ -569,7 +665,7 @@ namespace WebAssembly.Net.Debugging {
url = Url,
executionContextId,
executionContextAuxData,
//hash = "abcdee" + id,
//hash: should be the v8 hash algo, managed implementation is pending
dotNetUrl = DotNetUrl,
};
}
@@ -577,13 +673,18 @@ namespace WebAssembly.Net.Debugging {
internal class DebugStore {
List<AssemblyInfo> assemblies = new List<AssemblyInfo> ();
HttpClient client = new HttpClient ();
readonly HttpClient client;
readonly ILogger logger;
public DebugStore (ILogger logger) {
public DebugStore (ILogger logger, HttpClient client) {
this.client = client;
this.logger = logger;
}
public DebugStore (ILogger logger) : this (logger, new HttpClient ())
{
}
class DebugItem {
public string Url { get; set; }
public Task<byte[][]> Data { get; set; }
@@ -623,7 +724,7 @@ namespace WebAssembly.Net.Debugging {
var bytes = await step.Data;
assembly = new AssemblyInfo (step.Url, bytes [0], bytes [1]);
} catch (Exception e) {
logger.LogDebug ($"Failed to Load {step.Url} ({e.Message})");
logger.LogDebug ($"Failed to load {step.Url} ({e.Message})");
}
if (assembly == null)
continue;
@@ -686,7 +787,7 @@ namespace WebAssembly.Net.Debugging {
}
foreach (var method in doc.Methods) {
foreach (var sequencePoint in method.methodDef.DebugInformation.SequencePoints) {
foreach (var sequencePoint in method.DebugInformation.SequencePoints) {
if (!sequencePoint.IsHidden && Match (sequencePoint, start, end))
res.Add (new SourceLocation (method, sequencePoint));
}
@@ -729,8 +830,7 @@ namespace WebAssembly.Net.Debugging {
yield break;
foreach (var method in sourceFile.Methods) {
foreach (var sequencePoint in method.methodDef.DebugInformation.SequencePoints) {
//FIXME handle multi doc methods
foreach (var sequencePoint in method.DebugInformation.SequencePoints) {
if (!sequencePoint.IsHidden && Match (sequencePoint, request.Line, request.Column))
yield return new SourceLocation (method, sequencePoint);
}
@@ -19,12 +19,21 @@ namespace WebAssembly.Net.Debugging {
this.sessionId = sessionId;
}
// hashset treats 0 as unset
public override int GetHashCode ()
=> sessionId?.GetHashCode () ?? 0;
=> sessionId?.GetHashCode () ?? -1;
public override bool Equals (object obj)
=> (obj is SessionId) ? ((SessionId) obj).sessionId == sessionId : false;
public static bool operator == (SessionId a, SessionId b)
=> a.sessionId == b.sessionId;
public static bool operator != (SessionId a, SessionId b)
=> a.sessionId != b.sessionId;
public static SessionId Null { get; } = new SessionId ();
public override string ToString ()
=> $"session-{sessionId}";
}
@@ -52,6 +61,42 @@ namespace WebAssembly.Net.Debugging {
=> (obj is MessageId) ? ((MessageId) obj).sessionId == sessionId && ((MessageId) obj).id == id : false;
}
internal class DotnetObjectId {
public string Scheme { get; }
public string Value { get; }
public static bool TryParse (JToken jToken, out DotnetObjectId objectId)
=> TryParse (jToken?.Value<string>(), out objectId);
public static bool TryParse (string id, out DotnetObjectId objectId)
{
objectId = null;
if (id == null)
return false;
if (!id.StartsWith ("dotnet:"))
return false;
var parts = id.Split (":", 3);
if (parts.Length < 3)
return false;
objectId = new DotnetObjectId (parts[1], parts[2]);
return true;
}
public DotnetObjectId (string scheme, string value)
{
Scheme = scheme;
Value = value;
}
public override string ToString ()
=> $"dotnet:{Scheme}:{Value}";
}
internal struct Result {
public JObject Value { get; private set; }
public JObject Error { get; private set; }
@@ -89,6 +134,9 @@ namespace WebAssembly.Net.Debugging {
public static Result Err (JObject err)
=> new Result (null, err);
public static Result Err (string msg)
=> new Result (null, JObject.FromObject (new { message = msg }));
public static Result Exception (Exception e)
=> new Result (null, JObject.FromObject (new { message = e.Message }));
@@ -139,23 +187,23 @@ namespace WebAssembly.Net.Debugging {
public static MonoCommands ClearAllBreakpoints ()
=> new MonoCommands ("MONO.mono_wasm_clear_all_breakpoints()");
public static MonoCommands GetObjectProperties (int objectId, bool expandValueTypes)
=> new MonoCommands ($"MONO.mono_wasm_get_object_properties({objectId}, { (expandValueTypes ? "true" : "false") })");
public static MonoCommands GetArrayValues (int objectId)
=> new MonoCommands ($"MONO.mono_wasm_get_array_values({objectId})");
public static MonoCommands GetArrayValueExpanded (int objectId, int idx)
=> new MonoCommands ($"MONO.mono_wasm_get_array_value_expanded({objectId}, {idx})");
public static MonoCommands GetDetails (DotnetObjectId objectId, JToken args = null)
=> new MonoCommands ($"MONO.mono_wasm_get_details ('{objectId}', {(args ?? "{}")})");
public static MonoCommands GetScopeVariables (int scopeId, params int[] vars)
=> new MonoCommands ($"MONO.mono_wasm_get_variables({scopeId}, [ {string.Join (",", vars)} ])");
public static MonoCommands SetBreakpoint (string assemblyName, int methodToken, int ilOffset)
public static MonoCommands SetBreakpoint (string assemblyName, uint methodToken, int ilOffset)
=> new MonoCommands ($"MONO.mono_wasm_set_breakpoint (\"{assemblyName}\", {methodToken}, {ilOffset})");
public static MonoCommands RemoveBreakpoint (int breakpointId)
=> new MonoCommands ($"MONO.mono_wasm_remove_breakpoint({breakpointId})");
public static MonoCommands ReleaseObject (DotnetObjectId objectId)
=> new MonoCommands ($"MONO.mono_wasm_release_object('{objectId}')");
public static MonoCommands CallFunctionOn (JToken args)
=> new MonoCommands ($"MONO.mono_wasm_call_function_on ({args.ToString ()})");
}
internal enum MonoErrorCodes {
@@ -229,8 +277,7 @@ namespace WebAssembly.Net.Debugging {
internal DebugStore store;
public TaskCompletionSource<DebugStore> Source { get; } = new TaskCompletionSource<DebugStore> ();
int nextValueTypeId = 0;
public Dictionary<string, JToken> ValueTypesCache = new Dictionary<string, JToken> ();
public Dictionary<string, JToken> LocalsCache = new Dictionary<string, JToken> ();
public DebugStore Store {
get {
@@ -244,11 +291,8 @@ namespace WebAssembly.Net.Debugging {
public void ClearState ()
{
CallStack = null;
ValueTypesCache.Clear ();
nextValueTypeId = 0;
LocalsCache.Clear ();
}
public int NextValueTypeId () => Interlocked.Increment (ref nextValueTypeId);
}
}
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.WebSockets;
@@ -118,7 +119,10 @@ namespace WebAssembly.Net.Debugging {
void Send (WebSocket to, JObject o, CancellationToken token)
{
var sender = browser == to ? "Send-browser" : "Send-ide";
Log ("protocol", $"{sender}: {o}");
var method = o ["method"]?.ToString ();
//if (method != "Debugger.scriptParsed" && method != "Runtime.consoleAPICalled")
Log ("protocol", $"{sender}: " + JsonConvert.SerializeObject (o));
var bytes = Encoding.UTF8.GetBytes (o.ToString ());
var queue = GetQueueForSocket (to);
@@ -165,9 +169,12 @@ namespace WebAssembly.Net.Debugging {
void ProcessBrowserMessage (string msg, CancellationToken token)
{
Log ("protocol", $"browser: {msg}");
var res = JObject.Parse (msg);
var method = res ["method"]?.ToString ();
//if (method != "Debugger.scriptParsed" && method != "Runtime.consoleAPICalled")
Log ("protocol", $"browser: {msg}");
if (res ["id"] == null)
pending_ops.Add (OnEvent (new SessionId (res ["sessionId"]?.Value<string> ()), res ["method"].Value<string> (), res ["params"] as JObject, token));
else
@@ -239,7 +246,7 @@ namespace WebAssembly.Net.Debugging {
{
JObject o = result.ToJObject (id);
if (result.IsErr)
logger.LogError ("sending error response {result}", result);
logger.LogError ($"sending error response for id: {id} -> {result}");
Send (this.ide, o, token);
}
@@ -15,14 +15,49 @@ using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace WebAssembly.Net.Debugging {
internal class EvaluateExpression {
class FindVariableNMethodCall : CSharpSyntaxWalker {
public List<IdentifierNameSyntax> variables = new List<IdentifierNameSyntax> ();
public List<InvocationExpressionSyntax> methodCall = new List<InvocationExpressionSyntax> ();
public List<object> values = new List<Object> ();
class FindThisExpression : CSharpSyntaxWalker {
public List<string> thisExpressions = new List<string> ();
public SyntaxTree syntaxTree;
public FindThisExpression (SyntaxTree syntax)
{
syntaxTree = syntax;
}
public override void Visit (SyntaxNode node)
{
if (node is IdentifierNameSyntax)
variables.Add (node as IdentifierNameSyntax);
if (node is ThisExpressionSyntax) {
if (node.Parent is MemberAccessExpressionSyntax thisParent && thisParent.Name is IdentifierNameSyntax) {
IdentifierNameSyntax var = thisParent.Name as IdentifierNameSyntax;
thisExpressions.Add(var.Identifier.Text);
var newRoot = syntaxTree.GetRoot ().ReplaceNode (node.Parent, thisParent.Name);
syntaxTree = syntaxTree.WithRootAndOptions (newRoot, syntaxTree.Options);
this.Visit (GetExpressionFromSyntaxTree(syntaxTree));
}
}
else
base.Visit (node);
}
public async Task CheckIfIsProperty (MonoProxy proxy, MessageId msg_id, int scope_id, CancellationToken token)
{
foreach (var var in thisExpressions) {
JToken value = await proxy.TryGetVariableValue (msg_id, scope_id, var, true, token);
if (value == null)
throw new Exception ($"The property {var} does not exist in the current context");
}
}
}
class FindVariableNMethodCall : CSharpSyntaxWalker {
public List<IdentifierNameSyntax> variables = new List<IdentifierNameSyntax> ();
public List<ThisExpressionSyntax> thisList = new List<ThisExpressionSyntax> ();
public List<InvocationExpressionSyntax> methodCall = new List<InvocationExpressionSyntax> ();
public List<object> values = new List<Object> ();
public override void Visit (SyntaxNode node)
{
if (node is IdentifierNameSyntax identifier && !variables.Any (x => x.Identifier.Text == identifier.Identifier.Text))
variables.Add (identifier);
if (node is InvocationExpressionSyntax) {
methodCall.Add (node as InvocationExpressionSyntax);
throw new Exception ("Method Call is not implemented yet");
@@ -33,15 +68,15 @@ namespace WebAssembly.Net.Debugging {
}
public async Task<SyntaxTree> ReplaceVars (SyntaxTree syntaxTree, MonoProxy proxy, MessageId msg_id, int scope_id, CancellationToken token)
{
CompilationUnitSyntax root = syntaxTree.GetCompilationUnitRoot ();
foreach (var var in variables) {
CompilationUnitSyntax root = syntaxTree.GetCompilationUnitRoot ();
ClassDeclarationSyntax classDeclaration = root.Members.ElementAt (0) as ClassDeclarationSyntax;
MethodDeclarationSyntax method = classDeclaration.Members.ElementAt (0) as MethodDeclarationSyntax;
JObject value = await proxy.TryGetVariableValue (msg_id, scope_id, var.Identifier.Text, token);
JToken value = await proxy.TryGetVariableValue (msg_id, scope_id, var.Identifier.Text, false, token);
if (value == null)
throw new Exception ("The name \"" + var.Identifier.Text + "\" does not exist in the current context");
throw new Exception ($"The name {var.Identifier.Text} does not exist in the current context");
values.Add (ConvertJSToCSharpType (value ["value"] ["value"].ToString (), value ["value"] ["type"].ToString ()));
@@ -49,9 +84,9 @@ namespace WebAssembly.Net.Debugging {
SyntaxFactory.Parameter (
SyntaxFactory.Identifier (var.Identifier.Text))
.WithType (SyntaxFactory.ParseTypeName (GetTypeFullName(value["value"]["type"].ToString()))));
var newRoot = root.ReplaceNode (method, updatedMethod);
syntaxTree = syntaxTree.WithRootAndOptions (newRoot, syntaxTree.Options);
root = root.ReplaceNode (method, updatedMethod);
}
syntaxTree = syntaxTree.WithRootAndOptions (root, syntaxTree.Options);
return syntaxTree;
}
@@ -79,8 +114,19 @@ namespace WebAssembly.Net.Debugging {
throw new Exception ($"Evaluate of this datatype {type} not implemented yet");
}
}
public static async Task<string> CompileAndRunTheExpression (MonoProxy proxy, MessageId msg_id, int scope_id, string expression, CancellationToken token)
static SyntaxNode GetExpressionFromSyntaxTree (SyntaxTree syntaxTree)
{
CompilationUnitSyntax root = syntaxTree.GetCompilationUnitRoot ();
ClassDeclarationSyntax classDeclaration = root.Members.ElementAt (0) as ClassDeclarationSyntax;
MethodDeclarationSyntax methodDeclaration = classDeclaration.Members.ElementAt (0) as MethodDeclarationSyntax;
BlockSyntax blockValue = methodDeclaration.Body;
ReturnStatementSyntax returnValue = blockValue.Statements.ElementAt (0) as ReturnStatementSyntax;
InvocationExpressionSyntax expressionInvocation = returnValue.Expression as InvocationExpressionSyntax;
MemberAccessExpressionSyntax expressionMember = expressionInvocation.Expression as MemberAccessExpressionSyntax;
ParenthesizedExpressionSyntax expressionParenthesized = expressionMember.Expression as ParenthesizedExpressionSyntax;
return expressionParenthesized.Expression;
}
internal static async Task<string> CompileAndRunTheExpression (MonoProxy proxy, MessageId msg_id, int scope_id, string expression, CancellationToken token)
{
FindVariableNMethodCall findVarNMethodCall = new FindVariableNMethodCall ();
string retString;
@@ -94,16 +140,13 @@ namespace WebAssembly.Net.Debugging {
}
}");
CompilationUnitSyntax root = syntaxTree.GetCompilationUnitRoot ();
ClassDeclarationSyntax classDeclaration = root.Members.ElementAt (0) as ClassDeclarationSyntax;
MethodDeclarationSyntax methodDeclaration = classDeclaration.Members.ElementAt (0) as MethodDeclarationSyntax;
BlockSyntax blockValue = methodDeclaration.Body;
ReturnStatementSyntax returnValue = blockValue.Statements.ElementAt (0) as ReturnStatementSyntax;
InvocationExpressionSyntax expressionInvocation = returnValue.Expression as InvocationExpressionSyntax;
MemberAccessExpressionSyntax expressionMember = expressionInvocation.Expression as MemberAccessExpressionSyntax;
ParenthesizedExpressionSyntax expressionParenthesized = expressionMember.Expression as ParenthesizedExpressionSyntax;
var expressionTree = expressionParenthesized.Expression;
FindThisExpression findThisExpression = new FindThisExpression (syntaxTree);
var expressionTree = GetExpressionFromSyntaxTree(syntaxTree);
findThisExpression.Visit (expressionTree);
await findThisExpression.CheckIfIsProperty (proxy, msg_id, scope_id, token);
syntaxTree = findThisExpression.syntaxTree;
expressionTree = GetExpressionFromSyntaxTree (syntaxTree);
findVarNMethodCall.Visit (expressionTree);
syntaxTree = await findVarNMethodCall.ReplaceVars (syntaxTree, proxy, msg_id, scope_id, token);
@@ -14,11 +14,14 @@ using Microsoft.CodeAnalysis;
namespace WebAssembly.Net.Debugging {
internal class MonoProxy : DevToolsProxy {
HashSet<SessionId> sessions = new HashSet<SessionId> ();
Dictionary<SessionId, ExecutionContext> contexts = new Dictionary<SessionId, ExecutionContext> ();
public MonoProxy (ILoggerFactory loggerFactory) : base(loggerFactory) { }
public MonoProxy (ILoggerFactory loggerFactory, bool hideWebDriver = true) : base(loggerFactory) { this.hideWebDriver = hideWebDriver; }
ExecutionContext GetContext (SessionId sessionId)
readonly bool hideWebDriver;
internal ExecutionContext GetContext (SessionId sessionId)
{
if (contexts.TryGetValue (sessionId, out var context))
return context;
@@ -76,7 +79,7 @@ namespace WebAssembly.Net.Debugging {
break;
}
case "Debugger.scriptParsed":{
case "Debugger.scriptParsed": {
var url = args? ["url"]?.Value<string> () ?? "";
switch (url) {
@@ -89,7 +92,15 @@ namespace WebAssembly.Net.Debugging {
Log ("verbose", $"proxying Debugger.scriptParsed ({sessionId.sessionId}) {url} {args}");
break;
}
case "Target.attachedToTarget": {
if (args["targetInfo"]["type"]?.ToString() == "page")
await DeleteWebDriver (new SessionId (args["sessionId"]?.ToString ()), token);
break;
}
}
return false;
}
@@ -99,12 +110,25 @@ namespace WebAssembly.Net.Debugging {
return res.Value? ["result"]? ["value"]?.Value<bool> () ?? false;
}
static int bpIdGenerator;
protected override async Task<bool> AcceptCommand (MessageId id, string method, JObject args, CancellationToken token)
{
// Inspector doesn't use the Target domain or sessions
// so we try to init immediately
if (hideWebDriver && id == SessionId.Null)
await DeleteWebDriver (id, token);
if (!contexts.TryGetValue (id, out var context))
return false;
switch (method) {
case "Target.attachToTarget": {
var resp = await SendCommand (id, method, args, token);
await DeleteWebDriver (new SessionId (resp.Value ["sessionId"]?.ToString ()), token);
break;
}
case "Debugger.enable": {
var resp = await SendCommand (id, method, args, token);
@@ -142,7 +166,7 @@ namespace WebAssembly.Net.Debugging {
//FIXME support variant where restrictToFunction=true and end is omitted
var end = SourceLocation.Parse (args? ["end"] as JObject);
if (start != null && end != null && await GetPossibleBreakpoints (id, start, end, token))
return true;
return true;
SendResponse (id, resp, token);
return true;
@@ -160,21 +184,39 @@ namespace WebAssembly.Net.Debugging {
}
var bpid = resp.Value["breakpointId"]?.ToString ();
var locations = resp.Value["locations"]?.Values<object>();
var request = BreakpointRequest.Parse (bpid, args);
context.BreakpointRequests[bpid] = request;
// is the store done loading?
var loaded = context.Source.Task.IsCompleted;
if (!loaded) {
// Send and empty response immediately if not
// and register the breakpoint for resolution
context.BreakpointRequests [bpid] = request;
SendResponse (id, resp, token);
}
if (await IsRuntimeAlreadyReadyAlready (id, token)) {
var store = await RuntimeReady (id, token);
Log ("verbose", $"BP req {args}");
await SetBreakpoint (id, store, request, token);
await SetBreakpoint (id, store, request, !loaded, token);
}
SendResponse (id, Result.OkFromObject (request.AsSetBreakpointByUrlResponse()), token);
if (loaded) {
// we were already loaded so we should send a response
// with the locations included and register the request
context.BreakpointRequests [bpid] = request;
var result = Result.OkFromObject (request.AsSetBreakpointByUrlResponse (locations));
SendResponse (id, result, token);
}
return true;
}
case "Debugger.removeBreakpoint": {
return await RemoveBreakpoint (id, args, token);
await RemoveBreakpoint (id, args, token);
break;
}
case "Debugger.resume": {
@@ -195,85 +237,153 @@ namespace WebAssembly.Net.Debugging {
}
case "Debugger.evaluateOnCallFrame": {
var objId = args? ["callFrameId"]?.Value<string> ();
if (objId.StartsWith ("dotnet:", StringComparison.Ordinal)) {
var parts = objId.Split (new char [] { ':' });
if (parts.Length < 3)
return true;
switch (parts [1]) {
case "scope": {
await GetEvaluateOnCallFrame (id, int.Parse (parts [2]), args? ["expression"]?.Value<string> (), token);
break;
}
}
return true;
if (!DotnetObjectId.TryParse (args? ["callFrameId"], out var objectId))
return false;
switch (objectId.Scheme) {
case "scope":
return await OnEvaluateOnCallFrame (id,
int.Parse (objectId.Value),
args? ["expression"]?.Value<string> (), token);
default:
return false;
}
return false;
}
case "Runtime.getProperties": {
var objId = args? ["objectId"]?.Value<string> ();
if (objId.StartsWith ("dotnet:", StringComparison.Ordinal)) {
var parts = objId.Split (new char [] { ':' });
if (parts.Length < 3)
return true;
switch (parts[1]) {
case "scope": {
await GetScopeProperties (id, int.Parse (parts[2]), token);
break;
}
case "object": {
await GetDetails (id, MonoCommands.GetObjectProperties (int.Parse (parts[2]), expandValueTypes: false), token);
break;
}
case "array": {
await GetArrayDetails (id, objId, parts, token);
break;
}
case "valuetype": {
await GetDetailsForValueType (id, objId,
get_props_cmd_fn: () => {
if (parts.Length < 4)
return null;
if (!DotnetObjectId.TryParse (args? ["objectId"], out var objectId))
break;
var containerObjId = int.Parse (parts[2]);
return MonoCommands.GetObjectProperties (containerObjId, expandValueTypes: true);
}, token);
break;
}
}
var result = await RuntimeGetProperties (id, objectId, args, token);
SendResponse (id, result, token);
return true;
}
case "Runtime.releaseObject": {
if (!(DotnetObjectId.TryParse (args ["objectId"], out var objectId) && objectId.Scheme == "cfo_res"))
break;
await SendMonoCommand (id, MonoCommands.ReleaseObject (objectId), token);
SendResponse (id, Result.OkFromObject (new{}), token);
return true;
}
// Protocol extensions
case "Dotnet-test.setBreakpointByMethod": {
Console.WriteLine ("set-breakpoint-by-method: " + id + " " + args);
var store = await RuntimeReady (id, token);
string aname = args ["assemblyName"]?.Value<string> ();
string typeName = args ["typeName"]?.Value<string> ();
string methodName = args ["methodName"]?.Value<string> ();
if (aname == null || typeName == null || methodName == null) {
SendResponse (id, Result.Err ("Invalid protocol message '" + args + "'."), token);
return true;
}
// GetAssemblyByName seems to work on file names
var assembly = store.GetAssemblyByName (aname);
if (assembly == null)
assembly = store.GetAssemblyByName (aname + ".exe");
if (assembly == null)
assembly = store.GetAssemblyByName (aname + ".dll");
if (assembly == null) {
SendResponse (id, Result.Err ("Assembly '" + aname + "' not found."), token);
return true;
}
var type = assembly.GetTypeByName (typeName);
if (type == null) {
SendResponse (id, Result.Err ($"Type '{typeName}' not found."), token);
return true;
}
var methodInfo = type.Methods.FirstOrDefault (m => m.Name == methodName);
if (methodInfo == null) {
SendResponse (id, Result.Err ($"Method '{typeName}:{methodName}' not found."), token);
return true;
}
bpIdGenerator ++;
string bpid = "by-method-" + bpIdGenerator.ToString ();
var request = new BreakpointRequest (bpid, methodInfo);
context.BreakpointRequests[bpid] = request;
var loc = methodInfo.StartLocation;
var bp = await SetMonoBreakpoint (id, bpid, loc, token);
if (bp.State != BreakpointState.Active) {
// FIXME:
throw new NotImplementedException ();
}
var resolvedLocation = new {
breakpointId = bpid,
location = loc.AsLocation ()
};
SendEvent (id, "Debugger.breakpointResolved", JObject.FromObject (resolvedLocation), token);
SendResponse (id, Result.OkFromObject (new {
result = new { breakpointId = bpid, locations = new object [] { loc.AsLocation () }}
}), token);
return true;
}
case "Runtime.callFunctionOn": {
if (!DotnetObjectId.TryParse (args ["objectId"], out var objectId))
return false;
var silent = args ["silent"]?.Value<bool> () ?? false;
if (objectId.Scheme == "scope") {
var fail = silent ? Result.OkFromObject (new { result = new { } }) : Result.Exception (new ArgumentException ($"Runtime.callFunctionOn not supported with scope ({objectId})."));
SendResponse (id, fail, token);
return true;
}
break;
var returnByValue = args ["returnByValue"]?.Value<bool> () ?? false;
var res = await SendMonoCommand (id, MonoCommands.CallFunctionOn (args), token);
if (!returnByValue &&
DotnetObjectId.TryParse (res.Value?["result"]?["value"]?["objectId"], out var resultObjectId) &&
resultObjectId.Scheme == "cfo_res")
res = Result.OkFromObject (new { result = res.Value ["result"]["value"] });
if (res.IsErr && silent)
res = Result.OkFromObject (new { result = new { } });
SendResponse (id, res, token);
return true;
}
}
return false;
}
async Task GetArrayDetails (MessageId id, string objId, string[] objIdParts, CancellationToken token)
async Task<Result> RuntimeGetProperties (MessageId id, DotnetObjectId objectId, JToken args, CancellationToken token)
{
switch (objIdParts.Length)
{
case 3: {
await GetDetails (id, MonoCommands.GetArrayValues (int.Parse (objIdParts [2])), token);
break;
}
case 4: {
// This form of the id is being used only for valuetypes right now
await GetDetailsForValueType(id, objId,
get_props_cmd_fn: () => {
var arrayObjectId = int.Parse (objIdParts [2]);
var idx = int.Parse (objIdParts [3]);
return MonoCommands.GetArrayValueExpanded (arrayObjectId, idx);
}, token);
break;
}
default:
SendResponse (id, Result.Exception (new ArgumentException ($"Unknown objectId format for array: {objId}")), token);
break;
if (objectId.Scheme == "scope")
return await GetScopeProperties (id, int.Parse (objectId.Value), token);
var res = await SendMonoCommand (id, MonoCommands.GetDetails (objectId, args), token);
if (res.IsErr)
return res;
if (objectId.Scheme == "cfo_res") {
// Runtime.callFunctionOn result object
var value_json_str = res.Value ["result"]?["value"]?["__value_as_json_string__"]?.Value<string> ();
if (value_json_str != null) {
res = Result.OkFromObject (new {
result = JArray.Parse (value_json_str.Replace (@"\""", "\""))
});
} else {
res = Result.OkFromObject (new { result = new {} });
}
} else {
res = Result.Ok (JObject.FromObject (new { result = res.Value ["result"] ["value"] }));
}
return res;
}
//static int frame_id=0;
@@ -318,9 +428,12 @@ namespace WebAssembly.Net.Debugging {
foreach (var mono_frame in the_mono_frames) {
++frame_id;
var il_pos = mono_frame ["il_pos"].Value<int> ();
var method_token = mono_frame ["method_token"].Value<int> ();
var method_token = mono_frame ["method_token"].Value<uint> ();
var assembly_name = mono_frame ["assembly_name"].Value<string> ();
// This can be different than `method.Name`, like in case of generic methods
var method_name = mono_frame ["method_name"]?.Value<string> ();
var store = await LoadStore (sessionId, token);
var asm = store.GetAssemblyByName (assembly_name);
if (asm == null) {
@@ -346,11 +459,11 @@ namespace WebAssembly.Net.Debugging {
}
Log ("info", $"frame il offset: {il_pos} method token: {method_token} assembly name: {assembly_name}");
Log ("info", $"\tmethod {method.Name} location: {location}");
Log ("info", $"\tmethod {method_name} location: {location}");
frames.Add (new Frame (method, location, frame_id-1));
callFrames.Add (new {
functionName = method.Name,
functionName = method_name,
callFrameId = $"dotnet:scope:{frame_id-1}",
functionLocation = method.StartLocation.AsLocation (),
@@ -367,7 +480,7 @@ namespace WebAssembly.Net.Debugging {
description = "Object",
objectId = $"dotnet:scope:{frame_id-1}",
},
name = method.Name,
name = method_name,
startLocation = method.StartLocation.AsLocation (),
endLocation = method.EndLocation.AsLocation (),
}}
@@ -443,89 +556,74 @@ namespace WebAssembly.Net.Debugging {
return true;
}
async Task GetDetails(MessageId msg_id, MonoCommands cmd, CancellationToken token, bool send_response = true)
internal bool TryFindVariableValueInCache(ExecutionContext ctx, string expression, bool only_search_on_this, out JToken obj)
{
var res = await SendMonoCommand(msg_id, cmd, 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;
if (ctx.LocalsCache.TryGetValue (expression, out obj)) {
if (only_search_on_this && obj["fromThis"] == null)
return false;
return true;
}
try {
var var_list = res.Value?["result"]?["value"]?.Values<JObject>().ToArray() ?? Array.Empty<JObject>();
if (var_list.Length > 0)
ExtractAndCacheValueTypes (GetContext (msg_id), var_list);
if (!send_response)
return;
var response = JObject.FromObject(new
{
result = var_list
});
SendResponse(msg_id, Result.Ok(response), token);
} catch (Exception e) when (send_response) {
Log ("verbose", $"failed to parse {res.Value} - {e.Message}");
SendResponse(msg_id, Result.Exception(e), token);
}
return false;
}
internal async Task<JObject> TryGetVariableValue (MessageId msg_id, int scope_id, string expression, CancellationToken token)
internal async Task<JToken> TryGetVariableValue (MessageId msg_id, int scope_id, string expression, bool only_search_on_this, CancellationToken token)
{
JObject thisValue = null;
JToken thisValue = null;
var context = GetContext (msg_id);
if (context.CallStack == null)
return null;
if (TryFindVariableValueInCache(context, expression, only_search_on_this, out JToken obj))
return obj;
var scope = context.CallStack.FirstOrDefault (s => s.Id == scope_id);
var vars = scope.Method.GetLiveVarsAt (scope.Location.CliLocation.Offset);
var live_vars = scope.Method.GetLiveVarsAt (scope.Location.CliLocation.Offset);
//get_this
int [] var_ids = { };
var res = await SendMonoCommand (msg_id, MonoCommands.GetScopeVariables (scope.Id, var_ids), token);
var values = res.Value? ["result"]? ["value"]?.Values<JObject> ().ToArray ();
thisValue = values.FirstOrDefault (v => v ["name"].Value<string> () == "this");
if (thisValue != null && expression == "this") {
return thisValue;
}
//search in locals
var var_id = vars.SingleOrDefault (v => v.Name == expression);
if (var_id != null) {
res = await SendMonoCommand (msg_id, MonoCommands.GetScopeVariables (scope.Id, new int [] { var_id.Index }), token);
values = res.Value? ["result"]? ["value"]?.Values<JObject> ().ToArray ();
return values [0];
var res = await SendMonoCommand (msg_id, MonoCommands.GetScopeVariables (scope.Id, live_vars.Select (lv => lv.Index).ToArray ()), token);
var scope_values = res.Value? ["result"]? ["value"]?.Values<JObject> ()?.ToArray ();
thisValue = scope_values?.FirstOrDefault (v => v ["name"]?.Value<string> () == "this");
if (!only_search_on_this) {
if (thisValue != null && expression == "this")
return thisValue;
var value = scope_values.SingleOrDefault (sv => sv ["name"]?.Value<string> () == expression);
if (value != null)
return value;
}
//search in scope
if (thisValue != null) {
var objectId = thisValue ["value"] ["objectId"].Value<string> ();
var parts = objectId.Split (new char [] { ':' });
res = await SendMonoCommand (msg_id, MonoCommands.GetObjectProperties (int.Parse (parts [2]), expandValueTypes: false), token);
values = res.Value? ["result"]? ["value"]?.Values<JObject> ().ToArray ();
var foundValue = values.FirstOrDefault (v => v ["name"].Value<string> () == expression);
if (foundValue != null)
if (!DotnetObjectId.TryParse (thisValue ["value"] ["objectId"], out var objectId))
return null;
res = await SendMonoCommand (msg_id, MonoCommands.GetDetails (objectId), token);
scope_values = res.Value? ["result"]? ["value"]?.Values<JObject> ().ToArray ();
var foundValue = scope_values.FirstOrDefault (v => v ["name"].Value<string> () == expression);
if (foundValue != null) {
foundValue["fromThis"] = true;
context.LocalsCache[foundValue ["name"].Value<string> ()] = foundValue;
return foundValue;
}
}
return null;
}
async Task GetEvaluateOnCallFrame (MessageId msg_id, int scope_id, string expression, CancellationToken token)
async Task<bool> OnEvaluateOnCallFrame (MessageId msg_id, int scope_id, string expression, CancellationToken token)
{
try {
var context = GetContext (msg_id);
if (context.CallStack == null)
return;
return false;
var varValue = await TryGetVariableValue (msg_id, scope_id, expression, token);
var varValue = await TryGetVariableValue (msg_id, scope_id, expression, false, token);
if (varValue != null) {
varValue ["value"] ["description"] = varValue ["value"] ["className"];
SendResponse (msg_id, Result.OkFromObject (new {
result = varValue ["value"]
}), token);
return;
return true;
}
string retValue = await EvaluateExpression.CompileAndRunTheExpression (this, msg_id, scope_id, expression, token);
@@ -534,123 +632,62 @@ namespace WebAssembly.Net.Debugging {
value = retValue
}
}), token);
return true;
} catch (Exception e) {
logger.LogTrace (e.Message, expression);
SendResponse (msg_id, Result.OkFromObject (new {}), token);
logger.LogDebug (e, $"Error in EvaluateOnCallFrame for expression '{expression}.");
}
return false;
}
async Task GetScopeProperties (MessageId msg_id, int scope_id, CancellationToken token)
async Task<Result> GetScopeProperties (MessageId msg_id, int scope_id, CancellationToken token)
{
try {
var ctx = GetContext (msg_id);
var scope = ctx.CallStack.FirstOrDefault (s => s.Id == scope_id);
if (scope == null) {
SendResponse (msg_id,
Result.Err (JObject.FromObject (new { message = $"Could not find scope with id #{scope_id}" })),
token);
return;
}
if (scope == null)
return Result.Err (JObject.FromObject (new { message = $"Could not find scope with id #{scope_id}" }));
var vars = scope.Method.GetLiveVarsAt (scope.Location.CliLocation.Offset);
var var_ids = vars.Select (v => v.Index).ToArray ();
var res = await SendMonoCommand (msg_id, MonoCommands.GetScopeVariables (scope.Id, var_ids), 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;
}
if (res.IsErr)
return res;
var values = res.Value? ["result"]? ["value"]?.Values<JObject> ().ToArray ();
if(values == null) {
SendResponse (msg_id, Result.OkFromObject (new {result = Array.Empty<object> ()}), token);
return;
}
ExtractAndCacheValueTypes (ctx, values);
if(values == null)
return Result.OkFromObject (new { result = Array.Empty<object> () });
var var_list = new List<object> ();
int i = 0;
for (; i < vars.Length && i < values.Length; i ++)
var_list.Add (new { name = vars [i].Name, value = values [i]["value"] });
for (; i < values.Length; i ++)
var_list.Add (values [i]);
for (; i < vars.Length && i < values.Length; i ++) {
// For async methods, we get locals with names, unlike non-async methods
// and the order may not match the var_ids, so, use the names that they
// come with
if (values [i]["name"] != null)
continue;
SendResponse (msg_id, Result.OkFromObject (new { result = var_list }), token);
ctx.LocalsCache[vars [i].Name] = values [i];
var_list.Add (new { name = vars [i].Name, value = values [i]["value"] });
}
for (; i < values.Length; i ++) {
ctx.LocalsCache[values [i]["name"].ToString()] = values [i];
var_list.Add (values [i]);
}
return Result.OkFromObject (new { result = var_list });
} catch (Exception exception) {
Log ("verbose", $"Error resolving scope properties {exception.Message}");
SendResponse (msg_id, Result.Exception (exception), token);
return Result.Exception (exception);
}
}
IEnumerable<JObject> ExtractAndCacheValueTypes (ExecutionContext ctx, IEnumerable<JObject> var_list)
async Task<Breakpoint> SetMonoBreakpoint (SessionId sessionId, string reqId, SourceLocation location, CancellationToken token)
{
foreach (var jo in var_list) {
var value = jo["value"]?.Value<JObject> ();
if (value ["type"]?.Value<string> () != "object")
continue;
if (!(value ["isValueType"]?.Value<bool> () ?? false) || // not a valuetype
!(value ["expanded"]?.Value<bool> () ?? false)) // not expanded
continue;
// Expanded ValueType
var members = value ["members"]?.Values<JObject>().ToArray() ?? Array.Empty<JObject>();
var objectId = value ["objectId"]?.Value<string> () ?? $"dotnet:valuetype:{ctx.NextValueTypeId ()}";
value ["objectId"] = objectId;
ExtractAndCacheValueTypes (ctx, members);
ctx.ValueTypesCache [objectId] = JArray.FromObject (members);
value.Remove ("members");
}
return var_list;
}
async Task<bool> GetDetailsForValueType (MessageId msg_id, string object_id, Func<MonoCommands> get_props_cmd_fn, CancellationToken token)
{
var ctx = GetContext (msg_id);
if (!ctx.ValueTypesCache.ContainsKey (object_id)) {
var cmd = get_props_cmd_fn ();
if (cmd == null) {
SendResponse (msg_id, Result.Exception (new ArgumentException (
"Could not find a cached value for {object_id}, and cant' expand it.")),
token);
return false;
} else {
await GetDetails (msg_id, cmd, token, send_response: false);
}
}
if (ctx.ValueTypesCache.TryGetValue (object_id, out var var_list)) {
var response = JObject.FromObject(new
{
result = var_list
});
SendResponse(msg_id, Result.Ok(response), token);
return true;
} else {
var response = JObject.FromObject(new
{
result = $"Unable to get details for {object_id}"
});
SendResponse(msg_id, Result.Err(response), token);
return false;
}
}
async Task<Breakpoint> SetMonoBreakpoint (SessionId sessionId, BreakpointRequest req, SourceLocation location, CancellationToken token)
{
var bp = new Breakpoint (req.Id, location, BreakpointState.Pending);
var bp = new Breakpoint (reqId, location, BreakpointState.Pending);
var asm_name = bp.Location.CliLocation.Method.Assembly.Name;
var method_token = bp.Location.CliLocation.Method.Token;
var il_offset = bp.Location.CliLocation.Offset;
@@ -687,7 +724,7 @@ namespace WebAssembly.Net.Debugging {
foreach (var req in context.BreakpointRequests.Values) {
if (req.TryResolve (source)) {
await SetBreakpoint (sessionId, context.store, req, token);
await SetBreakpoint (sessionId, context.store, req, true, token);
}
}
}
@@ -718,12 +755,12 @@ namespace WebAssembly.Net.Debugging {
return store;
}
async Task<bool> RemoveBreakpoint(MessageId msg_id, JObject args, CancellationToken token) {
async Task RemoveBreakpoint(MessageId msg_id, JObject args, CancellationToken token) {
var bpid = args? ["breakpointId"]?.Value<string> ();
var context = GetContext (msg_id);
if (!context.BreakpointRequests.TryGetValue (bpid, out var breakpointRequest))
return false;
return;
foreach (var bp in breakpointRequest.Locations) {
var res = await SendMonoCommand (msg_id, MonoCommands.RemoveBreakpoint (bp.RemoteId), token);
@@ -735,10 +772,9 @@ namespace WebAssembly.Net.Debugging {
}
}
breakpointRequest.Locations.Clear ();
return false;
}
async Task SetBreakpoint (SessionId sessionId, DebugStore store, BreakpointRequest req, CancellationToken token)
async Task SetBreakpoint (SessionId sessionId, DebugStore store, BreakpointRequest req, bool sendResolvedEvent, CancellationToken token)
{
var context = GetContext (sessionId);
if (req.Locations.Any ()) {
@@ -746,12 +782,22 @@ namespace WebAssembly.Net.Debugging {
return;
}
var locations = store.FindBreakpointLocations (req).ToList ();
var comparer = new SourceLocation.LocationComparer ();
// if column is specified the frontend wants the exact matches
// and will clear the bp if it isn't close enoug
var locations = store.FindBreakpointLocations (req)
.Distinct (comparer)
.Where (l => l.Line == req.Line && (req.Column == 0 || l.Column == req.Column))
.OrderBy (l => l.Column)
.GroupBy (l => l.Id);
logger.LogDebug ("BP request for '{req}' runtime ready {context.RuntimeReady}", req, GetContext (sessionId).IsRuntimeReady);
var breakpoints = new List<Breakpoint> ();
foreach (var loc in locations) {
var bp = await SetMonoBreakpoint (sessionId, req, loc, token);
foreach (var sourceId in locations) {
var loc = sourceId.First ();
var bp = await SetMonoBreakpoint (sessionId, req.Id, loc, token);
// If we didn't successfully enable the breakpoint
// don't add it to the list of locations for this id
@@ -765,7 +811,8 @@ namespace WebAssembly.Net.Debugging {
location = loc.AsLocation ()
};
SendEvent (sessionId, "Debugger.breakpointResolved", JObject.FromObject (resolvedLocation), token);
if (sendResolvedEvent)
SendEvent (sessionId, "Debugger.breakpointResolved", JObject.FromObject (resolvedLocation), token);
}
req.Locations.AddRange (breakpoints);
@@ -796,31 +843,18 @@ namespace WebAssembly.Net.Debugging {
return false;
var src_file = (await LoadStore (msg_id, token)).GetFileById (id);
var res = new StringWriter ();
try {
var uri = new Uri (src_file.Url);
string source = $"// Unable to find document {src_file.SourceUri}";
if (uri.IsFile && File.Exists(uri.LocalPath)) {
using (var f = new StreamReader (File.Open (uri.LocalPath, FileMode.Open))) {
await res.WriteAsync (await f.ReadToEndAsync ());
}
using (var data = await src_file.GetSourceAsync (checkHash: false, token: token)) {
if (data.Length == 0)
return false;
source = res.ToString ();
} else if (src_file.SourceUri.IsFile && File.Exists(src_file.SourceUri.LocalPath)) {
using (var f = new StreamReader (File.Open (src_file.SourceUri.LocalPath, FileMode.Open))) {
await res.WriteAsync (await f.ReadToEndAsync ());
}
source = res.ToString ();
} else if(src_file.SourceLinkUri != null) {
var doc = await new WebClient ().DownloadStringTaskAsync (src_file.SourceLinkUri);
await res.WriteAsync (doc);
source = res.ToString ();
using (var reader = new StreamReader (data))
source = await reader.ReadToEndAsync ();
}
SendResponse (msg_id, Result.OkFromObject (new { scriptSource = source }), token);
} catch (Exception e) {
var o = new {
@@ -833,5 +867,19 @@ namespace WebAssembly.Net.Debugging {
}
return true;
}
async Task DeleteWebDriver (SessionId sessionId, CancellationToken token)
{
// see https://github.com/mono/mono/issues/19549 for background
if (hideWebDriver && sessions.Add (sessionId)) {
var res = await SendCommand (sessionId,
"Page.addScriptToEvaluateOnNewDocument",
JObject.FromObject (new { source = "delete navigator.constructor.prototype.webdriver"}),
token);
if (sessionId != SessionId.Null && !res.IsOk)
sessions.Remove (sessionId);
}
}
}
}
+48 -38
View File
@@ -97,8 +97,8 @@ namespace WebAssembly.Net.Debugging {
proc.BeginErrorReadLine ();
proc.BeginOutputReadLine ();
if (await Task.WhenAny (tcs.Task, Task.Delay (2000)) != tcs.Task) {
Console.WriteLine ("Didnt get the con string after 2s.");
if (await Task.WhenAny (tcs.Task, Task.Delay (5000)) != tcs.Task) {
Console.WriteLine ("Didnt get the con string after 5s.");
throw new Exception ("node.js timedout");
}
var line = await tcs.Task;
@@ -132,9 +132,6 @@ namespace WebAssembly.Net.Debugging {
app.UseStaticFiles ();
TestHarnessOptions options = optionsAccessor.CurrentValue;
Console.WriteLine ($"Chrome from: '{options.ChromePath}'");
Console.WriteLine ($"Files from: '{options.AppPath}'");
Console.WriteLine ($"Using page : '{options.PagePath}'");
var provider = new FileExtensionContentTypeProvider();
provider.Mappings [".wasm"] = "application/wasm";
@@ -147,48 +144,56 @@ namespace WebAssembly.Net.Debugging {
});
var devToolsUrl = options.DevToolsUrl;
var psi = new ProcessStartInfo ();
psi.Arguments = $"--headless --disable-gpu --remote-debugging-port={devToolsUrl.Port} http://{TestHarnessProxy.Endpoint.Authority}/{options.PagePath}";
psi.UseShellExecute = false;
psi.FileName = options.ChromePath;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
app.UseRouter (router => {
router.MapGet ("launch-chrome-and-connect", async context => {
Console.WriteLine ("New test request");
var client = new HttpClient ();
await LaunchAndServe (psi, context, async (str) => {
string res = null;
var start = DateTime.Now;
try {
var client = new HttpClient ();
var psi = new ProcessStartInfo ();
while (res == null) {
// Unfortunately it does look like we have to wait
// for a bit after getting the response but before
// making the list request. We get an empty result
// if we make the request too soon.
await Task.Delay (100);
psi.Arguments = $"--headless --disable-gpu --lang=en-US --incognito --remote-debugging-port={devToolsUrl.Port} http://{TestHarnessProxy.Endpoint.Authority}/{options.PagePath}";
psi.UseShellExecute = false;
psi.FileName = options.ChromePath;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
res = await client.GetStringAsync (new Uri (new Uri (str), "/json/list"));
Console.WriteLine ("res is {0}", res);
var elapsed = DateTime.Now - start;
if (res == null && elapsed.Milliseconds > 2000) {
Console.WriteLine ($"Unable to get DevTools /json/list response in {elapsed.Seconds} seconds, stopping");
return null;
await LaunchAndServe (psi, context, async (str) => {
var start = DateTime.Now;
JArray obj = null;
while (true) {
// Unfortunately it does look like we have to wait
// for a bit after getting the response but before
// making the list request. We get an empty result
// if we make the request too soon.
await Task.Delay (100);
var res = await client.GetStringAsync (new Uri (new Uri (str), "/json/list"));
Console.WriteLine ("res is {0}", res);
if (!String.IsNullOrEmpty (res)) {
// Sometimes we seem to get an empty array `[ ]`
obj = JArray.Parse (res);
if (obj != null && obj.Count >= 1)
break;
}
var elapsed = DateTime.Now - start;
if (elapsed.Milliseconds > 5000) {
Console.WriteLine ($"Unable to get DevTools /json/list response in {elapsed.Seconds} seconds, stopping");
return null;
}
}
}
var obj = JArray.Parse (res);
if (obj == null || obj.Count < 1)
return null;
var wsURl = obj[0]? ["webSocketDebuggerUrl"]?.Value<string> ();
Console.WriteLine (">>> {0}", wsURl);
var wsURl = obj[0]? ["webSocketDebuggerUrl"]?.Value<string> ();
Console.WriteLine (">>> {0}", wsURl);
return wsURl;
});
return wsURl;
});
} catch (Exception ex) {
Console.WriteLine ($"launch-chrome-and-connect failed with {ex.ToString ()}");
}
});
});
@@ -196,6 +201,11 @@ namespace WebAssembly.Net.Debugging {
Console.WriteLine($"Doing the nodejs: {options.NodeApp}");
var nodeFullPath = Path.GetFullPath (options.NodeApp);
Console.WriteLine (nodeFullPath);
var psi = new ProcessStartInfo ();
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.Arguments = $"--inspect-brk=localhost:0 {nodeFullPath}";
psi.FileName = "node";
+5 -5
View File
@@ -7,7 +7,7 @@
<PropertyGroup Label="Framework Version settings">
<FrameworkMajorVersion>0</FrameworkMajorVersion>
<FrameworkMinorVersion>2</FrameworkMinorVersion>
<FrameworkPatchVersion>2</FrameworkPatchVersion>
<FrameworkPatchVersion>3</FrameworkPatchVersion>
<FrameworkPreReleasePreviewNumber>1</FrameworkPreReleasePreviewNumber>
<FrameworkPreReleaseVersionLabel>preview$(FrameworkPreReleasePreviewNumber)</FrameworkPreReleaseVersionLabel>
<FrameworkPreReleaseBrandingLabel>Preview $(FrameworkPreReleasePreviewNumber)</FrameworkPreReleaseBrandingLabel>
@@ -19,7 +19,7 @@
<PropertyGroup Label="Bindings Version settings">
<BindingsMajorVersion>0</BindingsMajorVersion>
<BindingsMinorVersion>2</BindingsMinorVersion>
<BindingsPatchVersion>2</BindingsPatchVersion>
<BindingsPatchVersion>3</BindingsPatchVersion>
<BindingsPreReleasePreviewNumber>1</BindingsPreReleasePreviewNumber>
<BindingsPreReleaseVersionLabel>preview$(BindingsPreReleasePreviewNumber)</BindingsPreReleaseVersionLabel>
<BindingsPreReleaseBrandingLabel>Preview $(BindingsPreReleasePreviewNumber)</BindingsPreReleaseBrandingLabel>
@@ -31,7 +31,7 @@
<PropertyGroup Label="HttpHandler Version settings">
<HttpHandlerMajorVersion>0</HttpHandlerMajorVersion>
<HttpHandlerMinorVersion>2</HttpHandlerMinorVersion>
<HttpHandlerPatchVersion>2</HttpHandlerPatchVersion>
<HttpHandlerPatchVersion>3</HttpHandlerPatchVersion>
<HttpHandlerPreReleasePreviewNumber>1</HttpHandlerPreReleasePreviewNumber>
<HttpHandlerPreReleaseVersionLabel>preview$(HttpHandlerPreReleasePreviewNumber)</HttpHandlerPreReleaseVersionLabel>
<HttpHandlerPreReleaseBrandingLabel>Preview $(HttpHandlerPreReleasePreviewNumber)</HttpHandlerPreReleaseBrandingLabel>
@@ -43,7 +43,7 @@
<PropertyGroup Label="ClientWebSocket Version settings">
<ClientWebSocketMajorVersion>0</ClientWebSocketMajorVersion>
<ClientWebSocketMinorVersion>2</ClientWebSocketMinorVersion>
<ClientWebSocketPatchVersion>2</ClientWebSocketPatchVersion>
<ClientWebSocketPatchVersion>3</ClientWebSocketPatchVersion>
<ClientWebSocketPreReleasePreviewNumber>1</ClientWebSocketPreReleasePreviewNumber>
<ClientWebSocketPreReleaseVersionLabel>preview$(ClientWebSocketPreReleasePreviewNumber)</ClientWebSocketPreReleaseVersionLabel>
<ClientWebSocketPreReleaseBrandingLabel>Preview $(ClientWebSocketPreReleasePreviewNumber)</ClientWebSocketPreReleaseBrandingLabel>
@@ -55,7 +55,7 @@
<PropertyGroup Label="SDK Version settings">
<SDKPackageMajorVersion>0</SDKPackageMajorVersion>
<SDKPackageMinorVersion>2</SDKPackageMinorVersion>
<SDKPackagePatchVersion>2</SDKPackagePatchVersion>
<SDKPackagePatchVersion>3</SDKPackagePatchVersion>
<SDKPackagePreReleasePreviewNumber>1</SDKPackagePreReleasePreviewNumber>
<SDKPackagePreReleaseVersionLabel>preview$(SDKPackagePreReleasePreviewNumber)</SDKPackagePreReleaseVersionLabel>
<SDKPackagePreReleaseBrandingLabel>Preview $(SDKPackagePreReleasePreviewNumber)</SDKPackagePreReleaseBrandingLabel>
+1 -1
View File
@@ -20,7 +20,7 @@
},
init: function () {
this.int_add = Module.mono_bind_static_method ("[sample] DebuggerTests.ValueTypesTest:MethodWithLocalStructs");
this.int_add = Module.mono_bind_static_method ("[sample] SampleMath:IntAdd");
this.output = document.getElementById ("output");
this.button = document.getElementById ("button");
-150
View File
@@ -1,150 +0,0 @@
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;
int f = 0;
return e;
}
public static int UseComplex (int a, int b) {
var complex = new Simple.Complex (10, "xx");
int c = a + b;
int d = c + b;
int e = d + a;
int f = 0;
e += complex.DoStuff ();
return e;
}
delegate bool IsMathNull (Math m);
public static int DelegatesTest () {
Func<Math, bool> fn_func = (Math m) => m == null;
Func<Math, bool> fn_func_null = null;
Func<Math, bool>[] fn_func_arr = new Func<Math, bool>[] { (Math m) => m == null };
Math.IsMathNull fn_del = Math.IsMathNullDelegateTarget;
var fn_del_arr = new Math.IsMathNull[] { Math.IsMathNullDelegateTarget };
var m_obj = new Math ();
Math.IsMathNull fn_del_null = null;
bool res = fn_func (m_obj) && fn_del (m_obj) && fn_del_arr[0] (m_obj) && fn_del_null == null && fn_func_null == null && fn_func_arr[0] != null;
// Unused locals
Func<Math, bool> fn_func_unused = (Math m) => m == null;
Func<Math, bool> fn_func_null_unused = null;
Func<Math, bool>[] fn_func_arr_unused = new Func<Math, bool>[] { (Math m) => m == null };
Math.IsMathNull fn_del_unused = Math.IsMathNullDelegateTarget;
Math.IsMathNull fn_del_null_unused = null;
var fn_del_arr_unused = new Math.IsMathNull[] { Math.IsMathNullDelegateTarget };
Console.WriteLine ("Just a test message, ignore");
return res ? 0 : 1;
}
public static int GenericTypesTest () {
var list = new System.Collections.Generic.Dictionary<Math[], IsMathNull> ();
System.Collections.Generic.Dictionary<Math[], IsMathNull> list_null = null;
var list_arr = new System.Collections.Generic.Dictionary<Math[], IsMathNull>[] { new System.Collections.Generic.Dictionary<Math[], IsMathNull> () };
System.Collections.Generic.Dictionary<Math[], IsMathNull>[] list_arr_null = null;
Console.WriteLine ($"list_arr.Length: {list_arr.Length}, list.Count: {list.Count}");
// Unused locals
var list_unused = new System.Collections.Generic.Dictionary<Math[], IsMathNull> ();
System.Collections.Generic.Dictionary<Math[], IsMathNull> list_null_unused = null;
var list_arr_unused = new System.Collections.Generic.Dictionary<Math[], IsMathNull>[] { new System.Collections.Generic.Dictionary<Math[], IsMathNull> () };
System.Collections.Generic.Dictionary<Math[], IsMathNull>[] list_arr_null_unused = null;
Console.WriteLine ("Just a test message, ignore");
return 0;
}
static bool IsMathNullDelegateTarget (Math m) => m == null;
public static void OuterMethod ()
{
Console.WriteLine ($"OuterMethod called");
var nim = new Math.NestedInMath ();
var i = 5;
var text = "Hello";
var new_i = nim.InnerMethod (i);
Console.WriteLine ($"i: {i}");
Console.WriteLine ($"-- InnerMethod returned: {new_i}, nim: {nim}, text: {text}");
int k = 19;
new_i = InnerMethod2 ("test string", new_i, out k);
Console.WriteLine ($"-- InnerMethod2 returned: {new_i}, and k: {k}");
}
static int InnerMethod2 (string s, int i, out int k)
{
k = i + 10;
Console.WriteLine ($"s: {s}, i: {i}, k: {k}");
return i - 2;
}
class NestedInMath
{
public int InnerMethod (int i)
{
SimpleStructProperty = new SimpleStruct () { dt = new DateTime (2020, 1, 2, 3, 4, 5) };
int j = i + 10;
string foo_str = "foo";
Console.WriteLine ($"i: {i} and j: {j}, foo_str: {foo_str} ");
j += 9;
Console.WriteLine ($"i: {i} and j: {j}");
return j;
}
Math m = new Math ();
public async System.Threading.Tasks.Task<bool> AsyncMethod0 (string s, int i)
{
string local0 = "value0";
await System.Threading.Tasks.Task.Delay (1);
Console.WriteLine ($"* time for the second await, local0: {local0}");
await AsyncMethodNoReturn ();
return true;
}
public async System.Threading.Tasks.Task AsyncMethodNoReturn ()
{
var ss = new SimpleStruct () { dt = new DateTime (2020, 1, 2, 3, 4, 5) };
var ss_arr = new SimpleStruct [] {};
//ss.gs.StringField = "field in GenericStruct";
//Console.WriteLine ($"Using the struct: {ss.dt}, {ss.gs.StringField}, ss_arr: {ss_arr.Length}");
string str = "AsyncMethodNoReturn's local";
//Console.WriteLine ($"* field m: {m}");
await System.Threading.Tasks.Task.Delay (1);
Console.WriteLine ($"str: {str}");
}
public static async System.Threading.Tasks.Task<bool> AsyncTest (string s, int i)
{
var li = 10 + i;
var ls = s + "test";
return await new NestedInMath().AsyncMethod0 (s, i);
}
public SimpleStruct SimpleStructProperty { get; set; }
}
struct SimpleStruct
{
public DateTime dt;
public GenericStruct<DateTime> gs;
}
public struct GenericStruct<T>
{
public System.Collections.Generic.List<T> List;
public string StringField;
}
}
-18
View File
@@ -1,18 +0,0 @@
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; }
}
+12 -12
View File
@@ -1,13 +1,13 @@
# Getting Started with the sample
The goal of this doc is to get you setup with a workable WebAssembly SDK and run the sample.
The goal of this doc is to get you setup with a workable WebAssembly SDK and run the sample.
## Content
&nbsp;&nbsp;&nbsp;&nbsp;[Requirements](#requirements)
&nbsp;&nbsp;&nbsp;&nbsp;[Create sample](#create-sample)
&nbsp;&nbsp;&nbsp;&nbsp;[Serving sample](#serving-sample)
&nbsp;&nbsp;&nbsp;&nbsp;[Requirements](#requirements)
&nbsp;&nbsp;&nbsp;&nbsp;[Create sample](#create-sample)
&nbsp;&nbsp;&nbsp;&nbsp;[Serving sample](#serving-sample)
## Requirements
@@ -36,17 +36,17 @@ The WebAssembly SDK includes the sample code that we can use.
1. Compile sample
```
csc /target:library -out:sample.dll /noconfig /nostdlib /r:$WASM_SDK/wasm-bcl/wasm/mscorlib.dll /r:$WASM_SDK/wasm-bcl/wasm/System.dll /r:$WASM_SDK/wasm-bcl/wasm/System.Core.dll /r:$WASM_SDK/wasm-bcl/wasm/Facades/netstandard.dll /r:$WASM_SDK/wasm-bcl/wasm/System.Net.Http.dll /r:$WASM_SDK/framework/WebAssembly.Bindings.dll /r:$WASM_SDK/framework/WebAssembly.Net.Http.dll dependency.cs sample.cs
csc /target:library -out:sample.dll /noconfig /nostdlib /r:$WASM_SDK/wasm-bcl/wasm/mscorlib.dll /r:$WASM_SDK/wasm-bcl/wasm/System.dll /r:$WASM_SDK/wasm-bcl/wasm/System.Core.dll /r:$WASM_SDK/wasm-bcl/wasm/Facades/netstandard.dll /r:$WASM_SDK/wasm-bcl/wasm/System.Net.Http.dll /r:$WASM_SDK/framework/WebAssembly.Bindings.dll /r:$WASM_SDK/framework/System.Net.Http.WebAssemblyHttpHandler.dll dependency.cs sample.cs
```
1. Package and publish sample
1. Package and publish sample
```
mono $WASM_SDK/packager.exe --copy=always --out=./publish --asset=./sample.html --asset=server.py sample.dll
```
The `package` command will generate a `runtime.js` file that will properly load the runtime and call `App.Init` after that.
It will copy the required files such as the support libraries and assets.
@@ -54,8 +54,8 @@ You should now have the following directory structure
```
.
|--- my-app
|--- publish // Output from the `packager.exe` application
|--- my-app
|--- publish // Output from the `packager.exe` application
|--- managed // Where to find the managed assemblies generated by packager.exe
|--- mono-config.js // Configuration file referenced in `sample.html` and `runtime.js`
|--- dotnet.js // Mono WebAssembly implementations
@@ -89,9 +89,9 @@ publish$ python server.py
('python 3 serving at port', 8000)
```
From a browser got to `http://localhost:8000/sample.html` or `http://127.0.0.1:8000/sample.html` depending on the browser.
From a browser got to `http://localhost:8000/sample.html` or `http://127.0.0.1:8000/sample.html` depending on the browser.
Change the port number to what the server specifies.
Change the port number to what the server specifies.
+1 -1
View File
@@ -1,4 +1,4 @@
*.xml
*.json
!src/WebAssembly.Bindings/LinkDescriptor/*
!src/WebAssembly.Net.Http/LinkDescriptor/*
!src/System.Net.Http.WebAssemblyHttpHandler/LinkDescriptor/*
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
@@ -9,15 +9,15 @@
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<NoWarn>1701;1702;1591; 1570; 1572; 1573</NoWarn>
<OutputPath>..\..\</OutputPath>
<DocumentationFile>..\..\netstandard2.0\WebAssembly.Net.Http.xml</DocumentationFile>
<DocumentationFile>..\..\netstandard2.0\System.Net.Http.WebAssemblyHttpHandler.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<NoWarn>1701;1702;1591; 1570; 1572; 1573</NoWarn>
<OutputPath>..\..\</OutputPath>
<DocumentationFile>..\..\netstandard2.0\WebAssembly.Net.Http.xml</DocumentationFile>
<DocumentationFile>..\..\netstandard2.0\System.Net.Http.WebAssemblyHttpHandler.xml</DocumentationFile>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\WebAssembly.Bindings\WebAssembly.Bindings.csproj" />
</ItemGroup>
</Project>
</Project>
@@ -1,48 +1,34 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using WebAssembly;
using WebAssembly.Core;
using WebAssembly.Host;
namespace WebAssembly.Net.Http.HttpClient {
public class WasmHttpMessageHandler : HttpMessageHandler {
namespace System.Net.Http
{
/// <summary>
/// <see cref="WebAssemblyHttpHandler" /> is a specialty message handler based on the
/// Fetch API for use in WebAssembly environments.
/// </summary>
/// <remarks>See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API</remarks>
public class WebAssemblyHttpHandler : HttpMessageHandler {
static JSObject fetch;
static JSObject window;
/// <summary>
/// Gets or sets the default value of the 'credentials' option on outbound HTTP requests.
/// Defaults to <see cref="FetchCredentialsOption.SameOrigin"/>.
/// </summary>
public static FetchCredentialsOption DefaultCredentials { get; set; }
= FetchCredentialsOption.SameOrigin;
public static RequestCache Cache { get; set; }
= RequestCache.Default;
public static RequestMode Mode { get; set; }
= RequestMode.Cors;
/// <summary>
/// Gets whether the current Browser supports streaming responses
/// </summary>
public static bool StreamingSupported { get; }
private static bool StreamingSupported { get; }
/// <summary>
/// Gets or sets whether responses should be streamed if supported
/// </summary>
public static bool StreamingEnabled { get; set; } = false;
static WasmHttpMessageHandler ()
static WebAssemblyHttpHandler()
{
using (var streamingSupported = new Function ("return typeof Response !== 'undefined' && 'body' in Response.prototype && typeof ReadableStream === 'function'"))
StreamingSupported = (bool)streamingSupported.Call ();
}
public WasmHttpMessageHandler ()
public WebAssemblyHttpHandler()
{
handlerInit ();
}
@@ -72,20 +58,16 @@ namespace WebAssembly.Net.Http.HttpClient {
{
try {
var requestObject = new JSObject ();
if (request.Properties.TryGetValue("WebAssemblyFetchOptions", out var fetchOoptionsValue) &&
fetchOoptionsValue is IDictionary<string, object> fetchOptions) {
foreach (var item in fetchOptions) {
requestObject.SetObjectProperty(item.Key, item.Value);
}
}
requestObject.SetObjectProperty ("method", request.Method.Method);
// See https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials for
// standard values and meanings
requestObject.SetObjectProperty ("credentials", DefaultCredentials);
// See https://developer.mozilla.org/en-US/docs/Web/API/Request/cache for
// standard values and meanings
requestObject.SetObjectProperty ("cache", Cache);
// See https://developer.mozilla.org/en-US/docs/Web/API/Request/mode for
// standard values and meanings
requestObject.SetObjectProperty ("mode", Mode);
// We need to check for body content
if (request.Content != null) {
if (request.Content is StringContent) {
@@ -139,7 +121,7 @@ namespace WebAssembly.Net.Http.HttpClient {
wasmHttpReadStream?.Dispose ();
}));
var args = new Core.Array();
var args = new WebAssembly.Core.Array();
args.Push (request.RequestUri.ToString ());
args.Push (requestObject);
@@ -164,9 +146,11 @@ namespace WebAssembly.Net.Http.HttpClient {
HttpResponseMessage httpresponse = new HttpResponseMessage ((HttpStatusCode)Enum.Parse (typeof (HttpStatusCode), status.Status.ToString ()));
httpresponse.Content = StreamingSupported && StreamingEnabled
? new StreamContent (wasmHttpReadStream = new WasmHttpReadStream (status))
: (HttpContent)new WasmHttpContent (status);
var streamingEnabled = request.Properties.TryGetValue("WebAssemblyEnableStreamingResponse", out var streamingEnabledValue) && (bool)streamingEnabledValue;
httpresponse.Content = StreamingSupported && streamingEnabled
? new StreamContent (wasmHttpReadStream = new WasmHttpReadStream (status))
: (HttpContent)new WasmHttpContent (status);
// Fill the response headers
// CORS will only allow access to certain headers.
@@ -362,7 +346,7 @@ namespace WebAssembly.Net.Http.HttpClient {
return 0;
}
try {
try {
using (var body = _status.Body) {
_reader = (JSObject)body.Invoke ("getReader");
}
@@ -446,105 +430,4 @@ namespace WebAssembly.Net.Http.HttpClient {
}
}
}
/// <summary>
/// Specifies a value for the 'credentials' option on outbound HTTP requests.
/// </summary>
public enum FetchCredentialsOption {
/// <summary>
/// Advises the browser never to send credentials (such as cookies or HTTP auth headers).
/// </summary>
[Export (EnumValue = ConvertEnum.ToLower)]
Omit,
/// <summary>
/// Advises the browser to send credentials (such as cookies or HTTP auth headers)
/// only if the target URL is on the same origin as the calling application.
/// </summary>
[Export ("same-origin")]
SameOrigin,
/// <summary>
/// Advises the browser to send credentials (such as cookies or HTTP auth headers)
/// even for cross-origin requests.
/// </summary>
[Export (EnumValue = ConvertEnum.ToLower)]
Include,
}
/// <summary>
/// The cache mode of the request. It controls how the request will interact with the browser's HTTP cache.
/// </summary>
public enum RequestCache {
/// <summary>
/// The browser looks for a matching request in its HTTP cache.
/// </summary>
[Export (EnumValue = ConvertEnum.ToLower)]
Default,
/// <summary>
/// The browser fetches the resource from the remote server without first looking in the cache,
/// and will not update the cache with the downloaded resource.
/// </summary>
[Export ("no-store")]
NoStore,
/// <summary>
/// The browser fetches the resource from the remote server without first looking in the cache,
/// but then will update the cache with the downloaded resource.
/// </summary>
[Export (EnumValue = ConvertEnum.ToLower)]
Reload,
/// <summary>
/// The browser looks for a matching request in its HTTP cache.
/// </summary>
[Export ("no-cache")]
NoCache,
/// <summary>
/// The browser looks for a matching request in its HTTP cache.
/// </summary>
[Export ("force-cache")]
ForceCache,
/// <summary>
/// The browser looks for a matching request in its HTTP cache.
/// Mode can only be used if the request's mode is "same-origin"
/// </summary>
[Export ("only-if-cached")]
OnlyIfCached,
}
/// <summary>
/// The mode of the request. This is used to determine if cross-origin requests lead to valid responses
/// </summary>
public enum RequestMode {
/// <summary>
/// If a request is made to another origin with this mode set, the result is simply an error
/// </summary>
[Export ("same-origin")]
SameOrigin,
/// <summary>
/// Prevents the method from being anything other than HEAD, GET or POST, and the headers from
/// being anything other than simple headers.
/// </summary>
[Export ("no-cors")]
NoCors,
/// <summary>
/// Allows cross-origin requests, for example to access various APIs offered by 3rd party vendors.
/// </summary>
[Export (EnumValue = ConvertEnum.ToLower)]
Cors,
/// <summary>
/// A mode for supporting navigation.
/// </summary>
[Export (EnumValue = ConvertEnum.ToLower)]
Navigate,
}
}
@@ -1,13 +1,13 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26124.0
# Visual Studio Version 16
VisualStudioVersion = 16.0.29905.134
MinimumVisualStudioVersion = 15.0.26124.0
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAssembly.Bindings", "WebAssembly.Bindings\WebAssembly.Bindings.csproj", "{176A0D0C-41F0-4C2F-A440-617518A30032}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebAssembly.Bindings", "WebAssembly.Bindings\WebAssembly.Bindings.csproj", "{176A0D0C-41F0-4C2F-A440-617518A30032}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAssembly.Net.Http", "WebAssembly.Net.Http\WebAssembly.Net.Http.csproj", "{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebAssembly.Net.WebSockets", "WebAssembly.Net.WebSockets\WebAssembly.Net.WebSockets.csproj", "{D399ED16-6F8E-4D6D-BF44-434D5F2986D7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAssembly.Net.WebSockets", "WebAssembly.Net.WebSockets\WebAssembly.Net.WebSockets.csproj", "{D399ED16-6F8E-4D6D-BF44-434D5F2986D7}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Net.Http.WebAssemblyHttpHandler", "System.Net.Http.WebAssemblyHttpHandler\System.Net.Http.WebAssemblyHttpHandler.csproj", "{EDD5C733-081C-49E2-944F-588729543B74}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -18,9 +18,6 @@ Global
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{176A0D0C-41F0-4C2F-A440-617518A30032}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{176A0D0C-41F0-4C2F-A440-617518A30032}.Debug|Any CPU.Build.0 = Debug|Any CPU
@@ -34,18 +31,6 @@ Global
{176A0D0C-41F0-4C2F-A440-617518A30032}.Release|x64.Build.0 = Release|Any CPU
{176A0D0C-41F0-4C2F-A440-617518A30032}.Release|x86.ActiveCfg = Release|Any CPU
{176A0D0C-41F0-4C2F-A440-617518A30032}.Release|x86.Build.0 = Release|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Debug|x64.ActiveCfg = Debug|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Debug|x64.Build.0 = Debug|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Debug|x86.ActiveCfg = Debug|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Debug|x86.Build.0 = Debug|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Release|Any CPU.Build.0 = Release|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Release|x64.ActiveCfg = Release|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Release|x64.Build.0 = Release|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Release|x86.ActiveCfg = Release|Any CPU
{D721826B-CD18-4FBC-A3BC-7CDDEA41F3A2}.Release|x86.Build.0 = Release|Any CPU
{D399ED16-6F8E-4D6D-BF44-434D5F2986D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D399ED16-6F8E-4D6D-BF44-434D5F2986D7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D399ED16-6F8E-4D6D-BF44-434D5F2986D7}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -58,6 +43,24 @@ Global
{D399ED16-6F8E-4D6D-BF44-434D5F2986D7}.Release|x64.Build.0 = Release|Any CPU
{D399ED16-6F8E-4D6D-BF44-434D5F2986D7}.Release|x86.ActiveCfg = Release|Any CPU
{D399ED16-6F8E-4D6D-BF44-434D5F2986D7}.Release|x86.Build.0 = Release|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Debug|x64.ActiveCfg = Debug|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Debug|x64.Build.0 = Debug|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Debug|x86.ActiveCfg = Debug|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Debug|x86.Build.0 = Debug|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Release|Any CPU.Build.0 = Release|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Release|x64.ActiveCfg = Release|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Release|x64.Build.0 = Release|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Release|x86.ActiveCfg = Release|Any CPU
{EDD5C733-081C-49E2-944F-588729543B74}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {555E8AE4-1D6A-4DFE-A358-C8C54A93C6E3}
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
Policies = $0
+16
View File
@@ -0,0 +1,16 @@
function big_array_js_test (len) {
var big = new Array(len);
for (let i=0; i < len; i ++) {
big[i]=i + 1000;
}
console.log('break here');
};
function object_js_test () {
var obj = {
a_obj: { aa: 5, ab: 'foo' },
b_arr: [ 10, 12 ]
};
return obj;
};
+18
View File
@@ -0,0 +1,18 @@
# Instructions for running
Make sure that you have the latest Blazor WebAssembly version:
`dotnet new -i Microsoft.AspNetCore.Components.WebAssembly.Templates::3.2.0-preview2.20160.5`
## To run:
`.\download-packages.ps1 -runtime <blazor webassembly runtime> -url <url to download .zip of wasm build>`
-- or --
`.\download-packages.ps1 -runtime <blazor webassembly runtime> -filepath <filepath to wasm build>`
`download-packages.sh` is the bash equivalent.
@@ -0,0 +1,26 @@
param ($filepath, $url, $runtime)
$PACKAGE_PATH="~\\.nuget\\packages\\microsoft.aspnetcore.components.webassembly.runtime\\$runtime\\tools\\dotnetwasm"
if ($null -eq $filepath) {
Invoke-WebRequest -Uri $url -OutFile wasm-package.zip -UseBasicParsing
Expand-Archive wasm-package.zip
cd wasm-package
}
else {
cd $filepath
}
rm -r $PACKAGE_PATH\bcl
cp wasm-bcl $PACKAGE_PATH\bcl
rm -r $PACKAGE_PATH\framework
cp framework $PACKAGE_PATH\framework
rm -r $PACKAGE_PATH\wasm\*
cp builds\release\dotnet.$runtime.js $PACKAGE_PATH\wasm\
cp builds\release\dotnet.wasm $PACKAGE_PATH\wasm\
cd ..
rm wasm-package.zip
rm -r wasm-package
@@ -0,0 +1,45 @@
#!/bin/bash
while (("$#"));
do
key="${1}"
case ${key} in
-r|--runtime)
RUNTIME="$2"
shift 2
;;
-f|--filepath)
FILEPATH="$2"
shift 2
;;
-u|--url)
URL="$2"
shift 2
;;
*)
shift
;;
esac
done
PACKAGE_PATH=$HOME/.nuget/packages/microsoft.aspnetcore.components.webassembly.runtime/$RUNTIME/tools/dotnetwasm
if [ -z "$FILEPATH" ]
then
wget -O wasm-package.zip $URL
unzip wasm-package.zip -d wasm-package/
FILEPATH=wasm-package/
fi
rm -r $PACKAGE_PATH/bcl
cp $FILEPATH/wasm-bcl $PACKAGE_PATH/bcl
rm -r $PACKAGE_PATH/framework
cp $FILEPATH/framework $PACKAGE_PATH/framework
rm "$PACKAGE_PATH"/wasm/*
cp $FILEPATH/builds/release/dotnet.$RUNTIME.js $PACKAGE_PATH/wasm/
cp $FILEPATH/builds/release/dotnet.wasm $PACKAGE_PATH/wasm/
rm wasm-package.zip
rm -rf wasm-package
+19 -10
View File
@@ -62,7 +62,7 @@ class Driver {
const string BINDINGS_ASM_NAME = "WebAssembly.Bindings";
const string BINDINGS_RUNTIME_CLASS_NAME = "WebAssembly.Runtime";
const string HTTP_ASM_NAME = "WebAssembly.Net.Http";
const string HTTP_ASM_NAME = "System.Net.Http.WebAssemblyHttpHandler";
const string WEBSOCKETS_ASM_NAME = "WebAssembly.Net.WebSockets";
const string BINDINGS_MODULE = "corebindings.o";
const string BINDINGS_MODULE_SUPPORT = "$tool_prefix/src/binding_support.js";
@@ -252,7 +252,7 @@ class Driver {
foreach (var prefix in bcl_prefixes)
resolver.AddSearchDirectory (prefix);
resolver.AddSearchDirectory(bcl_facades_prefix);
resolver.AddSearchDirectory(framework_prefix);
resolver.AddSearchDirectory(framework_prefix);
rp.AssemblyResolver = resolver;
rp.InMemory = true;
@@ -341,7 +341,7 @@ class Driver {
{
Default,
Always,
IfNewer
IfNewer
}
enum ExecMode {
@@ -353,7 +353,7 @@ class Driver {
enum LinkMode
{
SdkOnly,
All
All
}
class WasmOptions {
@@ -371,6 +371,7 @@ class Driver {
public bool Simd;
public bool EnableDynamicRuntime;
public bool LinkerExcludeDeserialization;
public bool EnableCollation;
}
int Run (string[] args) {
@@ -432,7 +433,8 @@ class Driver {
NativeStrip = true,
Simd = false,
EnableDynamicRuntime = false,
LinkerExcludeDeserialization = true
LinkerExcludeDeserialization = true,
EnableCollation = false
};
var p = new OptionSet () {
@@ -480,6 +482,7 @@ class Driver {
AddFlag (p, new BoolFlag ("native-strip", "strip final executable", opts.NativeStrip, b => opts.NativeStrip = b));
AddFlag (p, new BoolFlag ("simd", "enable SIMD support", opts.Simd, b => opts.Simd = b));
AddFlag (p, new BoolFlag ("linker-exclude-deserialization", "Link out .NET deserialization support", opts.LinkerExcludeDeserialization, b => opts.LinkerExcludeDeserialization = b));
AddFlag (p, new BoolFlag ("collation", "enable unicode collation support", opts.EnableCollation, b => opts.EnableCollation = b));
var new_args = p.Parse (args).ToArray ();
foreach (var a in new_args) {
@@ -740,7 +743,7 @@ class Driver {
}
foreach(var asset in assets) {
CopyFile (asset,
CopyFile (asset,
Path.Combine (out_prefix, Path.GetFileName (asset)), copyType, "Asset: ");
}
}
@@ -908,7 +911,7 @@ class Driver {
ninja.WriteLine ($" command = bash -c '$emcc $emcc_flags {emcc_link_flags} -o $out_js --js-library $tool_prefix/src/library_mono.js --js-library $tool_prefix/src/dotnet_support.js {wasm_core_support_library} $in' {strip_cmd}");
ninja.WriteLine (" description = [EMCC-LINK] $in -> $out_js");
ninja.WriteLine ("rule linker");
ninja.WriteLine (" command = mono $tools_dir/monolinker.exe -out $builddir/linker-out -l none --deterministic --disable-opt unreachablebodies --exclude-feature com --exclude-feature remoting --exclude-feature etw $linker_args || exit 1; mono $tools_dir/wasm-tuner.exe --gen-empty-assemblies $out");
ninja.WriteLine (" command = mono $tools_dir/monolinker.exe -out $builddir/linker-out -l none --deterministic --disable-opt unreachablebodies --exclude-feature com,remoting,etw $linker_args || exit 1; mono $tools_dir/wasm-tuner.exe --gen-empty-assemblies $out");
ninja.WriteLine (" description = [IL-LINK]");
ninja.WriteLine ("rule aot-instances-dll");
ninja.WriteLine (" command = echo > aot-instances.cs; csc /deterministic /out:$out /target:library aot-instances.cs");
@@ -973,8 +976,10 @@ class Driver {
if (enable_aot)
ninja.WriteLine ("build $builddir/aot-in: mkdir");
{
var source_file = Path.GetFullPath (Path.Combine (tool_prefix, "src", "linker-subs.xml"));
ninja.WriteLine ($"build $builddir/linker-subs.xml: cpifdiff {source_file}");
foreach (var file in new string[] { "linker-subs.xml", "linker-disable-collation.xml" }) {
var source_file = Path.GetFullPath (Path.Combine (tool_prefix, "src", file));
ninja.WriteLine ($"build $builddir/{file}: cpifdiff {source_file}");
}
}
var ofiles = "";
var bc_files = "";
@@ -1125,6 +1130,10 @@ class Driver {
linker_infiles += "| linker-subs.xml";
if (opts.LinkerExcludeDeserialization)
linker_args += "--exclude-feature deserialization ";
if (!opts.EnableCollation) {
linker_args += "--substitutions linker-disable-collation.xml ";
linker_infiles += " linker-disable-collation.xml";
}
if (!string.IsNullOrEmpty (linkDescriptor)) {
linker_args += $"-x {linkDescriptor} ";
foreach (var assembly in root_assemblies) {
@@ -1178,7 +1187,7 @@ class Driver {
{
var srcInfo = new FileInfo (sourceFileName);
var dstInfo = new FileInfo (destFileName);
if (srcInfo.LastWriteTime.Ticks > dstInfo.LastWriteTime.Ticks || srcInfo.Length > dstInfo.Length)
File.Copy(sourceFileName, destFileName, true);
else
+7 -2
View File
@@ -3,9 +3,8 @@ using System.Linq;
using System.Net.Http;
using System.Reflection;
using WebAssembly;
using WebAssembly.Net.Http.HttpClient;
public class Math {
public class SampleMath {
public static int IntAdd (int a, int b) {
var cp = new Simple.Complex (10, "hello");
int c = a + b;
@@ -21,6 +20,12 @@ public class Math {
public int First (int[] x) {
return x.FirstOrDefault ();
}
public static void Run ()
{
DebuggerTests.EntryClass.run ();
}
}
namespace GeoLocation
@@ -111,7 +111,7 @@ namespace Mono.WebAssembly.Build
return base.ValidateParameters ();
}
static List<string> bindingNames = new List<string> {"WebAssembly.Bindings","WebAssembly.Net.Http","WebAssembly.Net.WebSockets"};
static List<string> bindingNames = new List<string> {"WebAssembly.Bindings","System.Net.Http.WebAssemblyHttpHandler","WebAssembly.Net.WebSockets"};
protected override string GenerateCommandLineCommands ()
{
@@ -256,7 +256,7 @@ namespace Mono.WebAssembly.Build
if (!File.Exists(toolsPath))
toolsPath = Path.GetFullPath(Path.Combine (GetParentDirectoryOf(dir,6), "out", "wasm-bcl", "wasm_tools", "monolinker.exe"));
return toolsPath;
}
}
static string GetParentDirectoryOf (string path, int up)
{
@@ -29,7 +29,7 @@
<PackageReference Include="Mono.WebAssembly.Framework" VersionOverride="$(_MonoWasmFrameworkPackageVersion)" Condition="'$(MonoWasmFrameworkPath)'=='' Or '$(_MonoWasmFrameworkFromPackage)'=='True'" />
<PackageReference Include="Mono.WebAssembly.Runtime" VersionOverride="$(_MonoWasmRuntimePackageVersion)" Condition="'$(MonoWasmRuntimePath)'=='' Or '$(_MonoWasmRuntimeFromPackage)'=='True'" />
<PackageReference Include="WebAssembly.Bindings" VersionOverride="$(_MonoWasmBindingsPackageVersion)" Condition="'$(MonoWasmBindingsPath)'=='' And '$(DisableImplicitWasmBindingReferences)' != 'True'" />
<PackageReference Include="WebAssembly.Net.Http" VersionOverride="$(_MonoWasmHttpHandlerPackageVersion)" Condition="'$(MonoWasmBindingsPath)'=='' And '$(DisableImplicitWasmBindingReferences)' != 'True'" />
<PackageReference Include="System.Net.Http.WebAssemblyHttpHandler" VersionOverride="$(_MonoWasmHttpHandlerPackageVersion)" Condition="'$(MonoWasmBindingsPath)'=='' And '$(DisableImplicitWasmBindingReferences)' != 'True'" />
<PackageReference Include="WebAssembly.Net.WebSockets" VersionOverride="$(_MonoWasmClientWebSocketPackageVersion)" Condition="'$(MonoWasmBindingsPath)'=='' And '$(DisableImplicitWasmBindingReferences)' != 'True'" />
</ItemGroup>
@@ -38,13 +38,13 @@
<PackageReference Include="Mono.WebAssembly.Framework" Version="$(_MonoWasmFrameworkPackageVersion)" Condition="'$(MonoWasmFrameworkPath)'=='' Or '$(_MonoWasmFrameworkFromPackage)'=='True'" />
<PackageReference Include="Mono.WebAssembly.Runtime" Version="$(_MonoWasmRuntimePackageVersion)" Condition="'$(MonoWasmRuntimePath)'=='' Or '$(_MonoWasmRuntimeFromPackage)'=='True'" />
<PackageReference Include="WebAssembly.Bindings" Version="[$(_MonoWasmBindingsPackageVersion)]" Condition="'$(MonoWasmBindingsPath)'=='' And '$(DisableImplicitWasmBindingReferences)' != 'True'" />
<PackageReference Include="WebAssembly.Net.Http" Version="[$(_MonoWasmHttpHandlerPackageVersion)]" Condition="'$(MonoWasmBindingsPath)'=='' And '$(DisableImplicitWasmBindingReferences)' != 'True'" />
<PackageReference Include="System.Net.Http.WebAssemblyHttpHandler" Version="[$(_MonoWasmHttpHandlerPackageVersion)]" Condition="'$(MonoWasmBindingsPath)'=='' And '$(DisableImplicitWasmBindingReferences)' != 'True'" />
<PackageReference Include="WebAssembly.Net.WebSockets" Version="[$(_MonoWasmClientWebSocketPackageVersion)]" Condition="'$(MonoWasmBindingsPath)'=='' And '$(DisableImplicitWasmBindingReferences)' != 'True'" />
</ItemGroup>
<ItemGroup Condition="'$(MonoWasmBindingsPath)' != '' And '$(DisableImplicitWasmBindingReferences)' != 'True'">
<Reference Include="$(MonoWasmBindingsPath)WebAssembly.Bindings.dll" />
<Reference Include="$(MonoWasmBindingsPath)WebAssembly.Net.Http.dll" />
<Reference Include="$(MonoWasmBindingsPath)System.Net.Http.WebAssemblyHttpHandler.dll" />
<Reference Include="$(MonoWasmBindingsPath)WebAssembly.Net.WebSockets.dll" />
</ItemGroup>
@@ -5,7 +5,7 @@
"MonoWasmFrameworkPath": "Overrides the path to the Mono WebAssembly framework assemblies.",
"MonoWasmRuntimePath": "Overrides the path to the Mono WebAssembly runtime.",
"MonoWasmTargetsPath": "Overrides the path to the Mono WebAssembly build targets.",
"MonoWasmBindingsPath": "Overrides the path to the Mono WebAssembly binding assemblies (WebAssembly.Bindings and WebAssembly.Net.Http).",
"DisableImplicitWasmBindingReferences": "Whether to omit references to the WebAssembly binding assemblies (WebAssembly.Bindings and WebAssembly.Net.Http)"
"MonoWasmBindingsPath": "Overrides the path to the Mono WebAssembly binding assemblies (WebAssembly.Bindings and System.Net.Http.WebAssemblyHttpHandler).",
"DisableImplicitWasmBindingReferences": "Whether to omit references to the WebAssembly binding assemblies (WebAssembly.Bindings and System.Net.Http.WebAssemblyHttpHandler)"
}
}
@@ -3,11 +3,11 @@
-->
<Project>
<PropertyGroup>
<_MonoWasmBuildPackageVersion>0.2.2</_MonoWasmBuildPackageVersion>
<_MonoWasmFrameworkPackageVersion>0.2.2</_MonoWasmFrameworkPackageVersion>
<_MonoWasmRuntimePackageVersion>0.2.2</_MonoWasmRuntimePackageVersion>
<_MonoWasmBindingsPackageVersion>0.2.2</_MonoWasmBindingsPackageVersion>
<_MonoWasmHttpHandlerPackageVersion>0.2.2</_MonoWasmHttpHandlerPackageVersion>
<_MonoWasmClientWebSocketPackageVersion>0.2.2</_MonoWasmClientWebSocketPackageVersion>
<_MonoWasmBuildPackageVersion>0.2.3</_MonoWasmBuildPackageVersion>
<_MonoWasmFrameworkPackageVersion>0.2.3</_MonoWasmFrameworkPackageVersion>
<_MonoWasmRuntimePackageVersion>0.2.3</_MonoWasmRuntimePackageVersion>
<_MonoWasmBindingsPackageVersion>0.2.3</_MonoWasmBindingsPackageVersion>
<_MonoWasmHttpHandlerPackageVersion>0.2.3</_MonoWasmHttpHandlerPackageVersion>
<_MonoWasmClientWebSocketPackageVersion>0.2.3</_MonoWasmClientWebSocketPackageVersion>
</PropertyGroup>
</Project>
+1 -1
View File
@@ -21,7 +21,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.WebAssembly.SdkTests",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.WebAssembly.Runtime", "Mono.WebAssembly.Runtime.Framework\Mono.WebAssembly.Runtime.csproj", "{7DD2FF9E-D36E-417D-806F-899087BE9C54}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAssembly.Net.Http", "WebAssembly.Net.Http.Framework\WebAssembly.Net.Http.csproj", "{F905CB2B-2EC2-4375-AC10-07F98E27822D}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http.WebAssemblyHttpHandler", "System.Net.Http.WebAssemblyHttpHandler.Framework\System.Net.Http.WebAssemblyHttpHandler.csproj", "{F905CB2B-2EC2-4375-AC10-07F98E27822D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAssembly.Bindings", "WebAssembly.Bindings.Framework\WebAssembly.Bindings.csproj", "{B8FDEB6F-F3CF-4C39-9275-C47CC1D34F22}"
EndProject
+1 -1
View File
@@ -19,7 +19,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{EBC911EF
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mono.WebAssembly.Runtime", "Mono.WebAssembly.Runtime.Framework\Mono.WebAssembly.Runtime.csproj", "{7DD2FF9E-D36E-417D-806F-899087BE9C54}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAssembly.Net.Http", "WebAssembly.Net.Http.Framework\WebAssembly.Net.Http.csproj", "{F905CB2B-2EC2-4375-AC10-07F98E27822D}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http.WebAssemblyHttpHandler", "System.Net.Http.WebAssemblyHttpHandler.Framework\System.Net.Http.WebAssemblyHttpHandler.csproj", "{F905CB2B-2EC2-4375-AC10-07F98E27822D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebAssembly.Bindings", "WebAssembly.Bindings.Framework\WebAssembly.Bindings.csproj", "{B8FDEB6F-F3CF-4C39-9275-C47CC1D34F22}"
EndProject
@@ -7,9 +7,9 @@
<NoPackageAnalysis>true</NoPackageAnalysis>
</PropertyGroup>
<ItemGroup>
<None Include="..\..\..\wasm\framework\WebAssembly.Net.Http.dll" PackagePath="lib\netstandard2.0\%(Filename)%(Extension)" Pack="True" />
<None Include="..\..\..\wasm\framework\WebAssembly.Net.Http.pdb" PackagePath="lib\netstandard2.0\%(Filename)%(Extension)" Pack="True" />
<None Include="..\..\..\wasm\framework\WebAssembly.Net.Http.xml" PackagePath="lib\netstandard2.0\%(Filename)%(Extension)" Pack="True" />
<None Include="..\..\..\wasm\framework\System.Net.Http.WebAssemblyHttpHandler.dll" PackagePath="lib\netstandard2.0\%(Filename)%(Extension)" Pack="True" />
<None Include="..\..\..\wasm\framework\System.Net.Http.WebAssemblyHttpHandler.pdb" PackagePath="lib\netstandard2.0\%(Filename)%(Extension)" Pack="True" />
<None Include="..\..\..\wasm\framework\System.Net.Http.WebAssemblyHttpHandler.xml" PackagePath="lib\netstandard2.0\%(Filename)%(Extension)" Pack="True" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WebAssembly.Bindings.Framework\WebAssembly.Bindings.csproj" />
@@ -1,5 +1,5 @@
{
"msbuild-sdks": {
"Mono.WebAssembly.Sdk": "0.2.2"
"Mono.WebAssembly.Sdk": "0.2.3"
}
}
+16 -10
View File
@@ -31,7 +31,7 @@ void core_initialize_internals ();
extern void* mono_wasm_invoke_js_marshalled (MonoString **exceptionMessage, void *asyncHandleLongPtr, MonoString *funcName, MonoString *argsJson);
extern void* mono_wasm_invoke_js_unmarshalled (MonoString **exceptionMessage, MonoString *funcName, void* arg0, void* arg1, void* arg2);
void mono_wasm_enable_debugging (void);
void mono_wasm_enable_debugging (int);
void mono_ee_interp_init (const char *opts);
void mono_marshal_ilgen_init (void);
@@ -313,6 +313,7 @@ icall_table_lookup_symbol (void *func)
void mono_initialize_internals ()
{
mono_add_internal_call ("WebAssembly.Runtime::InvokeJS", mono_wasm_invoke_js);
// TODO: what happens when two types in different assemblies have the same FQN?
// Blazor specific custom routines - see dotnet_support.js for backing code
mono_add_internal_call ("WebAssembly.JSInterop.InternalCalls::InvokeJSMarshalled", mono_wasm_invoke_js_marshalled);
@@ -327,6 +328,8 @@ void mono_initialize_internals ()
EMSCRIPTEN_KEEPALIVE void
mono_wasm_load_runtime (const char *managed_path, int enable_debugging)
{
const char *interp_opts = "";
monoeg_g_setenv ("MONO_LOG_LEVEL", "debug", 0);
monoeg_g_setenv ("MONO_LOG_MASK", "gc", 0);
#ifdef ENABLE_NETCORE
@@ -347,8 +350,11 @@ mono_wasm_load_runtime (const char *managed_path, int enable_debugging)
#endif
#else
mono_jit_set_aot_mode (MONO_AOT_MODE_INTERP_LLVMONLY);
if (enable_debugging)
mono_wasm_enable_debugging ();
if (enable_debugging) {
// Disable optimizations which interfere with debugging
interp_opts = "-all";
mono_wasm_enable_debugging (enable_debugging);
}
#endif
#ifdef LINK_ICALLS
@@ -366,7 +372,7 @@ mono_wasm_load_runtime (const char *managed_path, int enable_debugging)
mono_icall_table_init ();
#endif
#ifdef NEED_INTERP
mono_ee_interp_init ("");
mono_ee_interp_init (interp_opts);
mono_marshal_ilgen_init ();
mono_method_builder_ilgen_init ();
mono_sgen_mono_ilgen_init ();
@@ -735,12 +741,12 @@ mono_wasm_enable_on_demand_gc (void)
}
// Returns the local timezone default is UTC.
EM_JS(size_t, mono_wasm_timezone_get_local_name, (),
EM_JS(size_t, mono_wasm_timezone_get_local_name, (),
{
var res = "UTC";
try {
res = Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch(e) {}
try {
res = Intl.DateTimeFormat().resolvedOptions().timeZone;
} catch(e) {}
var buff = Module._malloc((res.length + 1) * 2);
stringToUTF16 (res, buff, (res.length + 1) * 2);
@@ -748,12 +754,12 @@ EM_JS(size_t, mono_wasm_timezone_get_local_name, (),
})
void
mono_timezone_get_local_name (MonoString *result)
mono_timezone_get_local_name (MonoString **result)
{
// WASM returns back an int pointer to a string UTF16 buffer.
// We then cast to `mono_unichar2*`. Returning `mono_unichar2*` from the JavaScript call will
// result in cast warnings from the compiler.
mono_unichar2 *tzd_local_name = (mono_unichar2*)mono_wasm_timezone_get_local_name ();
result = mono_string_from_utf16 (tzd_local_name);
*result = mono_string_from_utf16 (tzd_local_name);
free (tzd_local_name);
}
+410 -78
View File
@@ -87,27 +87,28 @@ var MonoSupportLib = {
_fixup_name_value_objects: function (var_list) {
var out_list = [];
var _fixup_value = function (value) {
if (value != null && value != undefined) {
var descr = value.description;
if (descr == null || descr == undefined)
value.description = '' + value.value;
}
return value;
};
var i = 0;
while (i < var_list.length) {
var o = var_list [i];
var name = o.name;
if (name == null || name == undefined) {
i ++;
o.value = _fixup_value(o.value);
out_list.push (o);
continue;
}
if (i + 1 < var_list.length) {
var value = var_list [i+1].value;
if (value != null && value != undefined) {
var descr = value.description;
if (descr == null || descr == undefined)
value.description = '' + value.value;
o.value = value;
}
}
if (i + 1 < var_list.length)
o.value = _fixup_value(var_list[i + 1].value);
out_list.push (o);
i += 2;
@@ -169,6 +170,7 @@ var MonoSupportLib = {
}
}
this._post_process_details(res);
this.var_info = []
return res;
@@ -197,7 +199,6 @@ var MonoSupportLib = {
this.mono_wasm_get_array_values_info = Module.cwrap ("mono_wasm_get_array_values", null, [ 'number' ]);
this.var_info = [];
console.log (">> mono_wasm_get_array_values " + objId);
this.mono_wasm_get_array_values_info (objId);
var res = MONO._fixup_name_value_objects (this.var_info);
@@ -228,11 +229,224 @@ var MonoSupportLib = {
return res;
},
_post_process_details: function (details) {
if (details == undefined)
return {};
if (details.length > 0)
this._extract_and_cache_value_types(details);
return details;
},
_next_value_type_id: function () {
return ++this._next_value_type_id_var;
},
_extract_and_cache_value_types: function (var_list) {
if (var_list == undefined || !Array.isArray (var_list) || var_list.length == 0)
return var_list;
for (let i in var_list) {
var value = var_list [i].value;
if (value == undefined || value.type != "object")
continue;
if (value.isValueType != true || value.expanded != true) // undefined would also give us false
continue;
var objectId = value.objectId;
if (objectId == undefined)
objectId = `dotnet:valuetype:${this._next_value_type_id ()}`;
value.objectId = objectId;
this._extract_and_cache_value_types (value.members);
this._value_types_cache [objectId] = value.members;
delete value.members;
}
return var_list;
},
_get_details_for_value_type: function (objectId, fetchDetailsFn) {
if (objectId in this._value_types_cache)
return this._value_types_cache[objectId];
this._post_process_details (fetchDetailsFn());
if (objectId in this._value_types_cache)
return this._value_types_cache[objectId];
// return error
throw new Error (`Could not get details for ${objectId}`);
},
_is_object_id_array: function (objectId) {
// Keep this in sync with `_get_array_details`
return (objectId.startsWith ('dotnet:array:') && objectId.split (':').length == 3);
},
_get_array_details: function (objectId, objectIdParts) {
// Keep this in sync with `_is_object_id_array`
switch (objectIdParts.length) {
case 3:
return this._post_process_details (this.mono_wasm_get_array_values(objectIdParts[2]));
case 4:
var arrayObjectId = objectIdParts[2];
var arrayIdx = objectIdParts[3];
return this._get_details_for_value_type(
objectId, () => this.mono_wasm_get_array_value_expanded(arrayObjectId, arrayIdx));
default:
throw new Error (`object id format not supported : ${objectId}`);
}
},
mono_wasm_get_details: function (objectId, args) {
var parts = objectId.split(":");
if (parts[0] != "dotnet")
throw new Error ("Can't handle non-dotnet object ids. ObjectId: " + objectId);
switch (parts[1]) {
case "object":
if (parts.length != 3)
throw new Error(`exception this time: Invalid object id format: ${objectId}`);
return this._post_process_details(this.mono_wasm_get_object_properties(parts[2], false));
case "array":
return this._get_array_details(objectId, parts);
case "valuetype":
if (parts.length != 3 && parts.length != 4) {
// dotnet:valuetype:vtid
// dotnet:valuetype:containerObjectId:vtId
throw new Error(`Invalid object id format: ${objectId}`);
}
var containerObjectId = parts[2];
return this._get_details_for_value_type(objectId, () => this.mono_wasm_get_object_properties(containerObjectId, true));
case "cfo_res": {
if (!(objectId in this._call_function_res_cache))
throw new Error(`Could not find any object with id ${objectId}`);
var real_obj = this._call_function_res_cache [objectId];
if (args.accessorPropertiesOnly) {
// var val_accessors = JSON.stringify ([
// {
// name: "__proto__",
// get: { type: "function", className: "Function", description: "function get __proto__ () {}", objectId: "dotnet:cfo_res:9999" },
// set: { type: "function", className: "Function", description: "function set __proto__ () {}", objectId: "dotnet:cfo_res:8888" },
// isOwn: false
// }], undefined, 4);
return { __value_as_json_string__: "[]" };
}
// behaving as if (args.ownProperties == true)
var descriptors = Object.getOwnPropertyDescriptors (real_obj);
var own_properties = [];
Object.keys (descriptors).forEach (k => {
var new_obj;
var prop_desc = descriptors [k];
if (typeof prop_desc.value == "object") {
// convert `{value: { type='object', ... }}`
// to `{ name: 'foo', value: { type='object', ... }}
new_obj = Object.assign ({ name: k}, prop_desc);
} else {
// This is needed for values that were not added by us,
// thus are like { value: 5 }
// instead of { value: { type = 'number', value: 5 }}
//
// This can happen, for eg., when `length` gets added for arrays
// or `__proto__`.
new_obj = {
name: k,
// merge/add `type` and `description` to `d.value`
value: Object.assign ({ type: (typeof prop_desc.value), description: '' + prop_desc.value },
prop_desc)
};
}
own_properties.push (new_obj);
});
return { __value_as_json_string__: JSON.stringify (own_properties) };
}
default:
throw new Error(`Unknown object id format: ${objectId}`);
}
},
_cache_call_function_res: function (obj) {
var id = `dotnet:cfo_res:${this._next_call_function_res_id++}`;
this._call_function_res_cache[id] = obj;
return id;
},
mono_wasm_release_object: function (objectId) {
if (objectId in this._cache_call_function_res)
delete this._cache_call_function_res[objectId];
},
mono_wasm_call_function_on: function (request) {
var objId = request.objectId;
var proxy;
if (objId in this._call_function_res_cache) {
proxy = this._call_function_res_cache [objId];
} else if (!objId.startsWith ('dotnet:cfo_res:')) {
var details = this.mono_wasm_get_details(objId);
var target_is_array = this._is_object_id_array (objId);
proxy = target_is_array ? [] : {};
Object.keys(details).forEach(p => {
var prop = details[p];
if (target_is_array) {
proxy.push(prop.value);
} else {
if (prop.name != undefined)
proxy [prop.name] = prop.value;
else // when can this happen??
proxy[''+p] = prop.value;
}
});
}
var fn_args = request.arguments != undefined ? request.arguments.map(a => a.value) : [];
var fn_eval_str = `var fn = ${request.functionDeclaration}; fn.call (proxy, ...[${fn_args}]);`;
var fn_res = eval (fn_eval_str);
if (request.returnByValue)
return fn_res;
if (fn_res == undefined)
throw Error ('Function returned undefined result');
var fn_res_id = this._cache_call_function_res (fn_res);
if (Object.getPrototypeOf (fn_res) == Array.prototype) {
return {
type: "object",
subtype: "array",
className: "Array",
description: `Array(${fn_res.length})`,
objectId: fn_res_id
};
} else {
return { type: "object", className: "Object", description: "Object", objectId: fn_res_id };
}
},
mono_wasm_start_single_stepping: function (kind) {
console.log (">> mono_wasm_start_single_stepping " + kind);
if (!this.mono_wasm_setup_single_step)
this.mono_wasm_setup_single_step = Module.cwrap ("mono_wasm_setup_single_step", 'number', [ 'number']);
this._next_value_type_id_var = 0;
this._value_types_cache = {};
return this.mono_wasm_setup_single_step (kind);
},
@@ -240,6 +454,13 @@ var MonoSupportLib = {
this.mono_wasm_runtime_is_ready = true;
// DO NOT REMOVE - magic debugger init function
console.debug ("mono_wasm_runtime_ready", "fe00e07a-5519-4dfe-b35a-f867dbaf2e28");
this._next_value_type_id_var = 0;
this._value_types_cache = {};
// FIXME: where should this go?
this._next_call_function_res_id = 0;
this._call_function_res_cache = {};
},
mono_wasm_set_breakpoint: function (assembly, method_token, il_offset) {
@@ -375,7 +596,7 @@ var MonoSupportLib = {
heapBytes.set (asm);
mono_wasm_add_assembly (file_name, memory, asm.length);
console.log ("MONO_WASM: Loaded: " + file_name);
//console.log ("MONO_WASM: Loaded: " + file_name);
--pending;
if (pending == 0) {
MONO.loaded_files = loaded_files;
@@ -432,30 +653,133 @@ var MonoSupportLib = {
}});
},
_mono_wasm_add_string_var: function(var_value) {
if (var_value == 0) {
MONO.mono_wasm_add_null_var ("string");
return;
}
MONO.var_info.push({
value: {
type: "string",
value: var_value,
}
});
},
_mono_wasm_add_getter_var: function(className) {
fixed_class_name = MONO._mono_csharp_fixup_class_name (className);
var value = `${fixed_class_name} { get; }`;
MONO.var_info.push({
value: {
type: "symbol",
value: value,
description: value
}
});
},
_mono_wasm_add_array_var: function(className, objectId, length) {
fixed_class_name = MONO._mono_csharp_fixup_class_name(className);
if (objectId == 0) {
MONO.mono_wasm_add_null_var (fixed_class_name);
return;
}
MONO.var_info.push({
value: {
type: "object",
subtype: "array",
className: fixed_class_name,
description: `${fixed_class_name}(${length})`,
objectId: "dotnet:array:"+ objectId,
}
});
},
mono_wasm_add_typed_value: function (type, str_value, value) {
var type_str = type;
if (typeof type != 'string')
type_str = Module.UTF8ToString (type);
if (typeof str_value != 'string')
str_value = Module.UTF8ToString (str_value);
switch (type_str) {
case "bool":
MONO.var_info.push ({
value: {
type: "boolean",
value: value != 0
}
});
break;
case "char":
MONO.var_info.push ({
value: {
type: "symbol",
value: `${value} '${String.fromCharCode (value)}'`
}
});
break;
case "number":
MONO.var_info.push ({
value: {
type: "number",
value: value
}
});
break;
case "string":
MONO._mono_wasm_add_string_var (str_value);
break;
case "getter":
MONO._mono_wasm_add_getter_var (str_value);
break;
case "array":
MONO._mono_wasm_add_array_var (str_value, value.objectId, value.length);
break;
case "pointer": {
MONO.var_info.push ({
value: {
type: "symbol",
value: str_value,
description: str_value
}
});
}
break;
default: {
var msg = `'${str_value}' ${value}`;
MONO.var_info.push ({
value: {
type: "symbol",
value: msg,
description: msg
}
});
break;
}
}
},
_mono_csharp_fixup_class_name: function(className)
{
// Fix up generic names like Foo`2<int, string> to Foo<int, string>
// and nested class names like Foo/Bar to Foo.Bar
return className.replace('/', '.').replace(/`\d+/, '');
return className.replace(/\//g, '.').replace(/`\d+/g, '');
},
},
mono_wasm_add_bool_var: function(var_value) {
MONO.var_info.push({
value: {
type: "boolean",
value: var_value != 0,
}
});
},
mono_wasm_add_number_var: function(var_value) {
MONO.var_info.push({
value: {
type: "number",
value: var_value,
}
});
mono_wasm_add_typed_value: function (type, str_value, value) {
MONO.mono_wasm_add_typed_value (type, str_value, value);
},
mono_wasm_add_properties_var: function(name, field_offset) {
@@ -469,13 +793,13 @@ var MonoSupportLib = {
MONO._async_method_objectId = objectId;
},
mono_wasm_begin_value_type_var: function(className) {
mono_wasm_begin_value_type_var: function(className, toString) {
fixed_class_name = MONO._mono_csharp_fixup_class_name(Module.UTF8ToString (className));
var vt_obj = {
value: {
type: "object",
className: fixed_class_name,
description: fixed_class_name,
description: (toString == 0 ? fixed_class_name : Module.UTF8ToString (toString)),
// objectId will be generated by MonoProxy
expanded: true,
isValueType: true,
@@ -504,13 +828,13 @@ var MonoSupportLib = {
}
},
mono_wasm_add_value_type_unexpanded_var: function (className) {
mono_wasm_add_value_type_unexpanded_var: function (className, toString) {
fixed_class_name = MONO._mono_csharp_fixup_class_name(Module.UTF8ToString (className));
MONO.var_info.push({
value: {
type: "object",
className: fixed_class_name,
description: fixed_class_name,
description: (toString == 0 ? fixed_class_name : Module.UTF8ToString (toString)),
// objectId added when enumerating object's properties
expanded: false,
isValueType: true
@@ -544,25 +868,11 @@ var MonoSupportLib = {
mono_wasm_add_array_item: function(position) {
MONO.var_info.push({
name: "[" + position + "]",
name: `${position}`
});
},
mono_wasm_add_string_var: function(var_value) {
if (var_value == 0) {
MONO.mono_wasm_add_null_var ("string");
return;
}
MONO.var_info.push({
value: {
type: "string",
value: Module.UTF8ToString (var_value),
}
});
},
mono_wasm_add_obj_var: function(className, objectId) {
mono_wasm_add_obj_var: function(className, toString, objectId) {
if (objectId == 0) {
MONO.mono_wasm_add_null_var (className);
return;
@@ -573,51 +883,73 @@ var MonoSupportLib = {
value: {
type: "object",
className: fixed_class_name,
description: fixed_class_name,
description: (toString == 0 ? fixed_class_name : Module.UTF8ToString (toString)),
objectId: "dotnet:object:"+ objectId,
}
});
},
mono_wasm_add_array_var: function(className, objectId) {
/*
* @className, and @targetName are in the following format:
*
* <ret_type>:[<comma separated list of arg types>]:<method name>
*/
mono_wasm_add_func_var: function (className, targetName, objectId) {
if (objectId == 0) {
MONO.mono_wasm_add_null_var (className);
MONO.mono_wasm_add_null_var (
MONO._mono_csharp_fixup_class_name (Module.UTF8ToString (className)));
return;
}
fixed_class_name = MONO._mono_csharp_fixup_class_name(Module.UTF8ToString (className));
MONO.var_info.push({
value: {
type: "object",
subtype: "array",
className: fixed_class_name,
description: fixed_class_name,
objectId: "dotnet:array:"+ objectId,
}
});
},
function args_to_sig (args_str) {
var parts = args_str.split (":");
// TODO: min length = 3?
parts = parts.map (a => MONO._mono_csharp_fixup_class_name (a));
mono_wasm_add_func_var: function(className, objectId) {
if (objectId == 0) {
MONO.mono_wasm_add_null_var (className);
return;
// method name at the end
var method_name = parts.pop ();
// ret type at the beginning
var ret_sig = parts [0];
var args_sig = parts.splice (1).join (', ');
return `${ret_sig} ${method_name} (${args_sig})`;
}
fixed_class_name = MONO._mono_csharp_fixup_class_name(Module.UTF8ToString (className));
MONO.var_info.push({
value: {
type: "function",
description: fixed_class_name,
objectId: "dotnet:object:"+ objectId,
}
});
var tgt_sig;
if (targetName != 0)
tgt_sig = args_to_sig (Module.UTF8ToString (targetName));
var type_name = MONO._mono_csharp_fixup_class_name (Module.UTF8ToString (className));
if (objectId == -1) {
// Target property
MONO.var_info.push ({
value: {
type: "symbol",
value: tgt_sig,
description: tgt_sig,
}
});
} else {
MONO.var_info.push ({
value: {
type: "object",
className: type_name,
description: tgt_sig,
objectId: "dotnet:object:" + objectId,
}
});
}
},
mono_wasm_add_frame: function(il, method, name) {
mono_wasm_add_frame: function(il, method, assembly_name, method_full_name) {
var parts = Module.UTF8ToString (method_full_name).split (":", 2);
MONO.active_frames.push( {
il_pos: il,
method_token: method,
assembly_name: Module.UTF8ToString (name)
assembly_name: Module.UTF8ToString (assembly_name),
// Extract just the method name from `{class_name}:{method_name}`
method_name: parts [parts.length - 1]
});
},
@@ -0,0 +1,15 @@
<linker>
<assembly fullname="mscorlib">
<resource name="collation.cjkCHS.bin" action="remove"/>
<resource name="collation.cjkCHT.bin" action="remove"/>
<resource name="collation.cjkJA.bin" action="remove"/>
<resource name="collation.cjkKO.bin" action="remove"/>
<resource name="collation.cjkKOlv2.bin" action="remove"/>
<resource name="collation.core.bin" action="remove"/>
<resource name="collation.tailoring.bin" action="remove"/>
<type fullname="System.Globalization.CompareInfo">
<method signature="System.Boolean get_UseManagedCollation()" body="stub" value="false"/>
</type>
</assembly>
</linker>
@@ -1,18 +1,18 @@
//describe, beforeAll, it, expect - are the Jasmine default methods
//karmaHTML is the karma-html package object with the access to all its features
describe("The WebAssembly Http Test Suite with Promise Library",function(){
const DEFAULT_TIMEOUT = 1000;
const DEFAULT_WS_TIMEOUT = 5000;
beforeAll(function(done){
//load DOM custom matchers from karma-jasmine-dom package
jasmine.addMatchers(DOMCustomMatchers);
//lets open our 'http-spec.html' file in the browser by 'index' tag as you specified in 'karma.conf.js'
karmaHTML.httpspecwithpromlib.open();
//karmaHTML.httpspecwithpromlib.onstatechange fires when the Document is loaded
//now the tests can be executed on the DOM
karmaHTML.httpspecwithpromlib.onstatechange = function(ready){
@@ -28,40 +28,25 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
};
});
it("should be a real Document object with Promise",function(){
var _document = karmaHTML.httpspecwithpromlib.document;
expect(_document.constructor.name).toEqual('HTMLDocument');
});
it('should support streaming', () => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
assert.equal(_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:IsStreamingSupported", []), true);
});
it('should have streaming enabled', () => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
assert.equal(_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:IsStreamingEnabled", []), true);
});
it('should have base path', () => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
assert.equal(_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:BasePath", []), "http://localhost:9876/");
});
});
it('RequestStream: should return size of Stream with streaming', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestStream", [true, "base/publish/NowIsTheTime.txt"]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -74,7 +59,7 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
it('RequestStream: blob should return size of Stream with streaming', (done) => {
@@ -82,9 +67,9 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
var _document = karmaHTML.httpspecwithpromlib.document;
var blob = new Blob([JSON.stringify({hello: "world"}, null, 2)], {type : 'application/json'});
var blobUrl = URL.createObjectURL(blob);
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestStream", [true, blobUrl]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -97,16 +82,16 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
URL.revokeObjectURL(blobUrl);
}, DEFAULT_TIMEOUT);
it('RequestByteArray: should return size of ByteArray with streaming', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestByteArray", [true, "base/publish/NowIsTheTime.txt"]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -119,7 +104,7 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
it('RequestByteArray: blob should return size of ByteArray with streaming', (done) => {
@@ -129,7 +114,7 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
var blobUrl = URL.createObjectURL(blob);
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestByteArray", [true, blobUrl]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -142,16 +127,16 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
URL.revokeObjectURL(blobUrl);
}, DEFAULT_TIMEOUT);
it('RequestStream: should return size of Stream without streaming', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestStream", [false, "base/publish/NowIsTheTime.txt"]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -164,8 +149,8 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('RequestStream: blob should return size of Stream without streaming', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
@@ -174,7 +159,7 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
var blobUrl = URL.createObjectURL(blob);
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestStream", [false, blobUrl]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -187,16 +172,16 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
URL.revokeObjectURL(blobUrl);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('RequestByteArray: should return size of ByteArray without streaming', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestByteArray", [false, "base/publish/NowIsTheTime.txt"]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -209,7 +194,7 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
it('RequestByteArray: blob should return size of ByteArray without streaming', (done) => {
@@ -219,7 +204,7 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
var blobUrl = URL.createObjectURL(blob);
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestByteArray", [false, blobUrl]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -232,16 +217,16 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
URL.revokeObjectURL(blobUrl);
}, DEFAULT_TIMEOUT);
it('GetStreamAsync_ReadZeroBytes_Success: should return 0', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:GetStreamAsync_ReadZeroBytes_Success", []).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -254,15 +239,15 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('ConnectWebSocketStatus: should return Error Code 1006 because unresolved host.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ConnectWebSocketStatus", ["ws://localhost", ""]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, '1006', "result doesn't match expected result 1006.");
@@ -274,15 +259,15 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_WS_TIMEOUT);
}, DEFAULT_WS_TIMEOUT);
it('ConnectWebSocketStatus: should return Error Code 1006 because of invalid protocol.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ConnectWebSocketStatus", ["ws://localhost:8889", ""]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, '1006', "result doesn't match expected result 1006.");
@@ -294,15 +279,15 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_WS_TIMEOUT);
}, DEFAULT_WS_TIMEOUT);
it('ConnectWebSocketStatusWithToken: should return Error Code 1006 because unresolved host.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ConnectWebSocketStatusWithToken", ["ws://localhost", ""]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, '1006', "result doesn't match expected result 1006.");
@@ -314,15 +299,15 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_WS_TIMEOUT);
}, DEFAULT_WS_TIMEOUT);
it('ConnectWebSocketStatusWithToken: should return Error Code 1006 because of invalid protocol.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ConnectWebSocketStatusWithToken", ["ws://localhost:8889", ""]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, '1006', "result doesn't match expected result 1006.");
@@ -334,15 +319,15 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_WS_TIMEOUT);
}, DEFAULT_WS_TIMEOUT);
it('OpenWebSocket: should return Open.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:OpenWebSocket", ["ws://localhost:8889", "echo-protocol"]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, 'Open', "result doesn't match expected result Open.");
@@ -354,15 +339,15 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('CloseWebSocket: should return Closed.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:CloseWebSocket", ["ws://localhost:8889", "echo-protocol"]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, 'Closed', "result doesn't match expected result Closed.");
@@ -374,16 +359,16 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('ReceiveHostCloseWebSocket: should return Closed.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ReceiveHostCloseWebSocket", ["ws://localhost:8889", "echo-protocol"]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, 'Closed', "result doesn't match expected result Closed.");
@@ -395,15 +380,15 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('CloseStatusDescCloseWebSocket: should return Close Code and Description.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:CloseStatusDescCloseWebSocket", ["ws://localhost:8889", "echo-protocol"]).then(
(result) =>
(result) =>
{
try {
var resultObj = JSON.parse(result);
@@ -417,15 +402,15 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('WebSocketSendText: should return echoed text.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:WebSocketSendText", ["ws://localhost:8889", "echo-protocol", "Hello WebSockets"]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, 'Hello WebSockets', "result does not match Hello WebSockets.");
@@ -437,15 +422,15 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('WebSocketSendBinary: should return echoed text.', (done) => {
//karmaHTML.httpspecwithpromlib.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspecwithpromlib.document;
var binBuffer = new Uint8Array([49,50,51,52,53,54,55,56,57])
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:WebSocketSendBinary", ["ws://localhost:8889", "echo-protocol", "Hello WebSockets"]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, 'Hello WebSockets', "result does not match Hello WebSockets.");
@@ -457,6 +442,6 @@ describe("The WebAssembly Http Test Suite with Promise Library",function(){
(error) => done.fail(error)
);
}, DEFAULT_WS_TIMEOUT);
}, DEFAULT_WS_TIMEOUT);
});
@@ -1,18 +1,18 @@
//describe, beforeAll, it, expect - are the Jasmine default methods
//karmaHTML is the karma-html package object with the access to all its features
describe("The WebAssembly Http Test Suite",function(){
const DEFAULT_TIMEOUT = 1000;
const DEFAULT_WS_TIMEOUT = 5000;
beforeAll(function(done){
//load DOM custom matchers from karma-jasmine-dom package
jasmine.addMatchers(DOMCustomMatchers);
//lets open our 'http-spec.html' file in the browser by 'index' tag as you specified in 'karma.conf.js'
karmaHTML.httpspec.open();
//karmaHTML.httpspec.onstatechange fires when the Document is loaded
//now the tests can be executed on the DOM
karmaHTML.httpspec.onstatechange = function(ready){
@@ -28,40 +28,25 @@ describe("The WebAssembly Http Test Suite",function(){
};
});
it("should be a real Document object",function(){
var _document = karmaHTML.httpspec.document;
expect(_document.constructor.name).toEqual('HTMLDocument');
});
it('should support streaming', () => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
assert.equal(_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:IsStreamingSupported", []), true);
});
it('should have streaming enabled', () => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
assert.equal(_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:IsStreamingEnabled", []), true);
});
it('should have base path', () => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
assert.equal(_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:BasePath", []), "http://localhost:9876/");
});
});
it('RequestStream: should return size of Stream with streaming', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestStream", [true, "base/publish/NowIsTheTime.txt"]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -74,7 +59,7 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
it('RequestStream: blob should return size of Stream with streaming', (done) => {
@@ -82,9 +67,9 @@ describe("The WebAssembly Http Test Suite",function(){
var _document = karmaHTML.httpspec.document;
var blob = new Blob([JSON.stringify({hello: "world"}, null, 2)], {type : 'application/json'});
var blobUrl = URL.createObjectURL(blob);
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestStream", [true, blobUrl]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -97,16 +82,16 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
URL.revokeObjectURL(blobUrl);
}, DEFAULT_TIMEOUT);
it('RequestByteArray: should return size of ByteArray with streaming', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestByteArray", [true, "base/publish/NowIsTheTime.txt"]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -119,7 +104,7 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
it('RequestByteArray: blob should return size of ByteArray with streaming', (done) => {
@@ -129,7 +114,7 @@ describe("The WebAssembly Http Test Suite",function(){
var blobUrl = URL.createObjectURL(blob);
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestByteArray", [true, blobUrl]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -142,16 +127,16 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
URL.revokeObjectURL(blobUrl);
}, DEFAULT_TIMEOUT);
it('RequestStream: should return size of Stream without streaming', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestStream", [false, "base/publish/NowIsTheTime.txt"]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -164,8 +149,8 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('RequestStream: blob should return size of Stream without streaming', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
@@ -174,7 +159,7 @@ describe("The WebAssembly Http Test Suite",function(){
var blobUrl = URL.createObjectURL(blob);
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestStream", [false, blobUrl]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -187,16 +172,16 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
URL.revokeObjectURL(blobUrl);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('RequestByteArray: should return size of ByteArray without streaming', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestByteArray", [false, "base/publish/NowIsTheTime.txt"]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -209,7 +194,7 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
it('RequestByteArray: blob should return size of ByteArray without streaming', (done) => {
@@ -219,7 +204,7 @@ describe("The WebAssembly Http Test Suite",function(){
var blobUrl = URL.createObjectURL(blob);
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:RequestByteArray", [false, blobUrl]).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -232,16 +217,16 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
URL.revokeObjectURL(blobUrl);
}, DEFAULT_TIMEOUT);
it('GetStreamAsync_ReadZeroBytes_Success: should return 0', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[HttpTestSuite]TestSuite.Program:GetStreamAsync_ReadZeroBytes_Success", []).then(
(result) =>
(result) =>
{
//console.log("we are here: " + result);
try {
@@ -254,15 +239,15 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('ConnectWebSocketStatus: should return Error Code 1006 because unresolved host.', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ConnectWebSocketStatus", ["ws://localhost", ""]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, '1006', "result doesn't match expected result 1006.");
@@ -274,15 +259,15 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_WS_TIMEOUT);
}, DEFAULT_WS_TIMEOUT);
it('ConnectWebSocketStatus: should return Error Code 1006 because of invalid protocol.', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ConnectWebSocketStatus", ["ws://localhost:8889", ""]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, '1006', "result doesn't match expected result 1006.");
@@ -294,15 +279,15 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_WS_TIMEOUT);
}, DEFAULT_WS_TIMEOUT);
it('ConnectWebSocketStatusWithToken: should return Error Code 1006 because unresolved host.', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ConnectWebSocketStatusWithToken", ["ws://localhost", ""]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, '1006', "result doesn't match expected result 1006.");
@@ -314,15 +299,15 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_WS_TIMEOUT);
}, DEFAULT_WS_TIMEOUT);
it('ConnectWebSocketStatusWithToken: should return Error Code 1006 because of invalid protocol.', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ConnectWebSocketStatusWithToken", ["ws://localhost:8889", ""]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, '1006', "result doesn't match expected result 1006.");
@@ -334,15 +319,15 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_WS_TIMEOUT);
}, DEFAULT_WS_TIMEOUT);
it('OpenWebSocket: should return Open.', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:OpenWebSocket", ["ws://localhost:8889", "echo-protocol"]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, 'Open', "result doesn't match expected result Open.");
@@ -354,15 +339,15 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('CloseWebSocket: should return Closed.', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:CloseWebSocket", ["ws://localhost:8889", "echo-protocol"]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, 'Closed', "result doesn't match expected result Closed.");
@@ -374,16 +359,16 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('ReceiveHostCloseWebSocket: should return Closed.', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:ReceiveHostCloseWebSocket", ["ws://localhost:8889", "echo-protocol"]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, 'Closed', "result doesn't match expected result Closed.");
@@ -395,15 +380,15 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('CloseStatusDescCloseWebSocket: should return Close Code and Description.', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:CloseStatusDescCloseWebSocket", ["ws://localhost:8889", "echo-protocol"]).then(
(result) =>
(result) =>
{
try {
var resultObj = JSON.parse(result);
@@ -417,15 +402,15 @@ describe("The WebAssembly Http Test Suite",function(){
(error) => done.fail(error)
);
}, DEFAULT_TIMEOUT);
}, DEFAULT_TIMEOUT);
it('WebSocketSendText: should return echoed text.', (done) => {
//karmaHTML.httpspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.httpspec.document;
_document.Module.BINDING.call_static_method("[WebSocketTestSuite]TestSuite.Program:WebSocketSendText", ["ws://localhost:8889", "echo-protocol", "Hello WebSockets"]).then(
(result) =>
(result) =>
{
try {
assert.equal(result, 'Hello WebSockets', "result does not match Hello WebSockets.");
@@ -114,5 +114,24 @@ describe("The WebAssembly Issues Test Suite",function(){
}, DEFAULT_TIMEOUT);
it('https://github.com/mono/mono/issues/18933 System.IO.Path.GetFileName does not work - GetFileName.', () => {
//karmaHTML.issuesspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.issuesspec.document;
var ret = _document.Module.BINDING.call_static_method("[IssuesTestSuite]TestSuite.Program:Issue18933_FileName_Backslash");
assert.equal(ret, "File1.txt", "result doesn't match File1.txt");
}, DEFAULT_TIMEOUT);
it('https://github.com/mono/mono/issues/18933 System.IO.Path.GetFileName does not work - DirectoryInfo.', () => {
//karmaHTML.issuesspec.document gives the access to the Document object of 'http-spec.html' file
var _document = karmaHTML.issuesspec.document;
var ret = _document.Module.BINDING.call_static_method("[IssuesTestSuite]TestSuite.Program:Issue18933_Directory_Backslash");
assert.equal(ret, "File1.txt", "result doesn't match File1.txt");
}, DEFAULT_TIMEOUT);
});
@@ -1,3 +1,22 @@
<Project>
<Import Project="Sdk.targets" Sdk="Microsoft.Build.CentralPackageVersions" />
<Import Project="$(MSBuildThisFileDirectory)..\..\..\common\Versions.props" />
<Target Name="_WriteDotNetTemplateVersion" BeforeTargets="PreBuildEvent">
<PropertyGroup>
<_globalOutputPath>$(MSBuildThisFileDirectory)</_globalOutputPath>
<_globalFixedContent>
<![CDATA[
{
"msbuild-sdks": {
"Microsoft.Build.CentralPackageVersions": "2.0.1",
"Microsoft.Build.Traversal": "1.0.34",
"Mono.WebAssembly.Sdk": "$(SDKPackageVersion)"
}
}
]]>
</_globalFixedContent>
</PropertyGroup>
<WriteLinesToFile File="$(_globalOutputPath)\global.json" Overwrite="true" Lines="$(_globalFixedContent)" />
</Target>
</Project>
@@ -1,6 +1,5 @@
using System;
using System.Net.Http;
using WebAssembly.Net.Http.HttpClient;
using System.Threading.Tasks;
using WebAssembly;
using System.Threading;
@@ -12,18 +11,6 @@ namespace TestSuite
{
static CancellationTokenSource cts = null;
public static bool IsStreamingSupported()
{
using (HttpClient httpClient = CreateHttpClient())
return WasmHttpMessageHandler.StreamingSupported;
}
public static bool IsStreamingEnabled()
{
using (HttpClient httpClient = CreateHttpClient())
return WasmHttpMessageHandler.StreamingEnabled;
}
public static string BasePath()
{
using (HttpClient httpClient = CreateHttpClient())
@@ -39,10 +26,9 @@ namespace TestSuite
{
using (HttpClient httpClient = CreateHttpClient())
{
Console.WriteLine($"streaming supported: { WasmHttpMessageHandler.StreamingSupported}");
WasmHttpMessageHandler.StreamingEnabled = streamingEnabled;
Console.WriteLine($"streaming enabled: {WasmHttpMessageHandler.StreamingEnabled}");
using (var rspMsg = await httpClient.GetAsync(url, cts.Token))
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
httpRequestMessage.Properties["WebAssemblyEnableStreamingResponse"] = streamingEnabled;
using (var rspMsg = await httpClient.SendAsync(httpRequestMessage, cts.Token))
{
requestTcs.SetResult((int)rspMsg.Content?.ReadAsStreamAsync().Result.Length);
}
@@ -65,12 +51,11 @@ namespace TestSuite
{
using (HttpClient httpClient = CreateHttpClient())
{
Console.WriteLine($"streaming supported: { WasmHttpMessageHandler.StreamingSupported}");
WasmHttpMessageHandler.StreamingEnabled = streamingEnabled;
Console.WriteLine($"streaming enabled: {WasmHttpMessageHandler.StreamingEnabled}");
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
httpRequestMessage.Properties["WebAssemblyEnableStreamingResponse"] = streamingEnabled;
Console.WriteLine($"url: {url}");
using (var rspMsg = await httpClient.GetAsync(url, cts.Token))
using (var rspMsg = await httpClient.SendAsync(httpRequestMessage, cts.Token))
{
requestTcs.SetResult(rspMsg.Content?.ReadAsByteArrayAsync().Result.Length);
}
@@ -88,9 +73,15 @@ namespace TestSuite
var requestTcs = new TaskCompletionSource<object>();
using (HttpClient client = CreateHttpClient())
using (Stream stream = await client.GetStreamAsync("base/publish/NowIsTheTime.txt"))
{
requestTcs.SetResult(await stream.ReadAsync(new byte[1], 0, 0));
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "base/publish/NowIsTheTime.txt");
httpRequestMessage.Properties["WebAssemblyEnableStreamingResponse"] = true;
using (var response = await client.SendAsync(httpRequestMessage))
using (Stream stream = await response.Content.ReadAsStreamAsync())
{
requestTcs.SetResult(await stream.ReadAsync(new byte[1], 0, 0));
}
}
return requestTcs.Task;
@@ -105,8 +96,7 @@ namespace TestSuite
{
BaseApiUrl = (string)location.GetObjectProperty("origin");
}
WasmHttpMessageHandler.StreamingEnabled = true;
return new HttpClient() { BaseAddress = new Uri(BaseApiUrl) };
}
}
}
}
@@ -20,7 +20,7 @@
<ItemGroup>
<PackageReference Include="System.Memory" />
<PackageReference Include="WebAssembly.Bindings" />
<PackageReference Include="WebAssembly.Net.Http" />
<PackageReference Include="System.Net.Http.WebAssemblyHttpHandler" />
</ItemGroup>
</Project>
@@ -120,16 +120,21 @@ namespace TestSuite
{
BaseApiUrl = (string)location.GetObjectProperty("origin");
}
// WasmHttpMessageHandler.StreamingEnabled = true;
// var client = new System.Net.Http.HttpClient()
// {
// DefaultRequestHeaders = { { "origin", "WindowsCalculator" } }
// };
return new HttpClient() { BaseAddress = new Uri(BaseApiUrl), DefaultRequestHeaders = { { "origin", "WindowsCalculator" } } };
}
// https://github.com/mono/mono/issues/18933 System.IO.Path.GetFileName doesn't work
public static string Issue18933_FileName_Backslash ()
{
return System.IO.Path.GetFileName(@"C:\FakePath\File1.txt");
}
// https://github.com/mono/mono/issues/18933 System.IO.Path.GetFileName doesn't work
public static string Issue18933_Directory_Backslash()
{
return new System.IO.DirectoryInfo(@"C:\FakePath\File1.txt").Name;
}
}
[Flags]
@@ -20,7 +20,7 @@
<ItemGroup>
<PackageReference Include="System.Memory" />
<PackageReference Include="WebAssembly.Bindings" />
<PackageReference Include="WebAssembly.Net.Http" />
<PackageReference Include="System.Net.Http.WebAssemblyHttpHandler" />
<PackageReference Include="WebAssembly.Net.WebSockets" />
</ItemGroup>
+2 -2
View File
@@ -2,8 +2,8 @@
<ItemGroup>
<PackageReference Update="Mono.WebAssembly.Sdk" Version="0.2.2" />
<PackageReference Update="WebAssembly.Bindings" Version="0.2.2" />
<PackageReference Update="WebAssembly.Net.Http" Version="0.2.2" />
<PackageReference Update="WebAssembly.Net.WebSockets" Version="0.2.2" />
<PackageReference Update="System.Net.Http.WebAssemblyHttpHandler" Version="0.2.2" />
<PackageReference Update="WebAssembly.Net.WebSockets" Version="0.2.2" />
<PackageReference Update="System.Memory" Version="4.5.3" />
</ItemGroup>
</Project>
@@ -20,7 +20,7 @@
<ItemGroup>
<PackageReference Include="System.Memory" />
<PackageReference Include="WebAssembly.Bindings" />
<PackageReference Include="WebAssembly.Net.Http" />
<PackageReference Include="System.Net.Http.WebAssemblyHttpHandler" />
<PackageReference Include="WebAssembly.Net.WebSockets" />
</ItemGroup>
+1 -1
View File
@@ -2,6 +2,6 @@
"msbuild-sdks": {
"Microsoft.Build.CentralPackageVersions": "2.0.1",
"Microsoft.Build.Traversal": "1.0.34",
"Mono.WebAssembly.Sdk": "0.2.2"
"Mono.WebAssembly.Sdk": "0.2.3"
}
}
@@ -122,7 +122,7 @@ namespace DebuggerTests
Console.WriteLine ($"Back from PlaceholderMethod, {c.id}");
}
public static async Task<bool> ValueTypeLocalsAsync (bool call_other)
public static async Task<bool> ValueTypeLocalsAsync (bool call_other = false)
{
var gvclass_arr = new SimpleGenericStruct<Point> [] {
new SimpleGenericStruct<Point> { Id = "gvclass_arr#1#Id", Color = RGB.Red, Value = new Point { X = 100, Y = 200, Id = "gvclass_arr#1#Value#Id", Color = RGB.Red } },
@@ -157,12 +157,12 @@ namespace DebuggerTests
}
// A workaround for method invocations on structs not working right now
public static async Task EntryPointForStructMethod (bool call_other)
public static async Task EntryPointForStructMethod (bool call_other = false)
{
await Point.AsyncMethod (call_other);
}
public static void GenericValueTypeLocals2 (bool call_other)
public static void GenericValueTypeLocals2 (bool call_other = false)
{
var gvclass_arr = new SimpleGenericStruct<Point[]> [] {
new SimpleGenericStruct<Point[]> {
@@ -229,6 +229,13 @@ namespace DebuggerTests
sc_arg.Id = "sc_arg#Id";
Console.WriteLine ($"AsyncInstanceMethod sc_arg: {sc_arg.Id}, local_gs: {local_gs.Id}");
}
public void GenericInstanceMethod<T> (T sc_arg) where T: SimpleClass
{
var local_gs = new SimpleGenericStruct<int> { Id = "local_gs#Id", Color = RGB.Green, Value = 4 };
sc_arg.Id = "sc_arg#Id";
Console.WriteLine ($"AsyncInstanceMethod sc_arg: {sc_arg.Id}, local_gs: {local_gs.Id}");
}
}
public class SimpleClass
@@ -253,4 +260,26 @@ namespace DebuggerTests
public RGB Color { get; set; }
public T Value { get; set; }
}
public class EntryClass {
public static void run ()
{
ArrayTestsClass.PrimitiveTypeLocals (true);
ArrayTestsClass.ValueTypeLocals (true);
ArrayTestsClass.ObjectTypeLocals (true);
ArrayTestsClass.GenericTypeLocals (true);
ArrayTestsClass.GenericValueTypeLocals (true);
ArrayTestsClass.GenericValueTypeLocals2 (true);
ArrayTestsClass.ObjectArrayMembers ();
ArrayTestsClass.ValueTypeLocalsAsync (true).Wait ();
ArrayTestsClass.EntryPointForStructMethod (true).Wait ();
var sc = new SimpleClass { X = 10, Y = 45, Id = "sc#Id", Color = RGB.Blue };
new Point { X = 90, Y = -4, Id = "point#Id", Color = RGB.Green }.GenericInstanceMethod (sc);
}
}
}
@@ -0,0 +1,23 @@
using System;
namespace DebuggerTests
{
public class CallFunctionOnTest {
public static void LocalsTest (int len)
{
var big = new int[len];
for (int i = 0; i < len; i ++)
big [i] = i + 1000;
var simple_struct = new Math.SimpleStruct () { dt = new DateTime (2020, 1, 2, 3, 4, 5), gs = new Math.GenericStruct<DateTime> { StringField = $"simple_struct # gs # StringField" } };
var ss_arr = new Math.SimpleStruct [len];
for (int i = 0; i < len; i ++)
ss_arr [i] = new Math.SimpleStruct () { dt = new DateTime (2020+i, 1, 2, 3, 4, 5), gs = new Math.GenericStruct<DateTime> { StringField = $"ss_arr # {i} # gs # StringField" } };
var nim = new Math.NestedInMath { SimpleStructProperty = new Math.SimpleStruct () { dt = new DateTime (2010, 6, 7, 8, 9, 10) } };
Action<Math.GenericStruct<int[]>> action = Math.DelegateTargetWithVoidReturn;
Console.WriteLine("foo");
}
}
}
@@ -0,0 +1,24 @@
using System;
using System.Globalization;
namespace DebuggerTests {
public class DateTimeTest {
public static string LocaleTest (string locale)
{
CultureInfo.CurrentCulture = new CultureInfo (locale, false);
Console.WriteLine("CurrentCulture is {0}", CultureInfo.CurrentCulture.Name);
DateTimeFormatInfo dtfi = CultureInfo.GetCultureInfo(locale).DateTimeFormat;
var fdtp = dtfi.FullDateTimePattern;
var ldp = dtfi.LongDatePattern;
var ltp = dtfi.LongTimePattern;
var sdp = dtfi.ShortDatePattern;
var stp = dtfi.ShortTimePattern;
DateTime dt = new DateTime (2020, 1, 2, 3, 4, 5);
string dt_str = dt.ToString();
Console.WriteLine("Current time is {0}", dt_str);
return dt_str;
}
}
}
@@ -13,6 +13,7 @@
this.outer_method = Module.mono_bind_static_method ("[debugger-test] Math:OuterMethod");
this.async_method = Module.mono_bind_static_method ("[debugger-test] Math/NestedInMath:AsyncTest");
this.method_with_structs = Module.mono_bind_static_method ("[debugger-test] DebuggerTests.ValueTypesTest:MethodWithLocalStructs");
this.run_all = Module.mono_bind_static_method ("[debugger-test] DebuggerTest:run_all");
this.static_method_table = {};
console.log ("ready");
},
@@ -34,6 +35,10 @@
return await method (...args);
}
function invoke_big_array_js_test (len) {
big_array_js_test(len);
}
function invoke_add () {
return App.int_add (10, 20);
}
@@ -61,9 +66,13 @@
function invoke_method_with_structs () {
return App.method_with_structs ();
}
function invoke_run_all () {
return App.run_all ();
}
</script>
<script type="text/javascript" src="mono-config.js"></script>
<script type="text/javascript" src="runtime.js"></script>
<script type="text/javascript" src="other.js"></script>
<script async type="text/javascript" src="dotnet.js"></script>
Stuff goes here
</body>
@@ -0,0 +1,103 @@
using System;
using System.Threading.Tasks;
namespace DebuggerTests
{
public class EvaluateTestsClass
{
public class TestEvaluate {
public int a;
public int b;
public int c;
public DateTime dt = new DateTime (2000, 5, 4, 3, 2, 1);
public void run(int g, int h, string valString) {
int d = g + 1;
int e = g + 2;
int f = g + 3;
int i = d + e + f;
var local_dt = new DateTime (2010, 9, 8, 7, 6, 5);
a = 1;
b = 2;
c = 3;
a = a + 1;
b = b + 1;
c = c + 1;
}
}
public static void EvaluateLocals ()
{
TestEvaluate f = new TestEvaluate();
f.run(100, 200, "test");
var f_s = new EvaluateTestsStruct ();
f_s.EvaluateTestsStructInstanceMethod (100, 200, "test");
f_s.GenericInstanceMethodOnStruct <int> (100, 200, "test");
var f_g_s = new EvaluateTestsGenericStruct<int> ();
f_g_s.EvaluateTestsGenericStructInstanceMethod (100, 200, "test");
Console.WriteLine ($"a: {f.a}, b: {f.b}, c: {f.c}");
}
}
public struct EvaluateTestsStruct
{
public int a;
public int b;
public int c;
DateTime dateTime;
public void EvaluateTestsStructInstanceMethod (int g, int h, string valString)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
int i = d + e + f;
a = 1;
b = 2;
c = 3;
dateTime = new DateTime (2020, 1, 2, 3, 4, 5);
a = a + 1;
b = b + 1;
c = c + 1;
}
public void GenericInstanceMethodOnStruct<T> (int g, int h, string valString)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
int i = d + e + f;
a = 1;
b = 2;
c = 3;
dateTime = new DateTime (2020, 1, 2, 3, 4, 5);
T t = default(T);
a = a + 1;
b = b + 1;
c = c + 1;
}
}
public struct EvaluateTestsGenericStruct<T>
{
public int a;
public int b;
public int c;
DateTime dateTime;
public void EvaluateTestsGenericStructInstanceMethod (int g, int h, string valString)
{
int d = g + 1;
int e = g + 2;
int f = g + 3;
int i = d + e + f;
a = 1;
b = 2;
c = 3;
dateTime = new DateTime (2020, 1, 2, 3, 4, 5);
T t = default(T);
a = a + 1;
b = b + 2;
c = c + 3;
}
}
}
+332
View File
@@ -0,0 +1,332 @@
using System;
public partial 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;
int f = 0;
return e;
}
public static int UseComplex (int a, int b) {
var complex = new Simple.Complex (10, "xx");
int c = a + b;
int d = c + b;
int e = d + a;
int f = 0;
e += complex.DoStuff ();
return e;
}
delegate bool IsMathNull (Math m);
public static int DelegatesTest () {
Func<Math, bool> fn_func = (Math m) => m == null;
Func<Math, bool> fn_func_null = null;
Func<Math, bool>[] fn_func_arr = new Func<Math, bool>[] { (Math m) => m == null };
Math.IsMathNull fn_del = Math.IsMathNullDelegateTarget;
var fn_del_arr = new Math.IsMathNull[] { Math.IsMathNullDelegateTarget };
var m_obj = new Math ();
Math.IsMathNull fn_del_null = null;
bool res = fn_func (m_obj) && fn_del (m_obj) && fn_del_arr[0] (m_obj) && fn_del_null == null && fn_func_null == null && fn_func_arr[0] != null;
// Unused locals
Func<Math, bool> fn_func_unused = (Math m) => m == null;
Func<Math, bool> fn_func_null_unused = null;
Func<Math, bool>[] fn_func_arr_unused = new Func<Math, bool>[] { (Math m) => m == null };
Math.IsMathNull fn_del_unused = Math.IsMathNullDelegateTarget;
Math.IsMathNull fn_del_null_unused = null;
var fn_del_arr_unused = new Math.IsMathNull[] { Math.IsMathNullDelegateTarget };
OuterMethod ();
Console.WriteLine ("Just a test message, ignore");
return res ? 0 : 1;
}
public static int GenericTypesTest () {
var list = new System.Collections.Generic.Dictionary<Math[], IsMathNull> ();
System.Collections.Generic.Dictionary<Math[], IsMathNull> list_null = null;
var list_arr = new System.Collections.Generic.Dictionary<Math[], IsMathNull>[] { new System.Collections.Generic.Dictionary<Math[], IsMathNull> () };
System.Collections.Generic.Dictionary<Math[], IsMathNull>[] list_arr_null = null;
Console.WriteLine ($"list_arr.Length: {list_arr.Length}, list.Count: {list.Count}");
// Unused locals
var list_unused = new System.Collections.Generic.Dictionary<Math[], IsMathNull> ();
System.Collections.Generic.Dictionary<Math[], IsMathNull> list_null_unused = null;
var list_arr_unused = new System.Collections.Generic.Dictionary<Math[], IsMathNull>[] { new System.Collections.Generic.Dictionary<Math[], IsMathNull> () };
System.Collections.Generic.Dictionary<Math[], IsMathNull>[] list_arr_null_unused = null;
OuterMethod ();
Console.WriteLine ("Just a test message, ignore");
return 0;
}
static bool IsMathNullDelegateTarget (Math m) => m == null;
public static void OuterMethod ()
{
Console.WriteLine ($"OuterMethod called");
var nim = new Math.NestedInMath ();
var i = 5;
var text = "Hello";
var new_i = nim.InnerMethod (i);
Console.WriteLine ($"i: {i}");
Console.WriteLine ($"-- InnerMethod returned: {new_i}, nim: {nim}, text: {text}");
int k = 19;
new_i = InnerMethod2 ("test string", new_i, out k);
Console.WriteLine ($"-- InnerMethod2 returned: {new_i}, and k: {k}");
}
static int InnerMethod2 (string s, int i, out int k)
{
k = i + 10;
Console.WriteLine ($"s: {s}, i: {i}, k: {k}");
return i - 2;
}
public class NestedInMath
{
public int InnerMethod (int i)
{
SimpleStructProperty = new SimpleStruct () { dt = new DateTime (2020, 1, 2, 3, 4, 5) };
int j = i + 10;
string foo_str = "foo";
Console.WriteLine ($"i: {i} and j: {j}, foo_str: {foo_str} ");
j += 9;
Console.WriteLine ($"i: {i} and j: {j}");
return j;
}
Math m = new Math ();
public async System.Threading.Tasks.Task<bool> AsyncMethod0 (string s, int i)
{
string local0 = "value0";
await System.Threading.Tasks.Task.Delay (1);
Console.WriteLine ($"* time for the second await, local0: {local0}");
await AsyncMethodNoReturn ();
return true;
}
public async System.Threading.Tasks.Task AsyncMethodNoReturn ()
{
var ss = new SimpleStruct () { dt = new DateTime (2020, 1, 2, 3, 4, 5) };
var ss_arr = new SimpleStruct [] {};
//ss.gs.StringField = "field in GenericStruct";
//Console.WriteLine ($"Using the struct: {ss.dt}, {ss.gs.StringField}, ss_arr: {ss_arr.Length}");
string str = "AsyncMethodNoReturn's local";
//Console.WriteLine ($"* field m: {m}");
await System.Threading.Tasks.Task.Delay (1);
Console.WriteLine ($"str: {str}");
}
public static async System.Threading.Tasks.Task<bool> AsyncTest (string s, int i)
{
var li = 10 + i;
var ls = s + "test";
return await new NestedInMath().AsyncMethod0 (s, i);
}
public SimpleStruct SimpleStructProperty { get; set; }
}
public static void PrimitiveTypesTest ()
{
char c0 = '€';
char c1 = 'A';
// TODO: other types!
// just trying to ensure vars don't get optimized out
if (c0 < 32 || c1 > 32)
Console.WriteLine ($"{c0}, {c1}");
}
public static int DelegatesSignatureTest ()
{
Func<Math, GenericStruct<GenericStruct<int[]>>, GenericStruct<bool[]>> fn_func = (m, gs) => new GenericStruct<bool[]>();
Func<Math, GenericStruct<GenericStruct<int[]>>, GenericStruct<bool[]>> fn_func_del = GenericStruct<int>.DelegateTargetForSignatureTest;
Func<Math, GenericStruct<GenericStruct<int[]>>, GenericStruct<bool[]>> fn_func_null = null;
Func<bool> fn_func_only_ret = () => { Console.WriteLine ($"hello"); return true; };
var fn_func_arr = new Func<Math, GenericStruct<GenericStruct<int[]>>, GenericStruct<bool[]>>[] { (m, gs) => new GenericStruct<bool[]>() };
Math.DelegateForSignatureTest fn_del = GenericStruct<int>.DelegateTargetForSignatureTest;
Math.DelegateForSignatureTest fn_del_l = (m, gs) => new GenericStruct<bool[]> { StringField = "fn_del_l#lambda" };
var fn_del_arr = new Math.DelegateForSignatureTest[] { GenericStruct<int>.DelegateTargetForSignatureTest, (m, gs) => new GenericStruct<bool[]> { StringField = "fn_del_arr#1#lambda" } };
var m_obj = new Math ();
Math.DelegateForSignatureTest fn_del_null = null;
var gs_gs = new GenericStruct<GenericStruct<int[]>>
{
List = new System.Collections.Generic.List<GenericStruct<int[]>> {
new GenericStruct<int[]> { StringField = "gs#List#0#StringField" },
new GenericStruct<int[]> { StringField = "gs#List#1#StringField" }
}
};
Math.DelegateWithVoidReturn fn_void_del = Math.DelegateTargetWithVoidReturn;
var fn_void_del_arr = new Math.DelegateWithVoidReturn[] { Math.DelegateTargetWithVoidReturn };
Math.DelegateWithVoidReturn fn_void_del_null = null;
var rets = new GenericStruct<bool[]>[] {
fn_func (m_obj, gs_gs),
fn_func_del (m_obj, gs_gs),
fn_del (m_obj, gs_gs),
fn_del_l (m_obj, gs_gs),
fn_del_arr[0] (m_obj, gs_gs),
fn_func_arr[0] (m_obj, gs_gs)
};
var gs = new GenericStruct<int[]>();
fn_void_del (gs);
fn_void_del_arr[0](gs);
fn_func_only_ret ();
foreach (var ret in rets) Console.WriteLine ($"ret: {ret}");
OuterMethod ();
Console.WriteLine ($"- {gs_gs.List[0].StringField}");
return 0;
}
public static int ActionTSignatureTest ()
{
Action<GenericStruct<int[]>> fn_action = (_) => { };
Action<GenericStruct<int[]>> fn_action_del = Math.DelegateTargetWithVoidReturn;
Action fn_action_bare = () => {};
Action<GenericStruct<int[]>> fn_action_null = null;
var fn_action_arr = new Action<GenericStruct<int[]>>[] {
(gs) => new GenericStruct<int[]>(),
Math.DelegateTargetWithVoidReturn,
null
};
var gs = new GenericStruct<int[]>();
fn_action (gs);
fn_action_del (gs);
fn_action_arr[0](gs);
fn_action_bare ();
OuterMethod ();
return 0;
}
public static int NestedDelegatesTest ()
{
Func<Func<int, bool>, bool> fn_func = (_) => { return true; };
Func<Func<int, bool>, bool> fn_func_null = null;
var fn_func_arr = new Func<Func<int, bool>, bool>[] { (gs) => { return true; } };
var fn_del_arr = new Func<Func<int, bool>, bool>[] { DelegateTargetForNestedFunc<Func<int, bool>> };
var m_obj = new Math ();
Func<Func<int, bool>, bool> fn_del_null = null;
Func<int, bool> fs = (i) => i == 0;
fn_func (fs);
fn_del_arr[0](fs);
fn_func_arr[0](fs);
OuterMethod ();
return 0;
}
public static void DelegatesAsMethodArgsTest ()
{
var _dst_arr = new DelegateForSignatureTest[] {
GenericStruct<int>.DelegateTargetForSignatureTest,
(m, gs) => new GenericStruct<bool[]> ()
};
Func<char[], bool> _fn_func = (cs) => cs.Length == 0;
Action<GenericStruct<int>[]> _fn_action = (gss) => { };
new Math ().MethodWithDelegateArgs (_dst_arr, _fn_func, _fn_action);
}
void MethodWithDelegateArgs (Math.DelegateForSignatureTest[] dst_arr, Func<char[], bool> fn_func,
Action<GenericStruct<int>[]> fn_action)
{
Console.WriteLine ($"Placeholder for breakpoint");
OuterMethod ();
}
public static async System.Threading.Tasks.Task MethodWithDelegatesAsyncTest ()
{
await new Math ().MethodWithDelegatesAsync ();
}
async System.Threading.Tasks.Task MethodWithDelegatesAsync ()
{
var _dst_arr = new DelegateForSignatureTest[] {
GenericStruct<int>.DelegateTargetForSignatureTest,
(m, gs) => new GenericStruct<bool[]> ()
};
Func<char[], bool> _fn_func = (cs) => cs.Length == 0;
Action<GenericStruct<int>[]> _fn_action = (gss) => { };
Console.WriteLine ($"Placeholder for breakpoint");
await System.Threading.Tasks.Task.CompletedTask;
}
public delegate void DelegateWithVoidReturn (GenericStruct<int[]> gs);
public static void DelegateTargetWithVoidReturn (GenericStruct<int[]> gs) { }
delegate GenericStruct<bool[]> DelegateForSignatureTest (Math m, GenericStruct<GenericStruct<int[]>> gs);
static bool DelegateTargetForNestedFunc<T>(T arg) => true;
public static unsafe void PointersTest ()
{
int ivalue0 = 5;
int ivalue1 = 10;
int* ip = &ivalue0;
int* ip_null = null;
int** ipp = &ip;
int*[] ipa = new int*[] { &ivalue0, &ivalue1, null };
char cvalue0 = 'q';
char* cp = &cvalue0;
DateTime dt = new DateTime(5, 6, 7, 8, 9, 10);
void* vp = &dt;
void* vp_null = null;
DateTime* dtp = &dt;
DateTime* dtp_null = null;
Console.WriteLine ($"-- break here");
}
public struct SimpleStruct
{
public DateTime dt;
public GenericStruct<DateTime> gs;
}
public struct GenericStruct<T>
{
public System.Collections.Generic.List<T> List;
public string StringField;
public static GenericStruct<bool[]> DelegateTargetForSignatureTest (Math m, GenericStruct<GenericStruct<T[]>> gs)
=> new GenericStruct<bool[]> ();
}
}
public class DebuggerTest
{
public static void run_all () {
locals ();
}
public static int locals () {
int l_int = 1;
char l_char = 'A';
long l_long = Int64.MaxValue;
ulong l_ulong = UInt64.MaxValue;
locals_inner ();
return 0;
}
static void locals_inner () {
}
}
@@ -0,0 +1,44 @@
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; }
public static void Types () {
double dPI = System.Math.PI;
float fPI = (float)System.Math.PI;
int iMax = int.MaxValue;
int iMin = int.MinValue;
uint uiMax = uint.MaxValue;
uint uiMin = uint.MinValue;
long l = uiMax * (long)2;
long lMax = long.MaxValue; // cannot be represented as double
long lMin = long.MinValue; // cannot be represented as double
sbyte sbMax = sbyte.MaxValue;
sbyte sbMin = sbyte.MinValue;
byte bMax = byte.MaxValue;
byte bMin = byte.MinValue;
short sMax = short.MaxValue;
short sMin = short.MinValue;
ushort usMin = ushort.MinValue;
ushort usMax = ushort.MaxValue;
var d = usMin + usMax;
}
}
@@ -91,6 +91,109 @@ namespace DebuggerTests {
public DateTime DT { get; set; }
public RGB RGB;
public static void MethodWithLocalsForToStringTest (bool call_other)
{
var dt0 = new DateTime (2020, 1, 2, 3, 4, 5);
var dt1 = new DateTime (2010, 5, 4, 3, 2, 1);
var ts = dt0 - dt1;
var dto = new DateTimeOffset (dt0, new TimeSpan(4, 5, 0));
decimal dec = 123987123;
var guid = new Guid ("3d36e07e-ac90-48c6-b7ec-a481e289d014");
var dts = new DateTime [] {
new DateTime (1983, 6, 7, 5, 6, 10),
new DateTime (1999, 10, 15, 1, 2, 3)
};
var obj = new ClassForToStringTests {
DT = new DateTime (2004, 10, 15, 1, 2, 3),
DTO = new DateTimeOffset (dt0, new TimeSpan(2, 14, 0)),
TS = ts,
Dec = 1239871,
Guid = guid
};
var sst = new StructForToStringTests {
DT = new DateTime (2004, 10, 15, 1, 2, 3),
DTO = new DateTimeOffset (dt0, new TimeSpan (3, 15, 0)),
TS = ts,
Dec = 1239871,
Guid = guid
};
Console.WriteLine ($"MethodWithLocalsForToStringTest: {dt0}, {dt1}, {ts}, {dec}, {guid}, {dts[0]}, {obj.DT}, {sst.DT}");
if (call_other)
MethodWithArgumentsForToStringTest (call_other, dt0, dt1, ts, dto, dec, guid, dts, obj, sst);
}
static void MethodWithArgumentsForToStringTest (
bool call_other, // not really used, just to help with using common code in the tests
DateTime dt0, DateTime dt1, TimeSpan ts, DateTimeOffset dto, decimal dec,
Guid guid, DateTime[] dts, ClassForToStringTests obj, StructForToStringTests sst)
{
Console.WriteLine ($"MethodWithArgumentsForToStringTest: {dt0}, {dt1}, {ts}, {dec}, {guid}, {dts[0]}, {obj.DT}, {sst.DT}");
}
public static async Task MethodWithLocalsForToStringTestAsync (bool call_other)
{
var dt0 = new DateTime (2020, 1, 2, 3, 4, 5);
var dt1 = new DateTime (2010, 5, 4, 3, 2, 1);
var ts = dt0 - dt1;
var dto = new DateTimeOffset (dt0, new TimeSpan(4, 5, 0));
decimal dec = 123987123;
var guid = new Guid ("3d36e07e-ac90-48c6-b7ec-a481e289d014");
var dts = new DateTime [] {
new DateTime (1983, 6, 7, 5, 6, 10),
new DateTime (1999, 10, 15, 1, 2, 3)
};
var obj = new ClassForToStringTests {
DT = new DateTime (2004, 10, 15, 1, 2, 3),
DTO = new DateTimeOffset (dt0, new TimeSpan(2, 14, 0)),
TS = ts,
Dec = 1239871,
Guid = guid
};
var sst = new StructForToStringTests {
DT = new DateTime (2004, 10, 15, 1, 2, 3),
DTO = new DateTimeOffset (dt0, new TimeSpan (3, 15, 0)),
TS = ts,
Dec = 1239871,
Guid = guid
};
Console.WriteLine ($"MethodWithLocalsForToStringTest: {dt0}, {dt1}, {ts}, {dec}, {guid}, {dts[0]}, {obj.DT}, {sst.DT}");
if (call_other)
await MethodWithArgumentsForToStringTestAsync (call_other, dt0, dt1, ts, dto, dec, guid, dts, obj, sst);
}
static async Task MethodWithArgumentsForToStringTestAsync (
bool call_other, // not really used, just to help with using common code in the tests
DateTime dt0, DateTime dt1, TimeSpan ts, DateTimeOffset dto, decimal dec,
Guid guid, DateTime[] dts, ClassForToStringTests obj, StructForToStringTests sst)
{
Console.WriteLine ($"MethodWithArgumentsForToStringTest: {dt0}, {dt1}, {ts}, {dec}, {guid}, {dts[0]}, {obj.DT}, {sst.DT}");
}
}
class ClassForToStringTests
{
public DateTime DT;
public DateTimeOffset DTO;
public TimeSpan TS;
public decimal Dec;
public Guid Guid;
}
struct StructForToStringTests
{
public DateTime DT;
public DateTimeOffset DTO;
public TimeSpan TS;
public decimal Dec;
public Guid Guid;
}
public enum RGB
+7
View File
@@ -75,7 +75,9 @@
-nomethod System.Text.Tests.StringBuilderTests.Remove_Invalid_Desktop
# System failures
# Added throwing PNSE to the respective code base (mcs/class/corlib/System.Diagnostics.Tracing/EventSource.cs)
-nomethod System.Net.Security.Tests.LoggingTest.EventSource_ExistsWithCorrectId
-nomethod System.Net.Security.Tests.NegotiateStreamStreamToStreamTest_Async.NegotiateStream_StreamToStream_FlushAsync_Propagated
-nomethod System.Net.Security.Tests.NegotiateStreamStreamToStreamTest_BeginEnd.NegotiateStream_StreamToStream_FlushAsync_Propagated
-nomethod System.Net.Security.Tests.NegotiateStreamStreamToStreamTest_Sync.NegotiateStream_StreamToStream_FlushAsync_Propagated
@@ -167,6 +169,7 @@
# System.Net.Security.Tests
# System.NotSupportedException: TLS Support not available
# Added throwing PNSE to the respective code base (mcs/class/System/System.Net.Security/SslStream.cs)
-nomethod System.Net.Security.Tests.SslStreamStreamToStreamTest_Async.SslStream_StreamToStream_Flush_Propagated
-nomethod System.Net.Security.Tests.SslStreamStreamToStreamTest_BeginEnd.SslStream_StreamToStream_Flush_Propagated
-nomethod System.Net.Security.Tests.SslStreamStreamToStreamTest_Sync.SslStream_StreamToStream_Flush_Propagated
@@ -179,3 +182,7 @@
# OOM
-nomethod System.Buffers.Text.Tests.Base64EncoderUnitTests.BasicEncodingWithFinalBlockFalse
# [SkipOnTargetFramework(TargetFrameworkMonikers.Mono)]
-nomethod System.SpanTests.ReadOnlySpanTests.EndsWith_NullInStrings_NonOrdinal
-nomethod System.SpanTests.ReadOnlySpanTests.StartsWith_NullInStrings_NonOrdinal