process_breakpoint() will process breakpoint, stepping, and method
exit/entry events all at the same time when checking a sequence point.
So, if there is is a breakpoint and a stepping event at the same time,
the debugger agent will suspend the current thread twice, which means
you have to click the step button in the debugger client twice on that
line. Considering only one of these events at a time seems to fix
the issue without breaking any current unit tests or showing any other
noticeable issues in testing.
* Fix bug #60843 and add test:
If an enum was nested inside a generic class, using it as an argument to a custom attribute would cause a runtime error in the custom attribute decoder. Update the decoder to forward this special case through the normal primitive loading path.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=60843
* Update based on PR feedback
* Don't use caller info attributes since FullAOT does not have them
* Revert "Don't use caller info attributes since FullAOT does not have them"
This reverts commit 316afb686363ef0e46c15d5858bbc1b85ffd5264.
* Fix embarassing bug in test case
* Update outdated test category name
* Disable bug 60843 test in interpreter
In commit 8ba48b5a41
mono_string_new was adjusted to only assert for
out of memory rather than all errors to preserve
previous behavior for invalid strings. This
change preserves behavior for mono_string_new_wrapper.
This commit allows customization of WCF service creation via the Factory attribute in an .svc file:
`<%@ ServiceHost Language="C#" Service="CustomService" Factory="CustomServiceHostFactory" %>`
All the patch does is uncomment a few lines that were already there and fix a small error. I am not sure why these lines were commented. Possibly the code is not sufficiently robust or it was just never given another look. But this works for me and it seems better than no support at all. For example, a custom ServiceHostFactory appears to be the only way to create a WCF service in a managed host which customizes EndpointDispatcher.AddressFilter and EndpointDispatcher.ContractFilter. This in turn is useful for proxied WCF services.
See also http://mono.1490590.n4.nabble.com/Mono-WCF-ServiceHost-Factory-option-td4251992.html (from 2012; never posted on the mailing list for some reason).
The previous code was handling only objects residing in 2 32bit card protected address spaces. This means card table scanning for objects larger than 4GB was potentially broken, while card scanning of objects larger than 8GB was completely broken.
Fixes https://github.com/mono/mono/issues/7537
[threads] Delay abort via handler block guard when in abort protected block.
`mono_install_handler_block_guard` is called when we want to signal an async
abort to another thread. In case the other thread is executing native code
while in a `finally` block, the handler block guard sets a byte in the finally
block that used to trigger a self abort (`mono_thread_self_abort`).
This PR renames `mono_thread_self_abort` to
`ves_icall_thread_finish_async_abort`. It also changes the code from
immediately executing a synchronous abort, to checking whether we are in an
abort protected block (most commonly - whether we were called from a cctor) and
in that case merely toggling the "async interrupt"
MonoInternalThread:thread_state bit. If we're not in an abort-protected block,
trigger a self interrupt (which will turn into an abort exception in the
icall wrapper of `ves_icall_thread_finish_async_abort`).
Fixes#7588
The latest `WebCompletionSource<T>` changes (PR #7358) exposed and
intensified the side-effects of a race condition between `WebOperation`
and `ServicePointScheduler`.
* WebCompletionSource<T> now contains new `CurrentResult` and `CurrentStatus`
properties, which allow completion status to be checked in a non-blocking way.
* WebOperation.CompleteResponseRead() has been renamed into Finish() and
contains the continuation that was previouly known as FinishReading().
Calling this new Finish() method will now complete the `finishedTask`
completion, which has a new accessor called `Finished`.
* The ServicePointScheduler's main-loop is still woken up by completion of
`WebOperation.Finished.Task`, but we use the new `CurrentResult` property
to check state in a non-blocking way. This ensures the the clean-up and
bookkeeping work that's necessary after `WebCompletion.Finish()` always
happens prior to starting new connections.
* [w32file] remove unused mono_w32file_get_times ()
* [w32file-unix] replace SECMULT with TICKS_PER_SECOND
* [w32file-unix] use CONVERT_BASE in more places
* [w32file-unix] factor setfiletime
* [w32file-unix] use utimes if available in order to set subsecond information on access and write time
* [FileTest] add regression test for github issue 7646
* [w32file-unix] reduce compiler warnings
* [w32file-unix] 1000ns = 1us and 1us = 10ticks
* [w32file-unix] add LL suffix to constant in order to prevent overflowing on 32bit systems
* [loader] Don't load framework Facade assemblies that are older than expected.
If there is an older framework Facade assembly in the search order before the
one that we want, don't load it.
"older" here means just compare the major components of the version.
Fixes https://github.com/mono/mono/issues/7624
Even though it's found during configure when targetting 10.7, it's not "really" available before versions 10.12 and it would crash with "lazy symbol binding failed".
When mono is used as a submodule then .git will be a file instead of a
directory. Adjusted the version.h generation code to support that.
Also newer git version started to use `(HEAD detached at <git sha>)`
in `git branch` output instead of `(detached from <git sha>)`,
fixed the regex to support that pattern too.
* [Tailcall] Cleanup is_supported_tail_call to only check virtual_, not opcode == CALLVIRT.
* [Tailcall] Generate tailcall address earlier to honor NT ABI.
Let R11 through tailcall.
Assert alignment when patching.
* [Tailcall] Factor out two copies of SysV varargs handling to a helper function and remove for NT.
Tailcall needs a third instance, and it likely gets in the way of NT tailcall, where it is not needed.
* [Tailcall] Teach amd64_patch how to patch jmp rip+32 and jmp [rip + 32]
very similar to call rip+32 and call [rip + 32]. This might be useful.
* [Tailcall] Fix varargs handling of tailcalls.
* Remove new asserts and just leave comments.
* [Tailcall] No need to free RAX on non-reg calls.
send an internal VM_DISPOSE command to shut down the debugger thread
properly. This prevents runtime hangs that occur during profile
events after the debugger shuts down.
* Fix bounds manipulation in Control.DrawToBitmap and dispose objects properly.
* Add test for DrawToBitmap and fix one more bug in the implementation.
Fixes#7620
On macOS the stopwatch's elapsed time was regularly getting skewed by 200-800ms. On average, yielding decreases the number of GCs by only 25%, while the elapsed time error is always less than 15ms.
Fixes#6999
When a thread has a handler block guard installed (a `finally` block
that checks the exvar to see if it should issue abort the thread because
another thread called Abort on it), ves_icall_thread_finish_async_abort
is called. It must clear the handler block guard for the current thread
in case the abort landed while we're in an abort protected block (a
cctor, most commonly). In that case we must resume the interruption
when we leave all the abort protected blocks, not just at the end of an
intermitent catch clause.
mono_install_handler_block_guard is called when we want to signal an async
abort to another thread. In case the other thread is executing native code
while in a `finally` block, the handler block guard sets a byte in the finally
block that used to trigger a self abort (`mono_thread_self_abort`).
This PR renames `mono_thread_self_abort` to
`ves_icall_thread_finish_async_abort`. It also changes the code from
immediately executing a synchronous abort, to checking whether we are in an
abort protected block (most commonly - whether we were called from a cctor) and
in that case merely toggling the "async interrupt"
MonoInternalThread:thread_state bit. If we're not in an abort-protected block,
trigger a self interrupt (which will turn into an abort exception in the
icall wrapper of `ves_icall_thread_finish_async_abort`).
* Revert "[Tailcall] Quick fix for building F#. Do not tailcall any method with a vtable_arg. (#7609)"
This reverts commit 8ceead93e3.
* [Tailcall] Correct fix for regression from change b4ee86154f.
Regression test not yet available.
* extra brace
* [jit] Incorrect code under mono --trace.
* [Tailcall] call_opcode == CEE_CALLVIRT does not matter for tailcall_membase, only virtual_ does.
* [Tailcall] Add FIXME for tail. not followed by ret. Correct behavior is to raise an exception, not fail an assert.
* [Tailcall] Add disabled debug code to break when compile a tailcall and/or execute a tailcall.
* [Tailcall] Add disabled debug code to try to tailcall any call followed by a ret.
This might be reasonable in the future, as well as a little data flow
analysis skipping nops and branches, as csc w/o -optimize outputs.
* [Tailcall] Add more tailcall tests, i.e. that would
have caught recent regression.
* [Tailcall] Replace #if 0 with MONO_DEBUG=tailcall_break_compile,tailcall_break_run,tailcall_try_all,tailcall_log,
tailcall_all. Consider MONO_TAILCALL_DEBUG instead.
* Revert "[Tailcall] Replace #if 0 with MONO_DEBUG=tailcall_break_compile,tailcall_break_run,tailcall_try_all,tailcall_log,"
This reverts commit 796d9490f672625189dfac47ff24b05f3fb65cbe.
* [Tailcall] Replace #if 0 with ifdefs:
define DEBUG_TAILCALL_BREAK_COMPILE breakpoint in method-to-ir
define DEBUG_TAILCALL_BREAK_RUN 1 codegen outputs breakpoint
define DEBUG_TAILCALL_TRY_ALL 1 consider any call followed by ret, can expand later
define DEBUG_TAILCALL 1 low volume logging under -v instead of -v -v
* [Tailcall] Dial back tailcalls on ARM32, where there is no
volatile non-parameter register in the ABI, in which to pass
an extra parameter. (Why not just pass as a regular first/last parameter?)
* [Tailcall] Dial back untested architectures MIPS S390x PowerPC SPARC.
* [Tailcall] Copy tailcall-generic-cast-il.il to tailcall-generic-cast-nocrash-il.il and tailcall-generic-cast-conservestack-il.il
All platforms should be able to run it without crash,
but only some can run it and conserve stack.
* [Tailcall] Finish splitting tailcall-generic-cast into nocrash and conservestack variations.
All platforms can run nocrash, only some conservestack.
* Change the logic for closing ToolStrip drop-downs to work for more complex nesting.
* Implement SetOwner/GetParent(with_owner=true) behavior for X11 and Carbon backends.
Fixes the logic for closing ToolStripDropDowns for the following cases:
* ComboBox embedded in ToolStripDropDown as seen in KeePass when the window is resized to be small enough for the toolbar to overflow.
* ToolStripDropDown containing controls that open other ToolStripDropDowns and the user clicks on the top-level ToolStripDropDown. The child ToolStripDropDown, and only that child, should be closed in that case.
* Update AnchorLayoutEvents to match Windows behavior, make Bug82762 test platform independent.
* Cache affected layout control and property across SuspendLayout/ResumeLayout.
* Extend AnchorLayoutEvents test.
* Update for little nuances in the layout code.
* Unify flow layout for ToolStrips and FlowLayoutPanel by using the IArrangedContainer and IArrangedElement abstractions.
* Implement basic table layout support for ToolStrips.
* Clean up handling of FlowLayoutSettings.
* Fixes for default values of LayoutSettings in tool strips.
* Remove more of the duct tape holding the ToolStrip layouts together and replace it with calls into the LayoutEngine. Fix other small bugs that prevented ToolStrip overflows from being displayed correctly. Tested with KeePass.
* Fix indentation.
* Address code style issues.
* Remove unnecessary override.
* Fix indentation.
* Bump API snapshot submodule
* Fix error in vcxproj filter causing load error in Visual Studio.
* Fixes issue #7596 on Windows x64.
Passing value types in Windows x64 not fitting into register will be passed
by reference (ArgValuetypeAddrInIReg or ArgValuetypeAddrOnStack )
using a local variable allocated in caller’s frame.
Current implementation sized and marshaled the native struct correctly when
using pinvoke, but it sized the final local passed as reference to the native method
using the managed stack size instead of the native. This caused the final copy
into the local to overwrite other locals on stack if managed and native struct stack
sizes differed.
The fix is to flag the local variable used as stack parameter with its pinvoke state.
This makes sure the stack allocation size will be correct when using value types
passed on the stacks in pinvokes.
When running other unit tests with sequence points I hit a similar issue with
empty structs as return parameters (using [StructLayout (LayoutKind.Sequential, Size = 0)].
This commit includes a fix to ignore the return value if it’s an empty struct on Windows x64.
* [sgen] Use current nursery size when computing allowance
The allowance is the minimum heap growth that we allow between two majors (which is 4 * nursery_size). We need to use the current nursery size instead of the 4MB default, in order to facilitate low memory uses.
* [sgen] Account for soft heap limit in allowance calculation
This is relevant in cases where the nursery size and soft heap limit are comparable in size.
* [profiler] Fix wrong docs for mono_profiler_set_call_instrumentation_filter_callback ().
* [mini] Don't inline methods if they're going to be instrumented for coverage.
This handles coverage instrumentation in a similar fashion to call
instrumentation.
Fixes#6186.
* [mini] Add MonoError to mini_get_shared_method_full and replace bucket of booleans with a flags enum.
* [mini] Eliminate mini_get_shared_method in favor of the variant that takes a MonoError.
* [mini] Rename GetSharedMethodFlags members to follow our coding conventions.
* [mini] Remove reduntant arguments in get_shared_inst.
* [mini] Inline partial in mini_get_shared_method_full.
* [mini] In mini_get_shared_method_full, rename gsharedvt to use_gsharedvt_inst and move it's value to depend on all_vt.
* [mini] Eliminate SHARE_MODE_ALL_VALUETYPES as its semantically equivalent to SHARE_MODE_GSHAREDVT.
* Fix platform-specific build issues
These changes allow some of the Mono code used by the debugger to build
on a few additional platforms. Specifically, this includes platforms:
* That don't have access to the full Win32 API
* That don't have access to the full Posix API
* That don't support IPv6
* Wrap `access` and `_access` in `g_access`
* Convert indentation to tabs
* Wrap `mktemp` and `_mktemp` in `g_mktemp`
* Wrap `open` and `_open` in `g_open`
* Wrap `write` and `_write` in `g_write`
* Fix indentation
* Use proper asserts
* Add a configure check for `access`
* Remove the use of HAVE_XBOXONE_WINAPI_SUPPORT
* Replace the previous definition of `g_open`
I missed that it was here in my earlier commit, and ended up redefining
it.
* Use `g_error` instead of `g_assert(0)`
* [Tailcall] Quick fix for building F#.
Do not tailcall any thing with a vtable_arg.
This does often work, but not in F#, along with unbox in the call target.
The problem is being further reduced and debugged, but this will serve for now.
Regression is from change b4ee86154f.
* [Tailcall] Temporarily disable tests that depend on tailcall.
* [Coop] ves_icall_System_Threading_Thread_GetDomainID convert to coop/handle.
* [Coop] Convert ves_icall_System_Threading_Thread_ConstructInternalThread to coop/handle.
* [Coop] Convert ves_icall_System_Threading_Thread_Thread_internal to coop/handle.
* [Coop] Convert mono_threads_get_max_stack_size ves_icall_System_Threading_Thread_SystemMaxStackSize/typo SystemMaxStackStize to coop/handle.
* [Coop] Convert ves_icall_System_Threading_Thread_Suspend to coop/handle.
* [Coop] Convert ves_icall_System_Threading_Thread_Sleep_internal to coop/handle.
* [Coop] Convert ves_icall_System_Threading_Thread_SpinWait_nop to coop/handle.
* [Coop] Convert threadpool.c to handles -- no pointers, just MonoError.
* [Coop] Convert ves_icall_System_Threading_InternalThread_Thread_free_internal to coop/handle.
* [Coop] Convert mmap to coop/handle -- where there aren't pointers, just unused errors.
* [Coop] Rename some error to ioerror or win32error.
* [Coop] Convert ves_icall_System_Threading_Thread_current_lcid to coop/handle -- no pointers.
* [Coop] Convert mono_mmap_open_file, mono_mmap_open_handle to coop/handle.
* [Coop] Convert ves_icall_System_Threading_Thread_Yield to coop/handle (no pointers).
* [Coop] Layer ves_icall_System_Threading_Thread_ConstructInternalThread over new mono_thread_construct_internal.
* Ignore out of memory.
* Favor mono_error_set_generic_error over small factories (loss of breakpoint?).
* Restore accidentally lost barrier.
* [Coop] Mostly undo commit d7bdbcc9a2e76913861b69ff106f0bf9573e7ea6
Convert ves_icall_System_Threading_Thread_Sleep_internal to coop/handle.
for now.
It duplicates mono_thread_execute_interruption to mono_thread_execute_interruption_handle
which we want to ensure does not last long.
This should be achieved better by pull
https://github.com/mono/mono/pull/6639
which removes all but one pointer user and leaves
that pointer user layered over handle instead of duplicating.
* [Coop] Fix Windows build.
* [Tailcall][Windows] Add missing error parameter.
* [Tailcall] Cleanup is_supported_tail_call to use language-base short circuit.
* [Tailcall] Move more of the logic into is_supported_tail_call.
* [Tailcall] Be sure not to use TAILCALL_MEM_BASE if not supported.
i.e. not if virtual_, besides CALLVIRT -- they are not quite the same.
* [Facades] Make System.Net.Http.Rtc.dll a net_4_x only facade
It doesn't make sense on mobile (see https://github.com/mono/mono/pull/7541#issuecomment-372434424) but we'd like to keep it in net_4_x to match Desktop .NET
* Bump API snapshot submodule
We implemented them in the facades until now but in .NET 4.7.1
they were promoted into the regular class libraries.
Use PLATFORM_DEBUG_FLAGS for IL-less assemblies
Also replace some files with corefx that were identical.
* Fix the test for OnCreateControl.
* Do not create child controls until the parent is created.
* Fix showing menus after CreateControl behavior change.
* Make all top-level controls call SetTopLevel.
* Fix TopLevelControl property to actually return top-level controls, not just Forms.
* [threads] Fix race between abort socket syscall and thread shutdown
The race happens when we call mono_thread_info_abort_socket_sycall_for_close on
a thread that's about to shut down.
We lookup the MonoThreadInfo for that thread outside the
mono_thread_info_suspend_lock, and then use it to send the signal once we've
taken the lock.
In between those two actions, the other thread already finished
unregister_thread and pthreads may already have destroyed its TLS keys and
otherwise started to dismantle the thread.
The fix is to do a second mono_thread_info_lookup once we have the lock and
only signal the other thread if it still around.
Fixes https://github.com/mono/mono/issues/6998
* [threads] Simplify mono_thread_info_abort_socket_syscall_for_close
Call mono_thread_info_lookup while holding the thread info suspend lock.
We no longer need to check for STATE_DETACHED because removing MonoThreadInfo on
detach is done while holding the suspend lock.
* [metadata] split IL generation code into seperate compilation units.
* [metadata] move ENABLE_ILGEN definition to configure
* [metadata] split IL generation code into seperate compilation units.
By adding callbacks for IL generating runtime code, we can link in code
later into the runtime that does such for configurations which do not
need IL generation initially. This is the case if you configure the
runtime with `--enable-minimal=jit,interpreter`.
In such configuration, the build will produce an additional library,
called `libmono-ilgen`.
An embedded can choose to link this library to the final binary and
initialize IL generation with the following three, newly added, API
calls:
* `void mono_marshal_ilgen_init (void)`
* `void mono_method_builder_ilgen_init (void)`
* `void mono_sgen_mono_ilgen_init (void)`
This change is mostly moving code around, but there are minor changes
like introducing the enum `MarshalTypeCheckPositions`, so we avoid
copy/paste constants accross compilation units.
* [windows] add IL gen files to windows build and set ENABLE_ILGEN
* [fixup!] fix windows build
* [fixup!] resolve merge conflicts with class getter commits
* marshal.c: b8da973620
* sgen-mono.c: 8ba4947f7a
at some point I gave up to resolve merge conflicts and worked through
errors/warnings by compiling with
> `CFLAGS=-DENABLE_CHECKED_BUILD_PRIVATE_TYPES=1`
so the result is likely a bit different
* redo lost changes from 57f3f34e60
* redo lost changes from 52514effbf
* [fixup!] fix array marshal
* [method-builder] use eglib types
review comment by Ludovic,
https://github.com/mono/mono/pull/7375#discussion_r171876337
* [marshal] remove stelem strings from header
review comment by Rodrigo,
https://github.com/mono/mono/pull/7375#discussion_r171921029
* gboolean g_is_usermode_native_debugger_present (void).
i.e. Win32 IsDebuggerPresent which is just call mov mov ret.
Other slower methods on other systems if possible and unintrusive (OSX).
This is very useful as in:
if (g_is_usermode_native_debugger_present ()) G_BREAKPOINT
"native" meaning "not managed"
"usermode" meaning "not kernel"
Both other kinds exist and are detected differently.
* Move new debugging utility from glib to mono/utils.
* Redo it with CoreCLR as basis. https://github.com/dotnet/coreclr/blob/master/src/pal/src/init/pal.cpp
* Link to a specific stable revision, not master.
https://raw.githubusercontent.com/dotnet/coreclr/f1c9dac3e2db2397e01cd2da3e8aaa4f81a80013/src/pal/src/init/pal.cpp
* Use a clearer form of boolean normalization.
* Update Visual Studio project files.
* Fix include path, remove unnecessary boolean canonicalization, spell out words, swap int/boolean.
* Header got missed in the move from glib.
It'd fail with the following errors since e6de24c2d1:
```
MCS [net_4_x-darwin] net_4_x_System.Data.OracleClient_test.dll
Test/System.Data.OracleClient.jvm/MonoTests.System.Data.Utils/ADONetTesterClass.cs(337,71): error CS0012: The type `System.Xml.Serialization.IXmlSerializable' is defined in an assembly that is not referenced. Consider adding a reference to assembly `System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
...
MCS [net_4_x-darwin] net_4_x_System.Json.Microsoft_test.dll
Test/System.Json/JsonValueTest.cs(23,12): error CS0012: The type `System.Dynamic.IDynamicMetaObjectProvider' is defined in an assembly that is not referenced. Consider adding a reference to assembly `System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
...
MCS [net_4_x-darwin] DummyAssembly.dll
error CS0518: The predefined type `System.Object' is not defined or imported
error CS0518: The predefined type `System.ValueType' is not defined or imported
```
* [ci] Add compiling class lib tests to mcs job
* Avoid recalculating Document on TextBox controls without handles. Properly dispose graphic contexts.
* Make sure all CreateGraphics calls are wrapped in using block.
* Avoid a couple more no-op calls in RichTextBox.
* Fix default values and the StartPage property in PrintPreviewControl.
* Do not cache resized bitmaps in PrintPreviewControl if the source data are scalable metafiles.
* [interp] Use jit's dead basic block detection
Using generating_code doesn't cover all cases since it doesn't do basic block liveness calculation.
* [interp] Throw instructions clear the stack
* [interp] Add stack check at return
There would be a compilation error in the XA build as follow:
```
obj/Release/bundles/armeabi-v7a/temp.c: In function 'install_aot_modules':
obj/Release/bundles/armeabi-v7a/temp.c:49:25: error: 'MONO_AOT_MODE_NORMAL' undeclared (first use in this function)
mono_jit_set_aot_mode (MONO_AOT_MODE_NORMAL);
^
obj/Release/bundles/armeabi-v7a/temp.c:49:25: note: each undeclared identifier is reported only once for each function it appears in
```
* [Tailcall] Fix the F# code; let rec functiona ()= printfn "%d" 1; functionb ()
and functionb ()= functiona ()
let ()= functiona ()
The test case and the fix are from https://bugzilla.xamarin.com/show_bug.cgi?id=25224.
Just bringing in change ca0dd5c0bb:
commit ca0dd5c0bb
Author: Zoltan Varga <[email protected]>
Date: Thu Dec 11 15:37:29 2014 -0500
[jit] Enable tail calls from gshared code. Fixes#25224.
Previously it was reverted due to performance regression, which has been fixed.
The problem was that use vs. patch of jmps was using inflated vs. non-inflated code.
Fixed here: https://github.com/mono/mono/commit/fe95e4b34b00caa8073dfa3b4473a43182abcbbb
The IL is:
.method public static !!a functiona<a>() cil managed
{
.
.
.
IL_001d: tail.
IL_001f: call !!0 '1'::functionb<!!0>()
IL_0024: ret
}
.method public static !!a functionb<a>() cil managed
{
IL_0000: tail.
IL_0002: call !!0 '1'::functiona<!!0>()
IL_0007: ret
}
* [Tailcall] Add tail.callvirt support to AMD64 JIT. Not yet
any other architecture (arm, x86, etc.) or scenario (AOT, LLVM,
interpreter, etc.)
This is based on F# that stack overflows to report failure:
type A() =
member this.f2 (a) = if a > 0 then this.f1(a - 1)
else 1
member this.f1 (a) = if a > 0 then this.f2(a - 1)
else 2
let a = A()
printfn "%d" (a.f1(1000 * 1000 * 10))
and in turn C#, self checking instead of stack overflowing:
using System;
using System.Runtime.CompilerServices;
using static System.Runtime.CompilerServices.MethodImplOptions;
unsafe class A
{
static int check (long stack1, long stack2)
{
return (stack1 == stack2) ? 0 : 1;
}
[MethodImpl (NoInlining)]
public virtual int f1 (int counter, long initial_stack, long current_stack)
{
int local;
if (counter > 0)
return f2 (counter - 1, initial_stack, (long)&local);
return check ((long)&local, current_stack);
}
[MethodImpl (NoInlining)]
public virtual int f2 (int counter, long initial_stack, long current_stack)
{
int local;
if (counter > 0)
return f1 (counter - 1, initial_stack, (long)&local);
return check ((long)&local, current_stack);
}
[MethodImpl (NoInlining)]
public static void Main ()
{
int stack;
Environment.Exit (new A().f1 (100, (long)&stack, 0));
}
}
And then IL, inserting tail prefixes and cleaning up a little:
.assembly extern mscorlib { }
.assembly b { }
.class A
{
.method static int32 check(int64 stack1, int64 stack2)
{
ldarg.0
ldarg.1
beq.s IL_0006
ldc.i4.1
ret
IL_0006:
ldc.i4.0
ret
}
.method newslot virtual instance int32 f1 (int32 counter, int64 initial_stack, int64 current_stack) noinlining
{
.locals init (int32 V_0)
ldarg.1
ldc.i4.0
ble.s IL_0013
ldarg.0
ldarg.1
ldc.i4.1
sub
ldarg.2
ldloca.s V_0
conv.u
conv.u8
tail. callvirt instance int32 A::f2 (int32, int64, int64)
ret
IL_0013:
ldloca.s V_0
conv.u
conv.u8
ldarg.3
tail. call int32 A::check (int64, int64)
ret
}
.method newslot virtual instance int32 f2 (int32 counter, int64 initial_stack, int64 current_stack) noinlining
{
.locals init (int32 V_0)
ldarg.1
ldc.i4.0
ble.s IL_0013
ldarg.0
ldarg.1
ldc.i4.1
sub
ldarg.2
ldloca.s V_0
conv.u
conv.u8
tail. callvirt instance int32 A::f1 (int32, int64, int64)
ret
IL_0013:
ldloca.s V_0
conv.u
conv.u8
ldarg.3
tail. call int32 A::check (int64, int64)
ret
}
.method static int32 Main () noinlining
{
.entrypoint
.locals init (int32 V_0)
newobj instance void A::.ctor()
ldc.i4 0x100
ldloca.s V_0
conv.u
conv.u8
ldc.i4.0
conv.i8
tail. callvirt instance int32 A::f1 (int32, int64, int64)
ret
}
.method instance void .ctor ()
{
ldarg.0
tail. call instance void [mscorlib]System.Object::.ctor ()
ret
}
}
* Allow comments anywhere in .md line, not just the start.
* [Tailcall] Avoid changing ins->sreg1 in OP_TAILCALL_MEMBASE.
This was likely based on OP_CALL_REG which has more reason to do
it but still not a good example.
* [Tailcall] Rollback x86/arm/ppc/llvm until changes are actually
complete/working.
* [Tailcall] Fix code formating: default at end, open brace at right on
previous line.
* [Tailcall] Consolidate comments out of tailcall-virt.cs and tailcall-virt.fs and into tailcall-virt.il.
Make IL less unreadable with whitespace.
Disable instead of enable tailcall-virt test.
* [Tailcall] Combine assert and default that it made unreachable and make assert more informative.
* [Tailcall] Remove a newline.
* [Tailcall] Add additional verbose output.
Add 3 tests that would seem focused on this change and would
seem to be fixed -- all three pass on desktop, all three fail
on previous mono, two are fixed now -- one needs more debugging --
generic value types.
Problem is probably:
is_supported_tail_call:
if (fsig->hasthis && cmethod->klass->valuetype)
/* this might point to the current method's stack */
supported_tail_call = FALSE;
* [Tailcall] Allow tail.callvirt on AMD64 AOT now, having tested it.
* [Tailcall] LLVM support for tail.callvirt/OP_TAILCALL_MEMBASE, now having tested it.
* [Tailcall] Disable new tests for interpreter as I had intended.
* [Tailcall] Consolide interpreter disabling of tailcall tests.
Address https://github.com/mono/mono/issues/7093 in kind of an adhoc way.
The correct fix is to make
```
((IEnumerable<U>) (new T[] {...})).GetEnumerator()
```
return an `IEnumerator<U>` (like .NET does) instead of `IEnumerator<T>`
and to stop marking IEnumerator as an array special interface.
fetching Microsoft.NET.Build.Extensions nuget from `cli-deps` to
`dotnet-core`. Both of these should have the same nugets but sometimes
seem to be off by one.
To pick up:
commit 345755cb49ee1979df280399f03178aae0b4029a
Author: Alex Rønne Petersen <[email protected]>
Date: Tue Mar 6 13:40:16 2018 +0100
Add build support for RISC-V. (#6)
Use `MonoClass` getters in the rest of the code in `mono/metadata/`
1. Add `mono_class_contextbound_bit_offset()` which returns the bit offset of `MonoClass:contextbound` which is needed by `remoting.c`
2. Add `mono_class_create_array_fill_type` which is used by sgen to write over unused nursery fragments.
3. Alllow `metadata-cross-helpers.c` to access `MonoClass` fields directly. Rationale: it needs to compute field offsets.
4. Everything else shouldn't have any functional changes.
https://github.com/mono/mono/issues/6925
---
* [metadata] Fix warnings in class-accessors.c
Fix warnings about missing prototypes for class-abi-details.h functions.
* [cominterop] Use MonoClass getters in cominterop.c
* [loader] Use MonoClass getters in loader.c
* [runtime] Use MonoClass getters in icall.c
* [metadata] Add mono_class_contextbound_bit_offset() accessor
Compute the bit offset of MonoClass:countextbound
* [remoting] Use MonoClass getters for remoting.c
* [boehm] Use MonoClass getters in boehm-gc.c
* [callspec] Use MonoClass getters in callspec.c
* [sre] Use MonoClass getters in dynamic-image.c
* [w32] Use MonoClass getters in w32process.c
* [debug] Use MonoClass getters in mono-debug.c
* [runtime] Use MonoClass getters in method-builder.c
* [runtime] Use MonoClass getters in security-manager.c
* [coop] Use MonoClass getters in handle.c
* [reflection] Use MonoClass getters in reflection.c
* [sgen] Add mono_class_create_array_fill_type
Used by sgen to fill nursery fragments before a collection
* [sgen] Use MonoClass getters in sgen-mono.c and the GC bridges
* [verify] Use MonoClass getters in the verifier
* [sre] Use MonoClass getters in SRE
* [custom_attr] Use MonoClass getters in custom-attrs.c
* [metadata] Use MonoClass getters in gc.c
* [security-core-clr] Use MonoClass getters in security-core-clr.c
* [metadata] Use MonoClass getters in metadata.c
* [metadata] Allow metadata-cross-helpers to access MonoClass fields
* [coop handle] Use MonoClass getter in mono_handle_unbox_unsafe
attribute(deprecated(message)) was introduced in gcc 4.5.
attribute(deprecated) was introduced in gcc 4.0?
pragma GCC diagnostic 4.2?
https://github.com/mono/mono/issues/7408
* Update many of the unit tests to pass on Windows.
* Update the TextBox default colors.
* Update ToolStripManager.RevertMerge error handling.
* Update menu item cloning to pass unit tests.
* Update PreviewKeyDownEventArgs.KeyValue behavior.
* Update return value of AccessibleObject.State.
* Update TextBoxBase.IsInputKey to treat backspace as input key.
* Update constructors of BindingCompleteEventArgs to properly set the Cancel property.
* Fix and cache ToolStrip[Item] default font.
* Run fixed layout unit tests.
* Silence the warnings and debug prints in unit tests.
* Update the default colors for ComboBox to match the TextBox.
* Remove superfluous debug prints that are already checked by Assert anyway.
* Make sure HandleCreated event is called for MDI children.
* Do not return zombie handles from CreateWindow, it causes invalid window handles to be sent to X11 functions and lot of noise in the unit test output.
* Do not return zombie handles from CreateWindow, it causes invalid window handles to be sent to X11 functions.
[System.Windows.Forms] Layout fixes
This is accumulation of layout related fixes from https://github.com/filipnavara/mac-playground. Some of the patches were rewritten, small bugs were fixed and it passes the unit tests now.
All the changes are listed in the commits, but the main ones are listed here:
- Rewritten TableLayout, which handles many quirks and unifies the code for GetPreferredSize and the actual layout.
- Fixed FlowLayoutPanel.GetPreferredSize to respect flow breaks.
- Many of the GetPreferredSize implementations fixed to return sensible values. For container controls with default layout the implementation is moved to DefaultLayout and shared.
- Implemented cache for GetPreferredSize that greatly improves the performance for complex layouts.
- Cleaned up implementations of SetBounds, SetBoundsCore and UpdateBounds that improve the performance by reducing the number of re-computations of the same values.
- Moved the calculation of dist_right and dist_bottom for anchor layouts to DefaultLayout.InitLayout.
The Linux build currently just displays "tarball" since we don't
have the .git directory when building the Linux packages.
This allows us to pass environment variables that contain the
branch+commit to the build for generating version.h so we can
show the more detailed info like on OSX.
Same as in https://github.com/mono/mono/pull/6033 to fix the following error on the FullAOT armel/armhf builds:
```
Ran out of trampolines of type 0 in '/home/builder/jenkins/workspace/test-mono-mainline-fullaot/label/debian-9-armhf/mcs/class/lib/testing_aot_full/mscorlib.dll' (limit 9000)
```
Now explicit bounds are only updated in SetBoundsCore, no more all the updating and restoring with UpdateBounds calls.
Rely on the WM_WINDOWSPOSCHANGED message to be sent from XplatUI.SetWindowPos to call UpdateBounds. This avoids an explicit call to XplatUI.GetWindowPos and UpdateBounds in SetBoundsCore.
Fix events triggered in incorrect order when Control.Controls.Remove is called.
Update Dispose behavior with events and exceptions to match the reference implementation more closely.
Rework the layout engines to use AutoSizeInternal property since TextBoxBase has its own AutoSize that should not be respected by layout engines.
Rework automatic sizing behavior of TextBoxBase to return correct values.
Rework TableLayout completely to use same code for layout and calculation of preferred size.
Co-authored-by: Jiri Volejnik <[email protected]>
The Label control has special sizing behaviour that predates the introduction of layout engines in .NET Framework 2.0. In earlier versions of the framework it used to auto-size itself. Now it does it only if it's contained in the default layout engine, otherwise it lets the layout engine do its magic.
* [mcs tests] fix runtime arguments passing to test harness
This fixes a regression introduced by
https://github.com/mono/mono/pull/5484/files#diff-d4a99dd2b7df29f027dae0b3eec6c8e6R193
The change it subtle: Variables are moved into another one, but one
variable got changed from `TEST_RUNTIME_FLAGS` to `RUNTIME_FLAGS`, which
causes the harness not picking up `--interpreter` if set.
* [interp] disable System.Threading.ThreadTest.Test_Interrupt
* [sre-save] Emit a warning if overwriting a MonoClass token with unequal value
It's not clear to me how we could ever have a class without a type_token set
even with a TypeBuilder.
* [sre-save] Use MonoClass getters in sre-save.c
* [sre-save] Change g_warning to g_error in mono_image_fill_export_table
We think this case should not happen.
* [sdks] Move common targets
* [sdks] Have RELEASE be empty when CONFIGURATION != 'release'
* [sdks] Create common runtime compilation template
* [sdks] Use runtime template for Android
* [sdks] Use runtime template for iOS
* Use VSCMD_ARG_TGT_ARCH env in mkbundle on Windows when trying to autodetect target architecture.
Using mkbundle on Windows with VS toolchain, mkbundle will detect target
architecture (x86/x64) by looking at the architecture of executing .NET runtime.
This could lead to some surprises when run from a VS development command propmt setup
to target x86 or x64 but running a mono binary using opposite architecture.
To mitigate this issue mkbundle will look now at the VSCMD_ARG_TGT_ARCH
set in VS development command prompts and use target architecture based
on this env variable. If not defined, current behavior will be used, picking the target
architecture based on executed .NET runtime architecture.
* Updated mkbundle documentation.
* [corlib] Remove IVT for S.R.I.RuntimeInformation facade
The types live in corlib now so we don't need the IVT anymore.
Also removed leftover SR.cs file.
* Bump API snapshot submodule
The original version of this code overwrote the same string over and over
again. Because of the order of operations, when looking for siblings of
Test.dll, we would probe for Test.dll.mdb, then Test.pdb, then Test.pdb.config
(note the last one - should be Test.dll.config).
New version of the code uses fresh strings for each sibling.
Fixes https://github.com/mono/mono/issues/7262
* [sdks] Add armv7s device build.
* [sdks] Disable dtrace on the cross compiler builds.
* [sdks] Avoid building mono-dtrace.h for the cross compilers, its not needed anymore.
* [sdks] Add a configure-mono target.
* [sdks] Put back the call to CheckXcodeDir.
* [sdks] Enable ccache if possible.
* [sdks] Generalize iosDeviceTemplate so it can build the tvos runtime as well. Add tvos device build.
- This is independent of optimization, which is seemingly what we want.
- This does not have bug under optimization that `error` has, that
currently breaks FullAOT builds.
This is an alternative to https://github.com/mono/mono/pull/7353.
Use ifdef GNUC || clang to indicate we know clang is compatible,
and not just depend on clang defining GNUC and being very compatible.
See also https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84628.
* [runtime] Export mono_runtime_get_aotid () for use in the profiler.
* [profiler] Add nanoseconds startup time to file header.
Fixes#6178.
* [profiler] Add a TYPE_AOT_ID event containing the current runtime's AOT ID, if available.
Fixes#6181.
* [profiler] Add Mvid to image load events.
Fixes#6180.
* [profiler] Add generation field to heap object events.
Fixes#6174.
* [profiler] Remove TYPE_SAMPLE_UBIN and some more dead ELF code.
We had a few stubs that threw not implemented exceptions in Dispose()
which causes the finalizer thread to abort.
Since those classes throw in the constructor already there's no way
to create a valid object and we can remove the throw in Dispose().
Fixes https://github.com/mono/mono/issues/7338
This new helper class uses `TaskCompletionSource<>` internally, but instead
of using TrySetException(), it sets a result containing an `ExceptionDispatchInfo`.
The problem with using TrySetException() is that it wraps the exception
object in an `AggregateException`, that would be unobserved if the caller
throws the original exception.
* [System]: Enable some System.Net.Requests tests from CoreFX.
* tests.make: add `$(XTEST_HARNESS_PATH)` to `TEST_MONO_PATH`,
so we can find xunit.assert.
* corefx/SR.cs: add `System.Net.Requests` resources from corefx.
* HttpWebRequest: See below for detailed summary.
* Match parameter names of overridden base class members.
* Fixed order of some argument / state checks to match the
tested behavior.
* Most async methods now throw exceptions instead of returning
faulted tasks when called with incorrect arguments.
* HttpWebResponse.ContentType: use `string.empty` as default.
* WebConnectionStream.FlushAsync: override to return a finished task.
* HttpWebRequestTest.AllowReadStreamBuffering: removed this test.
* test-helpers/RemoteExecutorConsoleApp: silently ignore compiler-
generated helper methods.
Enabled tests from CoreFX:
--------------------------
Added the following tests from external/corefx/src/System.Net.Requests/tests:
* AuthorizationTest, FileWebRequestTest, GlobalProxySelectionTest,
HttpRequestCachePolicyTest, HttpWebRequestTest, HttpWebResponseHeaderTest,
HttpWebResponseTest, LoggingTest, RequestStreamTest, WebRequestTest
Not working yet:
* AuthenticationManagerTest, FtpWebRequestTest
We are currently using
../../../external/corefx/src/System.Net.Requests/tests/*.cs:AuthenticationManagerTest.cs,FtpWebRequestTest.cs
Summary of HttpWebRequest changes:
----------------------------------
* Host - we are now using the implementation from corefx.
* DefaultMaxResponseHeadersLength (unused) - fix default value.
* AllowReadStreamBuffering (unused) - allow this property to
be read/written.
* ContinueTimeout - likewise.
* DefaultCachePolicy (unused) - allow this property to be
read/written and set default value.
* DefaultMaximumErrorResponseLength (unused) - likewise.
* Connection - use implementation from corefx.
* Method - use implementation from corefx, which has additional
error checks.
* MaximumResponseHeadersLength - use implementation from corefx,
adding error checks.
* ReadWriteTimeout - likewise.
* ProtocolVersion - include parameter name in ArgumentException.
* TransferEncoding - use implementation from corefx.
* BeginGetRequestStream / GetRequestStreamAsync / GetRequestStream:
throw exceptions when called with incorrect arguments rather than
returning faulted tasks.
* Disable the corefx tests for the moment.
* Bump API snapshot submodule
* Update tests.make
* [acceptance-tests] Revert part of 1216780e83.
This didn't work as well as I'd hoped.
* [libgc] Export GC_start_blocking () and GC_end_blocking ().
* [libgc] Allow GC_start_blocking ()/GC_end_blocking () to be called unbalanced.
This makes things a bit easier in Mono.
* [libgc] Implement GC_start_blocking ()/GC_end_blocking () for Windows.
* [utils/event] Export the MonoOSEvent APIs for use in the profiler.
* [runtime] Implement thread info flags and get rid of tools threads.
The concept of a tools thread was originally a good solution to the problem of
some internal threads needing to be exempt from stop-the-world. Since they were
introduced, however, we've added more code in the profiler's internal threads
which require certain properties that don't hold true for tools threads. In
particular, we call into some APIs in the metadata layer that, while not
needing the managed heap, do need a domain to be set under certain conditions
(see #6188).
To avoid further complicating the semantics of tools thread by trying to set a
domain for them in a way that doesn't break things horribly, we'll instead do
away with the concept entirely. We already had mono_gc_set_skip_thread () to
flag a thread as being exempt from stop-the-world, which we used in thread pool
threads. This means we already have the infrastructure that is necessary for a
thread to be fully attached to the runtime as a managed thread while still
being exempt from stop-the-world.
So, we do the following:
1. Introduce a set of flags that can be set on a MonoThreadInfo at arbitrary
points (although not in async context). These can indicate that the thread
doesn't want to participate in stop-the-world, doesn't want to receive
sampling signals, etc.
2. Change the thread iteration macros to allow skipping threads with specific
flags set and use this where appropriate (e.g. SGen stop-the-world code).
3. Get rid of mono_gc_set_skip_thread () and make runtime code use the new
mono_thread_info_set_flags () instead.
4. Switch all internal profiler threads to using mono_thread_attach () and
mono_thread_detach (). Use mono_thread_info_set_flags () to disable
stop-the-world and sampling signals for these threads immediately after they
start.
With these changes, internal profiler threads are now fully attached threads
and can call any APIs in the runtime as long as they don't touch the managed
heap.
* [libgc] Add a note about how GC_start_blocking ()/GC_end_blocking () differ from upstream.
* [runtime] Use getters in IS_MONOTYPE()
* [metadata] Add m_class_offsetof_fieldName accessors
These look like:
```c
intptr_t
m_class_offsetof_someField (void) {
return MONO_STRUCT_OFFSET (MonoClass, someField);
}
```
When Mono is compiled with the definition of MonoClass
hidden (--enable-checked-build=private_types),
only the function prototypes are available via
mono/metadata/class-abi-details.h
When Mono is compiled without the checked build flag,
the functions are inlined into that header.
* [metadata] Add accessor function mono_class_set_nonblittable
This is needed by mono_marshal_load_type_info ()
* [marshal] Use m_class_get_ getters to access MonoClass fields
* OpenBSD hasn't have /dev/srandom anymore. See:
https://mastodon.social/@_xhr_/99389358375291806
* Crichton hasn't touched Mono since 2004, per logs. I
doubt they're who to consult about this issue anymore, if
someone somehow does.
* Always enable explicit null checks for AIX
AIX has a "null page" that allows reads (but not W|X) to occur on
*0; allegedly legacy crap for old stupid C programs that poorly
managed string handling. Because of this, we can't catch SIGSEGVs
to give out NREs with - we have to do null checks ourselves. As
such, turn this debug option on all the time; it's seemingly what
other managed runtimes have done, at least according to with what
one contact says.
* Make explicit null checking definable by architecture headers
Turns out other OSes do this too; so best to keep it generic.
To the poor souls on HP-UX and IRIX, good luck!
* Make arch-specific explicit null checks a backend option instead
Don't put ifdefs into JIT code except in that init_backend func;
also make ifdef name consistent with the debug flag name
* Rework the Win32 drag and drop bridge not to depend on Hwnd object.
* Avoid using Hwnd.GetBorderWidth directly.
* Unify GetParent calls to make same sense out of them. They should either consider form owners or not, which wasn't consistent across the XplatUI backends and uses.
Reimplement Control.FromChildHandle using XplatUI instead of relying on Hwnd class.
* Update GetParent parameters.
* Remove direct accesses to Hwnd objects from Control.
* Don't create the Hwnd object in the XplatUIWin32 backend.
* Split handling of Hwnd.GetNextStackedFormLocation for MDI windows into MdiClient to remove dependency on Hwnd objects.
We were previously passing to EH the address to the context that is being set up by the suspend mechanism. This context could get modified while we unwind, confusing EH (could raise `cfa_reg != -1` assertion)
This commit significantly reduces the race window and should mostly avoid crashes (if we get the wrong context we should just fail to invoke clauses from managed)
Don't assert when comparing if an "array special interface" is assignable from
an array.
The code assumed that the special interface is some sort of generic instance
like ``IList`1<string>``, but it could be a generic type definition
``IList`1``.
There is a case where we would be obligated to return TRUE:
If someone used reflection to get the generic param of ``IList`1`` and then made an
array:
```
var i = typeof (IList<>);
var iparam = i.GetTypeInfo().GenericTypeParameters [0]; // returns gparam T
var a = iparam.MakeArrayType (); // T[]
Console.WriteLine (i.IsAssignableFrom (a));
```
But that case is handled by the `MONO_CLASS_IMPLEMENTED_INTERFACE` check,
earlier in mono_class_is_assignable_from.
So we can return FALSE here.
Fixes https://github.com/mono/mono/issues/7095
* [metadata] Fix m_classdef_get_next_class_cache getter to be byref
Apparently the way this field is used is to internally chain cached classes, so
we need its address.
* [metadata] Use MonoClass getters in image.c
* [metadata] Allow debug-helpers to access MonoClass fields directly.
* [metadata] Use MonoClass getters in mono-error.c
* [sgen] Use MonoClass getters in sgen-debug.c
* [sgen] Use MonoClass getters in sgen-client-mono.h
* [metadta] Use MonoClass getters in appdomain.c
* [metadata] Use MonoClass getters in exceptions.c
The mkbundle VS toolchain build has never supported zlib and the -z argument.
Commit adds zlib.lib or zlibstaticlib (depending on use of --static) to the
linker command line when using -z argument.
NOTE, user still needs to make sure zlib.h, zconf.h, zlib.lib or zlibstatic.lib
is visible to cl.exe and link.exe when running mkbundle using VS toolchain.
* [metadata] Create transient ginst during parsing.
Allocate the instantiation types transiently so that they can be freed if
we're going to ultimately discard this MonoGenericInst candidate.
* [metadata] Store GenericParamInfo for anonymous generic params in a cache in MonoImage
The issue is that mono_metadata_parse_generic_param can be called from
mono_metadata_parse_method_signature_full without a MonoGenericContainer which
means we will image_alloc0 temporary MonoGenericParamInfo every time.
This happens, for example in method_from_methodspec in loader.c when we
parse a generic instantiation without having a generic container on hand.
* [metadata] Use MonoGenericParamFull for all generic params
We used to allocate a smaller MonoGenericParam for anonymous generic
parameters. Instead always allocate a MonoGenericParamFull now (which has the
extra MonoGenericParamInfo fields).
As a result, update call sites that checked whether mono_generic_param_info
returned non-NULL to check gparam->owner->is_anonymous instead.
As a fesult of that, update mono_metadata_load_generic_params to create
non-anonymous parameters right away if we know the class or method that will
eventually own them.
* [metadata] Remove anon gparam MonoClass caches from MonoImage
Now that all generic parameters are MonoGenericParamFull and have a pklass
field, cache the class corresponding to a generic param in the struct itself
instead of an external cache.
* [metadata] Remove gshared constraint gparam caches from MonoImage
Now that every gparam is a MonoGenericParamFull, we can always cache the
MonoClass for a gparam in MonoGenericParamFull:pklass.
* [wasm] Enable LTO in release builds. Change packaging to include both debug and release builds.
* [wasm/sgen] Make it possible to disable debug helpers and do so under wasm. Saves 2% on a release build.
* [Tailcall] Add 11 tests. They all run w/o exception or stack overflow, on all platforms.
They are self-checking and report if they were tail called.
All 11 pass on Windows .NET.
2 pass with Mono on Windows or Mac.
CoreCLR not tested as it is a difficult/unknown command line environment.
Mono has problems with at least:
virtual
non-managed pointers
generics
calli
managed references even if not to current frame
Tests originally written in C# and then run through ildasm and perl.
See https://github.com/jaykrell/mono/commits/tailcalltest2.gen.
* [Tailcall] Interpreter fails all tailcall tests.
SvcHttpHandler is supposed to be thread-safe so it shouldn't use plain
Dictionary without additional locking.
The problem is apparent when running test app from issue #7134 with
hyperfastcgi as the following exception sometimes surfaces:
```
[System.NullReferenceException]: Object reference not set to an instance of an object
at System.Collections.Generic.Dictionary`2[TKey,TValue].TryInsert (TKey key, TValue value, System.Collections.Generic.InsertionBehavior behavior) [0x00111] in .../mono/external/corefx/src/Common/src/CoreLib/System/Collections/Generic/Dictionary.cs:441
at System.Collections.Generic.Dictionary`2[TKey,TValue].set_Item (TKey key, TValue value) [0x00000] in .../mono/external/corefx/src/Common/src/CoreLib/System/Collections/Generic/Dictionary.cs:223
at System.ServiceModel.Channels.SvcHttpHandler.ProcessRequest (System.Web.HttpContext context) [0x00048] in .../mono/mcs/class/System.ServiceModel/System.ServiceModel.Channels/SvcHttpHandler.cs:82
at System.Web.HttpApplication+<Pipeline>d__225.MoveNext () [0x008fd] in .../mono/mcs/class/System.Web/System.Web/HttpApplication.cs:1338
at System.Web.HttpApplication.Tick () [0x00000] in .../mono/mcs/class/System.Web/System.Web/HttpApplication.cs:927
```
* Add test for bug 18941
* Expand and update bug 18941 test because there are more problems with our handling of empty structs
* Remove array offset calculation from test because it uses unmanaged sizes. Fix calculation of struct sizes used in marshal struct layout (fixes SizeOf(TestOffsets))
* Correct Marshal.SizeOf implementation to use mono_marshal_type_size instead of returning native sizes
* Remove commented out code
* [sre] Remove S.R.E.FieldBuilder:table_idx field
The field was used in two ways:
1. as the temporary token returned by MemberInfo.MetadataToken
property
2. as a way for sre-save to record the field index in the dynamic assembly.
For (1) we now use the value returned by
ModuleBuilder.GetToken(MemberInfo) (ie a pseudotoken).
For (2) we lookup the field index in the dynamic assembly hash that maps
MonoClassField pointers to indices.
* [sre] Assign consecutive tokens to all fields in a class.
Ensure that a token and a Module are enough to uniquely identify every
MonoClassField.
Because of how metadata is represented in Mono, the fields defined in a
class must have consecutive tokens (because the MonoClass:field.first
and and MonoClass:field.count are used to index into the
MonoClass:fields array).
When the class is created we bump the "next available field token" value
in the ModuleBuilder. Any FieldBuilder objects that are still alive
after the type is created will use RuntimeResolve() to map from their
pseudotoken to the real token.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=33208
* [sre] Change S.R.E.ModuleBuilder.get_next_table_index to take a count
Allow us to reserve more than one consecutive token.
(For now all the callers just have count == 1)
* [sre] Access S.R.E.ModuleBuilder:table_indexes from typebuilder_setup_fields
Use the ModuleBuidler:table_indexes array for assigning tokens to fields
when a TypeBuilder is constructing a type. Also register those tokens
with the runtime so that ResolveMember calls work.
* [test] System.Reflection.Emit.ModuleBuilder field tokens in a module should be distinct
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=33208
* [runtime] Relax assertions in mono_class_{get,set}_first_field_idx
Removed the !klass->image->dynamic check. Classes created by SRE are
of kind MONO_CLASS_DEF and have a first field index.
* Fix issues due to API changes.
* Bump mscorlib version
https://github.com/mono/mono/issues/7200
Three styles:
1. LIBS="$LIBS -lfoo" -- common and probably works
2. LIBS+="-lfoo" -- was here and does not work
3. LIBS+=" -lfoo" -- should work
%p-formatted numbers already include '0x'
Fixes this output when dumping threads:
"Threadpool worker" tid=0x0x7000105cc000 this=0x0x10bc18508 , thread handle : 0x7fbb9e6c6c90, state : not waiting
to become:
"Threadpool worker" tid=0x7000105cc000 this=0x10bc18508 , thread handle : 0x7fbb9e6c6c90, state : not waiting
* [configure] Remove sgen_copying. It's dead.
* [configure] Add sgen_gc_bridge and sgen_split_nursery to the configure flags.
* [configure] Remove more dead configure flags.
* [configure] Par is now just a feature of conc, remove that too
* [sgen] Fix enable minimal for concurrent configuration.
* [sgen] Fix enable minimal for the split nursery.
* [sgen] Use the new enable minimal to compile the bridge code out.
* [wasm] Switch to the new enable minimal flagd and add mono-opt.js build. The new flags save 300k out of 2.8m.
* Fix *setup_async_callback and add *resume_sighandler_ctx on PPC
mono_arch_setup_async_callback didn't work on systems that use
function pointers. For consistency with other backends with
exception support, also add mono_arch_setup_resume_sighandler_ctx,
which we can use to support mono_arch_setup_async_callback, like
those other backends.
Also enable async callbacks on AIX, then enable
*resume_sighandler_ctx on PPC Linux (untested) and AIX. With this,
I can now ^C in the REPL with AIX and have it work; whereas before
it bombed out, with or without async callbacks enabled or disabled.
* Don't configure func descriptors twice, set args reg with user data
* No sense configuring configuring function descriptors if
the restore sigcontext call already set them up. (If Mac
OS supports is verified and added to the ifdef maze, it'd
be safe to remove this whole ifdef, and let the call in
`exceptions-ppc` handle it all, as all supported OSes
would have that call...)
* Set user_data in an arguments register, like what amd64
and z do.
These don't seem to cause any regressions, like the first patch.
* Remove unnecessary case for PPC
* mono_ppc_set_func_into_sigctx is unused now, remove it
* Everyone has MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX on PPC now
* Everyone has MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX on PPC too
mono_threads_is_safepoints_enabled is used to check if cooperative suspend safepoints are enabled, while mono_threads_is_blocking_transition_enabled is used to check if GC safe/unsafe transition are enabled.
* [mini] Change mono_arch_is_inst_imm () to receive the non-imm and imm opcode.
* [mini] Provide a stub for mono_arch_exceptions_init ().
* [mini] No need to define MONO_ARCH_FPSTACK_SIZE on platforms that don't use it.
* [mini] Remove some dead defines from backend headers.
* [mini] Remove the unused dummy_store opcode.
* [mini] Handle dummy init instructions in all backends.
* [mini] Implement live range instructions in all backends.
* [mini] Allocate trampolines from the domain code manager where appropriate.
* [wasm] Add server.py for those that want to experiment with streaming compilation.
* [wasm] Implement System.Threading.Timer.
Timer implementation is done in a somewhat convoluted way.
First, we change Timer to not depend on a scheduler thread.
What we do is call for the runtime to schedule a timed callback to be executed.
Next step, the runtime. We add enough plumbing to get this call to JS.
Finally, in JS we either call setTimeout or schedule it to be run on the next tick.
Oh, wait, timeouts are ignored on non-web environments? Yes, right now its only use case
is offline testing, so ain't no time to wait for all this timeouting.
* [aot] Add hybrid aot tests.
* [jit] Disable partial sharing during JITting, its only been tested in full aot mode, and doesn't seem to work with JITted methods. Fixes https://github.com/mono/mono/issues/7085.
Context: https://github.com/xamarin/xamarin-android/pull/1078
xamarin-android uses `mono-api-html` and `mono-api-info` in order to
perform API comparisons; see e.g. 4e459045.
A recent problem has arisen regarding "inter-API-level diffs": there
are many API changes which we consider to be acceptable, and thus
would like to ignore. Unfortunately, `mono-api-html` doesn't support
ignoring many of these constructs, e.g. base class changes:
<h3>Type Changed: Android.Preferences.CheckBoxPreference</h3>
Modified base type: <span class='removed removed-inline removed-breaking-inline'>Android.Preferences.Preference</span> <span class='added '>Android.Preferences.TwoStatePreference</span>
and property type changes:
<h3>Type Changed: Android.Views.InputEvent</h3>
<p>Modified properties:</p>
<pre>
<div data-is-breaking> public <span class='added added-breaking-inline'>abstract</span> int DeviceId { get; }
</div><div data-is-breaking> public <span class='added added-breaking-inline'>abstract</span> InputSourceType Source { get; }
Overhaul the `mono-api-html` "ignore" infrastructure:
* Introduce ignore "scoping". Previously, the ignore options would
only match the *member* text against any provided regular
expression. Thus, `mono-api-html -r ToString` would ignore *all*
members containing `ToString`. Furthermore, there was no way to
restrict the ignore to a particular type. Expand the regex
semantics so that the declaring type is used as a "prefix" for the
to-be-matched text. For example, if a class `Example` is removed,
`mono-api-html` will now match the following value against any
`-r` regular expressions:
Example: Removed type
* Add a `mono-api-html -v` option, to control output verbosity.
When specified, `mono-api-html` will print out available `-r`/etc.
option values:
$ mono-api-html expected.xml new.xml -v
Possible -a value: Android.Resource: Added fields: public static const int AccessibilityEventTypes;
Possible -r value: Android.Preferences.CheckBoxPreference: Modified base type: 'Android.Preferences.Preference' to 'Android.Preferences.TwoStatePreference'
Possible -r value: Android.Views.InputEvent: Modified properties: public int DeviceId { get; }
Possible -n value: Android.Views.UnavailableException: Added type
...
Additionally, allow `mono-api-html` to take a
`Mono.Options.ResponseFileSource`, which allows `@response-files` to
be used as command-line options.
Althought it was previously defined in a public API header, the macro was not
usable for the last several years since it was implemented in terms of
the MonoClass definition which was not visible in the public API.
There is a subtle semantic change here: mono_type_is_generic_parameter will
return FALSE if it's given a byref type parameter, the previous definition of
the macro would return TRUE. (E.g. if you had "class F<T>" then
IS_INTERFACE("T&") used to return TRUE but will now return FALSE. )
Also
- Move mono_class_set_failure definition to class-accessors.c
- Move a few functions that set up specific MonoClass fields to class-init.c:
- mono_class_setup_has_finalizer
- mono_class_setup_nested_types
- mono_class_setup_supertypes
Some terminals like vt220 don't have a format string for setting foreground
or background colors. In that case, the set*color members of the
TermInfoDriver are set to null and trying to set the background color throws.
Signed-off-by: Kai Ruhnau <[email protected]>
* [profiler] Document addition of MONO_ROOT_SOURCE_EPHEMERON.
* [profiler] Remove dead ELF traversal code.
This was buggy and hasn't been enabled for a long time.
The code uses reflection to access all the fields in the RuntimeFeatures
class. When running the linker we strip out these fields since
they're `const` and the test fails because it can't find the expected values.
Since the linker always removes all constant fields we can't simply
"use" the field in the test and instead we just bail out when encountering this case.
Also used Dictionary instead of tuples for the test since it renders
better in the nunit output.
Fixes https://github.com/mono/mono/issues/7145
* Assorted fixes for AIX and i
* Fix a bug I introduced when changing the MonoArray vector
type; array lengths wouldn't match up to what they
actually were on AIX/i.
* Use a custom mkdtemp implementation on Unices without
mkdtemp - and ones that do but don't necessarily have it,
like i 7.1, which lacks mkdtemp in its libc. We can't
determine this at runtime, so AIX will have to suffer
with i.
* Enhance PowerPC hwcap on AIX to detect features like
Linux does.
* Don't use clock_getres on AIX, because i 7.1 doesn't have
that syscall - it's in libc, but it'll bomb out with a
SIGILL; the way unimplemented opcodes are handled on i.
* Don't use PROT_NONE for hazard pointer alloc when on AIX
AIX and i 7.2 are OK with doing this, but i 7.1 is not and will
SIGSEGV because we violate access privleges; not even mprotect will
change this. As such, change to r/w protection for AIX/i.
* Fix Environment.OSVersion on AIX/i
Before, it would report "Unix 1.0.0.0" due to the fact AIX only
puts the minor version number where other Unices would put the
whole version in uname. Set up an ifdef for AIX and deal with this
semantic difference with a sprintf.
* Disable mffgpr on AIX
Reports of it not working on i 7.1 on POWER7; tester reports
disabling this in hwcap makes it run. This requires further
investigation.
* Fix threadpool errno delivering bogus values with _THREAD_SAFE
We didn't set this, and we need it so that errno is thread-local on
AIX/i. Oops!
* Make suggested changed to AIX branch
* use sizeof (utsname) for sanity's sake
* use a variable for hazard table protection
* match defines for CPPFLAGS -> libmono_cflags
In certain cases of having concurrent WCF requests
HttpReplyChannel.TryReceiveRequest can return true with the context
being null ("at closing phase").
This patch prevents crashing the whole application with a
NullReferenceException as reported in issue #7134.
Whether this is just covering the issue over or a real fix is yet to be
determined.
Fixes https://github.com/mono/mono/issues/7134
Assume a class implementing multiple generic I`1 interfaces. If a virtual call invocation is trying to resolve the correct interface using object O implementing I`1 also , the interface is resolved using a set of rules (not fully implemented in Mono), but a requirement is that the chosen interface is "variant-compatible" with object O, that is its generic parameters are set to the same types.
This last requirement is relaxed as an implementation-specific detail when I`1 is IEnumerator`1, in which case e.g. a virtual call on a class implementing IEnumerator<byte> can happen with an object of type IEnumerator<sbyte> by way of sharing IEnumerator`1 as a generic interface they define. Here, clearly the interfaces are not "variant-compatible", and this is allowed.
Resolution of classes implementing IEnumerator should still attempt to select a compatible interface using the standard rules before attempting to apply this special rule.
This is unnecessary and doesn't really make sense semantically in general as
some targets might define a different arch_target depending on bitness, while
still using the same arch/ subdir.
* Change first parameter of mono_nullable_box from guint8* to gpointer to avoid casts.
* [Coop] Provide object creation functions that return handles
and related. Existing functions are left unchanged
instead of layering over new to allay performance concerns.
Note that there are several variations new_object:
alloc vs. non-alloc
fast vs. regular -- fast does not handle finalization or weak fields and is external only
specific vs. non-specific -- specific is "vtable" and "non-specific" is "class"
"_handle" implies "_checked" if we can get away with it, as conversion continues
mono_gc_alloc_handle_array
mono_gc_alloc_handle_mature
mono_gc_alloc_handle_obj
mono_gc_alloc_handle_pinned_obj
mono_gc_alloc_handle_string
mono_gc_alloc_handle_vector
mono_gc_register_object_with_weak_fields(MonoObjectHandle) (raw "obj" vs. handle "object")
mono_gc_wbarrier_object_copy_handle
mono_nullable_box_handle
mono_object_clone_handle
mono_object_new_by_vtable "_by_vtable" instead of "_specific", and implies handle
mono_object_new_handle "_by_class" implied
mono_object_new_handle_mature "_by_class" implied
mono_object_new_pinned_handle "_by_class" implied
mono_object_register_finalizer_handle
mono_value_box_handle
* Combine mono_object_new_fast and mono_object_new_fast_checked.
Suppose we wanted to use coop handles to implement the following icall:
[MethodImpl (InternalCall)]
extern void GetGenericValueImpl<T> (int idx, T out value);
The question is: how should we pass the argument "value" to the C code?
If it was a reference type like "string" , we would use a coop handle:
void ves_icall_GetGenericValueImpl_string (gint32 idx, MonoStringHandleOut value, MonoError *error);
But if it was a valuetype, we would instead pin the memory with an interior
handle and pass the raw address:
void ves_icall_GetGenericValueImpl_int32 (gint32 idx, gint32 *value, MonoError *error);
But we don't have two different implementation on the C side - there's just one
icall - we have to choose a single mechanism.
So the mechanism we choose is to treat all the args like valuetypes - pin the
memory in the wrapper and pass a raw pointer to the C side.
The other troubling possibility is if someone writes:
[MethodImpl (InternalCall)]
extern void BadInternalCall<T> (Something s, T bad);
Now we really don't have any options. So we just assert that noone ever writes
such a call.
On interp we can't async abort since we cannot unwind from an ip in the interp, so the interpreter does explicit checks as part of branch instructions.
Note this can lead to increased stack usage when compiling with -O0.
* [offsets-tool] Add an '--output' argument to specify the output file directly instead of generating it from the target triple.
* [sdks] Add targets for the watch cross compiler.
* [mkbundle] Automatically bundle config files and machine.config files for the simple/cross compiler scenario, fixes one of the missing issues for #6230
When using the interp_wrapper to enter interp from native we don't need to save the lmf since it doesn't make sense to unwind to native. Also make sure we have the interp context set up if we weren't attached at interp transition time.
While Mono does copy the values of arrays back when they are marshaled
to unmanaged code, .NET does not seem to be doing this, and manifests
as the Syscall.poll invocation in Mono.Posix with .NET Core does not update
the values in the provided array.
The following example should print "Got 1 and 1" with the following command:
```
echo foo | dotnet run
```
But instead prints 0 and 1 on .NET Core, but the correct result with Mono.
This patch is going here for the sake of the Mono.Posix.NetCore package that
we publish.
Sample:
```
using System;
using System.Runtime.InteropServices;
class X {
private struct _pollfd {
public int fd;
public short events;
public short revents;
}
[DllImport("libc")]
static extern int poll ([In,Out]_pollfd[] ufds, uint nfds, int timeout);
static void Main ()
{
var p2 = new _pollfd [1] { new _pollfd () { fd = 0, events = 1 } };
var m = poll (p2, 1, -1);
Console.WriteLine ("Got: {0} and {1}", n, pollmap [0].revents);
Console.ReadLine ();
}
}
```
* [runtime] Unboxing of nullable enums should throw for boxed ints. Fixes gh #6666.
For some reason, one can't unbox the underlying type of an enum into a nullable.
This is counter intuitive to the unboxing rules of enums, but it's what dotnet does.
* [interp] Unboxing of nullable enmus should throw for boxed ints
fixes https://github.com/mono/mono/issues/6666 for the interpreter
Ensure that the callback to mono_domain_foreach_safe can actually do stuff with the domain argument like running code.
This new function make it possible to do so safely, unlikely the previous one.
This ensures that the process exit callback has a shot of correctly executing on domains racily being unloaded.
The ProcessExit event is fired before the threadpool is shutdown, so we can leverage that to run them
with a timeout.
The timeout is 3 seconds per appdomain. It could be improved by making that global to all domains if that
ever becomes an issue.
MonoError is simplified for MME by having the error message eagerly created, which simplifies things A LOT.
Managed Exception creation is simplified by only setting Message, as it's done by other runtimes.
* [mini] Fix mini_emit_memory_copy_internal with ref types and remove workaround from mono_method_to_ir
* [mini] Remove unused argument and rename function to better reflect its use.
* [utils] Fix swapped member and signature fields in error message.
* [runtime] Simplify MME by only setting the message field since ClassName/MemberName don't need to be set.
* [runtime] Add mono_error_set_method_missing to exceptions.c and collapse setting MME to a single function.
This implements the cleanup discussed in the PR.
* [runtime] Cleanup MonoError for BadImageFormatException.
Move mono_error_set_bad_image & mono_error_set_bad_image_name to exception.c.
Rename mono_error_set_bad_image_name to mono_error_set_bad_image_by_name.
Introduce mono_corlib_exception_new_with_args to be used when creating exception objects.
It's easier to consume than mono_exception_from_name_two_strings_checked as it takes string arguments as char*.
Fix usage of mono_error_set_bad_image_by_name to never dup the supplied image name as the callee does it.
Fix some empty error messages.
Finally, reduce the cruft in mono_error_prepare_exception by using the new exception creation function from above.
* [runtime] Cleanup MonoError of FileNotFoundException.
Move it to use the generic first_argument and make it a simple error - IE, get_message doesn't format anything.
* [runtime] Rework MonoError for MissingFieldException.
* Fix build issues
* [runtime] Ensure memory is freed using new MonoError set functions.
When unboxing nullable we call Nullable.Unbox which returns the valuetype, but CEE_UNBOX needs to return an address to it. Therefore we store the result in a local in the frame so we can get its address.
* [mini] Fix mini_emit_memory_copy_internal with ref types and remove workaround from mono_method_to_ir
* [mini] Remove unused argument and rename function to better reflect its use.
* Fix gshared support for default interface methods by always passing an mrgctx to them.
This is needed because these methods can be part of more than one inheritance hierarchy or
be present more than once in the same inheritance hierarchy so its not possible to
assign rgxtx slots to their gshared entries that would work in all cases.
* [jit] Add a mini_method_is_default_method () helper function.
Fix a regression introduced in the new web stack - when connecting
to a DNS host name that resolves to multiple IP addresses, we need
to probe them all.
On iOS, "localhost" will resolve to both "::1" and "127.0.0.1".
* [runtime] Make icall tables loadable.
Move the icall table code into a separate icall-table.c file, which is either linked into libmono or compiled into a
separate libmono-icall-table.a archive which can be linked into an app, and installed by calling mono_icall_table_init ().
* Change ClCompile to ClInclude for new .h file.
We must not push one vararg at a time since the alignment of the argument is not the same as the alignment of a value type in interp (which is always 8)
Detect conflicts caused by diamond inheritance during vtable construction, and throw an exception when a conflicting
methods is called.
Disable generic sharing for default interface methods, it doesn't work yet, probably
because these methods are called on classes, but the gshared information is associated with the interface.
Enable dim-diamondshape.exe test.
Setting ReadTimeout in WebResponseStream.ctor throws System.Net.Sockets.SocketException : Invalid arguments on iOS.
Set it in WebConnection.InitConnection() immediately after establishing a connection, before we read/write anything.
* [jit] Simplify some gshared code by calling mini_method_get_rgctx () in more places, make mono_method_lookup_rgctx () static. NFC.
* [jit] Get rid of the 'method' argument to emit_get_rgctx (), it should always be equal to cfg->method. NFC.
.. process. Version from:
https://github.com/dotnet/cli/blob/501e11d928c21608999c934f0a7078570b688c6c/build/DependencyVersions.props
```
<MicrosoftNETSdkPackageVersion>2.1.0-preview1-62414-02</MicrosoftNETSdkPackageVersion>
<MicrosoftNETBuildExtensionsPackageVersion>$(MicrosoftNETSdkPackageVersion)</MicrosoftNETBuildExtensionsPackageVersion>
```
Also, update the list in the runtime and deniedAssembliesList.txt
installed for use by msbuild.
.. assemblies.
This is specifically required for handling .net assemblies in
`Microsoft.NET.Build.Extensions` nuget which don't work on mono. These
assemblies are bundled with msbuild and we want to be able to deny these
at runtime.
* [configure.ac] Add --enable-checked-build=private_types option
The idea is that when private_types is turned on, we will hide the definitions
of various structs in Mono and only allow access via getter/setter
methods.
If private_types is off, those same getters would be static inline functions
and also the struct definition would be visible (to allow for incremental
conversion of existing code).
* [metadata] Move _MonoClass definition to class-private-definition.h
* [metadata] Define a getter for every MonoClass field
in a checked build, the getters are just declared in class-internals.h and
defined in class-accessors.h
in a non-checked build, the getters are static inline functions in class-internals.h
For a field foo of type FooType define
FooType m_class_get_foo (MonoClass *klass) { return klass->foo; }
The exceptions are fields that are embedded structs, e.g. MonoType byval_arg,
for those we return a pointer to the field instead of a copy:
MonoType * m_class_get_byval_arg (MonoClass *klass) { return &klass->byval_arg; }
* [metadata] Rename MonoClass boolean getters to use is/has names
instead of the string m_class_get_fieldname pattern
- m_class_is_inited
- m_class_is_size_inited
- m_class_is_valuetype
- m_class_is_enumtype
- m_class_is_blittable
- m_class_is_unicode
- m_class_was_typebuilder
- m_class_is_ghcimpl
- m_class_has_finalize
- m_class_is_delegate
- m_class_is_gc_descr_inited
- m_class_has_cctor
- m_class_has_references
- m_class_has_static_refs
- m_class_has_no_special_static_fields
- m_class_is_com_object
- m_class_is_interfaces_inited
- m_class_is_simd_type
- m_class_is_has_finalize_inited
- m_class_is_fields_inited
- m_class_has_failure
* [metadata] (class-internals.h) Use m_class_get_ getters
* [metadata] (class-inlines.h) Use m_class_get_ getters
* [metadata] (class-accessors.c) Use m_class_get_ getters; setters not done
The setters are not converted.
Ultimately, I think that will sort itself out - a few of them are only used
from SRE and from MonoClass construction - we will eventually provide setters
for just two places and hide them elsewhere.
When doing a vararg call we push on the vtstack the current call signature followed by the params. The child_frame will have a pointer to this memory on the parents vt_stack from where it can linearly access the varargs using the same ArgIterator logic.
Use `git blame -C10 mono/metadata/class-init.c` to see attribution for most of the old code.
This PR comprises:
* [metadata] Move (some) MonoClass construction to class-init.c
So far moved MonoClassDef, MonoClassGtd and MonoClassGenericInst construction
functions.
The idea is to eventually isolate functions that needs write/setter access to
MonoClass fields in a separate translation unit and make MonoClass opaque and
only accessible via getters everywhere else.
* [metadata] Move pointer MonoClass creation to class-init.c
* Mark mono_ptr_class_get as external only, runtime should use
mono_class_create_ptr.
* [msvc] Add mono/metadata/class-init.c (and .h) to the .targets file
* [metadata] Rename mono_generic_class_get_class
to mono_class_create_generic_inst
* [metadata] Move array class creation to class-init.c
* Mark mono_array_class_get external only, runtime should use
mono_class_create_array
* Mark mono_bounded_array_class_get external only, runtime should use
mono_class_create_bounded_array
* [metadata] Move generic param creation to class-init.c
* Also move mono_class_setup_vtable_general, mono_class_init_sizes, mono_class_setup_methods
* [metadata] Move mono_class_setup_basic_field_info to class-init.c
* [metadata] Move mono_class_setup_fields to class-init.c
* [metadata] Rename mono_class_from_generic_parameter_internal
to mono_class_create_generic_parameter
* [metadata] Move mono_class_layout_fields to class-init.c
* [metadata] Move mono_class_setup_{properties,events} to class-init.h
* [metadata] Move mono_class_setup_interfaces to class-init.c
* Also move mono_class_setup_mono_type
* [metadata] Move mono_class_setup_parent to class-init.c
* [metadata] remove some extern statistics
* [runtime] Add a 'frame_addr' field to MonoStackFrameInfo, which is equal to either interp_frame or ctx->sp.
Use this field to compare frames with each other or with stack addresses instead of setting ctx->sp to
the interp frame address, which breaks mixed mode, since mixed mode assumes ctx->sp is the real
sp of the last native interpreter frame.
* [ci] Reenable mixed mode tests.
* [System]: WebResponseStream now correctly reads the chunk trailer when using gzip/deflate.
This should actually fix bug #59779.
* Add missing ConfigureAwait(false)
* Get autotools scripts for Mono and Boehm to recognize i
PASE is most similar to AIX, and perhaps I assume other commercial
Unices, as well as PowerPC Linux, so grab variables from them as
needed.
With this, we get glib failing to build due to missing mkdtemp.
* Use better cpp definition to grab more of what we want
* Fix random and 64-bit file offset support
* Set TARGET on IBM i on POWER
* Add hack to gfile-unix.c to work around flawed AIX header
From comment:
/* HACK: the preprocessor will not give us mkdtemp no matter
what and Mono (for good reason) does
"-Werror-implicit-function-declaration" so we error out;
instead declare mkdtemp here; the linker will find mkdtemp
anwyays. libuv has had similar issues, but they just ignore
the compiler warning instead of failing on it.
See: github.com/libuv/libuv/pull/740 */
* Work around missing definition on AIX/PASE
* Fix conflicting definition from due too AIX headers
* Initial work to get JIT working on AIX
* uncertain about NIP; is IAR the right register? need review from
PPC asm people
* needs calling convention work; AIX does NOT use ELF
* Fix lack of casting on sigcontext macros, fix errnos for AIX
* AIX doesn't distinguish between ENOTEMPTY and EEXIST without a
define. Handle this case with a conditional cpp directive..
* When ctx is a void pointer, dereferencing as a struct will fail.
Handle this case with a cast.
* Handle regular AIX as well as PASE
* Implement stack boundaries check for AIX, volume info func
* vol info should be like other Unix, just needs to bridge ifdef
* highly uncertain for the bounds checking, needs further review
* Fix typo in mono/utils/mono-threads-aix.c
* In boehm-gc.c, don't use pthread_getattr_np on AIX even if available
It's not available on IBM i, and even if available, toolchains for AIX
may "helpfully" swap out system headers with variants that remove
functions like pthread_getattr_np.
* Don't use "-export-dynamic" on non-GNU ld
IBM ld considers "-e" to be a flag for setting the entry point.
Detect non-GNU ld, and offer equivalents when possible.
The makefile in mini had to be changed as a result due to
hardcoded flags.
* Use pthread-stop-world.c on AIX
Remove an ifdef that gated this off to AIX. It seems the old AIX
specific files shouldn't be used, and that the changelog for libgc
says pthread should work fine on AIX instead; yet it was blocked.
Restore this, as it compiles and seems to let mono-boehm link fine.
* AIX workarounds for some of support dir
* fstab on AIX is there, but defines a struct more like other
platforms' checklist struct.
* AIX, like macOS and some BSDs, doesn't define some serial types.
* psignal is another victim of GNU; even then it isn't in PASE
headers anyways
* More support workarounds for AIX headers
* Replacement function body for syslog2 on vsyslog-less platforms
AIX lacks vsyslog; detect in autoconf and act appropriately.
* Final support hacks for AIX
* Fix problematic stack management on AIX
this gets us past ifdefs, after much handwringing
* get the right end of the stack; r1/stack pointer is on the wrong
end and ustk is just plain broken
* AIX doesn't seem to like the semantics of the mmap call valloc
does here; either we're allocating into an area we shouldn't be
or we're not passing the right flags. Until then, learn to live
without the stack guard?
* Disable Boehm GC on AIX
Focus on getting SGen working, and avoid legacy debugging nonsense
* Remove AIX ifdef-undef and replace with s/hz/uhz
* Don't use sigaltstack on AIX due to bugginess with guard sections
The valloc call on AIX has issues after issuing mprotect; don't do
do it. I believe it fails because we aren't issuing the right
flags on AIX, or because we're allocating inside of an already
allocated area.
* Perform a 64-bit build on AIX
We still crash at the same place, but probably for the best that
we switch to 64-bit. (Maybe we could make it configurable?)
* Fix func descriptor ifdef, add initial (likely wrong) defs for AIX
* AIX doesn't define __powerpc64__ or __ppc64__ when compiling as
64-bit. Use an alternate ifdef, and shuffle around that ifdef
anyways, as it could lead to wrong results on other platforms
too.
* AIX likely needs special definitions, especially on 32-bit. The
calling convention is closest to PPC64BE Linux, but not exactly.
* Fix stack size on AIX
Ruby dealt with this before: https://github.com/ruby/ruby/commit/a2594be783c727c6034308f5294333752c3845bb
* Set up initial PPC hwcap for AIX, fix ftnptr ifdefs, tweak AIX defs
* Fix hwcap to use better values on PPC AIX
Still needs more adjustment though
* Fix alignment issue on AIX, tweak mini-ppc values just a bit more
* On AIX, doubles are always aligned by 4 if they're in structs.
Since we need to have them aligned by 8 on 64-bit, this is bad,
so change the type on AIX.
* We can use this definition on AIX
Now we can bootstrap Mono!
* Shuffle MonoArray ifdef per suggestion of @vargaz
* Fix System.Decimal division on big endian systems
Before, we got non-sensical overflow on things like
`(Decimal)Int32.MaxValue / 1000`; now they get the same value,
comparing this POWER6 running AIX to my server's output running
OpenBSD/amd64.
* Fix dynamically linked build of Mono on AIX
nm wasn't seeing 64-bit symbools as it defaults to 32-bit mode,
also never try to use GNU nm
* Fix PPC64 define in mono-config
Interestingly, there was an AIX define already present, and that
definition is present in AIX's passed includes, so continue to use
it.
* Don't use __thread even if detected on AIX
tl;dr: The assembler gets angry with __thread and minimal-toc, and
changing options to replace minimal-toc causes linker issues; this
TLS option isn't important anyways if we have pthread instead,
like before when we were using Perzl's old GCC without __thread.
* Get lib.a(lib.o) type archives working with P/Invoke for AIX
AIX libraries are very, very strange compared to other Unices.
I'm not entirely sure if this is correct or optimal; it may need
to special case further. For now, it's enough to get gacutil
up and running.
Some resources I found useful for this charade:
<http://stromberg.dnsalias.org/~dstromberg/AIX-shared-libs.html>
Also set libc and libintl to their proper values.
* Scheduling priority hack for i
PASE doesn't accept anything other than SCHED_OTHER, and the funcs
for getting min/max don't work either. AIX suffers, but only a
little bit.
* Final polish on request
Remove Boehm changes if we don't use Boehm, tweak some defines,
remove some externs, tweak autoconf file
* Be aware of ERESTART, on OSes that use it
Instead of EINTR/EAGAIN, AIX uses ERESTART. Handle this, so things
like xsp are less chatty when performing async IO.
The `label` environment variable is set by Jenkins based on the
chroot/node configuration a given job is using.
This crept into the CI scripts while it should have been a
separate concern and caused all sorts of issues when we bumped
from e.g. debian-8-* to debian-9-* in some jobs.
Instead we should consistently use the CI_TAGS env var which we
control exclusively.
* [sdks] Fix build for llvm
* [sdks] Have .stamp-%-configure always depend on .stamp-%-toolchain
* [sdks] Dependencies on directories should always be order-only
This commit implements checking whether the compiler used to build mono supports
the recently added switches to generate code designed to mitigate the effects of
the Spectre/Meltdown bugs of the modern CPUs (https://meltdownattack.com/).
As of this commit the options are implemented for GCC 8.x, 7.3 and backported to
some older versions of gcc 7.x (e.g. in Ubuntu). The options tested for, and
used, here are:
-mindirect-branch (https://gcc.gnu.org/onlinedocs/gcc-7.3.0/gcc/x86-Options.html#index--mindirect-branch)
-mfunction-return (https://gcc.gnu.org/onlinedocs/gcc-7.3.0/gcc/x86-Options.html#index--mfunction-return)
Checks and usage of the above flags is hidden behind the
`--with-spectre-mitigation` configure option, defaulting to `no`.
Two additional options are implemented to specify the kind of thunk to implement
by each of the flags above:
--with-spectre-indirect-branch-choice=keep,thunk,inline,extern
Convert indirect branches to the specified kind of thunk (defaults to inline)
--with-spectre-function-return-choice=keep,thunk,inline,extern
Convert function return instructions to the specified kind of
thunk (defaults to inline)
The CoreFX version has a few error checks which are not in the
referencesource, switching to CoreFX allows us to enable their tests.
Use Path.GetRandomFileName() and Path.GetTempFileName() in tests.
We are now using nested streams to take care of buffering, chunked encoding and automatic decompression.
GZip / Deflate decompression have been moved inside `WebResponseStream`, the `HttpWebResponse` now always returns a `WebResponseStream` (and not a `GZipStream`) because we have to do extra book-keeping after reading the entire content.
Returns TRUE if the method flags indicate that it's not expected to have a
body because it is abstract, a PInvoke, an internal call or a
runtime method.
* Print combined stdout and stderr in console output.
* Print the RNG seed used for a test run on startup and in the test report.
* Set the individual test timeout back to 6 hours.
* Use the nodefaults profiler option.
* Allow configuration through environment variables:
- MONO_PROFILER_STRESS_OPTIONS: Specify a set of profiler options to use
instead of the randomly generated ones.
- MONO_PROFILER_STRESS_REGEX: Specify a regular expression to filter which
tests should be run.
- MONO_PROFILER_STRESS_SEED: Specify the RNG seed. Useful for reproducing full
test runs at a later point.
- MONO_PROFILER_STRESS_TIMEOUT: Specify a different individual test timeout
from the default.
it has the right logic to avoid this:
```
ld: -undefined and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together
```
i.e. setting `-no-undefined`. However, this requires that we link
against `libmonosgen` on those platforms.
We've been using a certain pattern for the Windows .msi for a long
time but the build output used a different name which we simply
manually renamed before publishing.
Since we want to automate as much as possible we can change the
build to produce the correct name right away.
For mono_thread_get_undeniable_exception to work, it needs to unwind the stack and find the first managed frame. This is only possible if we push an interp LMF with a frame for the interp to native transition.
During interp frame unwinding, we were initializing the sp field (to the corresponding interpreter frame) starting with the parent frames of the first interpreter frame.
Debugger maintains it's own list of loaded classes. The unload/filter
logic does not handle composite types like arrays and generic instances.
Expose and reuse the logic from metadata that properly detects any
usage of an image within a type.
This prevents the cache from containing MonoClass values which have
already been freed by the metadata cleaning code.
* Minimal fix to Authenticode infrastructure to understand PE32+.
A number of other problems are noticed in the code but commented only.
This fixes https://bugzilla.xamarin.com/show_bug.cgi?id=56071
* Induce many array out of bounds accesses, and some other error paths.
* Tweaks.
* tweak
* Move braces, move addition, document constants and use them.
* whitespace
* fix comment
* remove diff-minimizing hacks
* cosmetic
* move braces and assume zero-initialization; adjust comment.
* improving Makefile but still a ways to go
* fix C# indent
* Change from C++ to C, and cleanup Makefile.
* update clean target in Makefile
* cleanup Makefile and C#
* remove test code that people don't like and it wasn't very useful
wordsmithing and new good information in comments
* Fix indentation
When an exception is thrown from jitted code, the EH mechanism correctly sets the interp resume data to the right interp frame that should catch the exception, but it resumes to the interpreter by force, setting the MonoContext. This context has invalid data (for example the SP points to a InterpFrame and it is not the real sp at interp exit)
This bug was exposed by inlining changes from d3763c6c1e
* Move machine handling of performance counters from native
to managed -- just slightly less native code therefore.
* PR feedback: Rename ValidMachine to IsValidMachine.
Use string::operator== instead of .Length/[].
Change InstanceExistsInternal to return bool/MonoBoolean directly instead of int.
Remove question mark on FIXME comment for more reliable grep.
Remove redundant zeroing of a pointer.
Also add two more variants
* mono_error_assert_msg_ok (err, msg) to print "msg, due to <err>" on failure
* mono_error_assertf_ok (err, fmt, args...) to print
"<formatted args>, due to <err>" on failure.
Avoid inlining some functions with high stack frame locals usage (ex functions that use MonoLMFExt which is a big structure).
No performance cost was observed on microbenchmarks, while stack usage decreased by over 3 times on amd64 and over 4 times on arm.
Give it 2.5 seconds.
https://jenkins.mono-project.com/job/test-mono-pull-request-amd64/10727/parsed_console/log.html
Tests run: 120, Passed: 119, Errors: 0, Failures: 1, Inconclusive: 0
Not run: 0, Invalid: 0, Ignored: 0, Skipped: 0
Elapsed time: 00:00:32.8320000
Errors and Failures:
EndBuildWaitsForSubmissionCompletion (MonoTests.Microsoft.Build.Execution.BuildSubmissionTest.EndBuildWaitsForSubmissionCompletion)
#5
Expected: less than or equal to 00:00:02
But was: 00:00:02.0757916
at MonoTests.Microsoft.Build.Execution.BuildSubmissionTest.EndBuildWaitsForSubmissionCompletion () [0x00126] in /mnt/jenkins/workspace/test-mono-pull-request-amd64/mcs/class/Microsoft.Build/Test/Microsoft.Build.Execution/BuildSubmissionTest.cs:105
at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in /mnt/jenkins/workspace/test-mono-pull-request-amd64/mcs/class/corlib/System.Reflection/MonoMethod.cs:305
Split mono_method_get_header_checked into internal and external forms. (#6609)
External form is mono_method_get_header_checked, the preexisting name.
Internal form is mono_method_get_header_internal.
External must initialize the MonoError for compatibility, internal can/should assume it is already initialized per the new pattern.
* g_assert should be an expression not a statement; provide g_assertf f is format like printf
- g_assert should be an expression, not a statement
ANSI C assert gets this correct, and I corrected
widely used NT ASSERT circa 2001 with no ill effects
Note that ANSI C assert is void, g_assert here is boolean.
- provide g_assertf
f is for format, like printf -- too terse?
Where you might previously say:
if (!(expr))
g_error(...); // like printf
now:
g_assertf(expr, ...)
Manual tests provided -- how to provide a test whose success is failure to compile?
Correct existing eglib/test to build and pass, but don't enable in build.
Enabling it is a line in toplevel configure.ac to add eglib/test/Makefile
after eglib/Makefile.
* Fix comment in test code.
* format with s instead of hs
* review
* [WASM] Fix System.Core issues and disable broken tests.
* [wasm] Fix cookie computation heap overflow. Use a local to make it thread safe.
* [wasm] Disable System tests that don't work under WASM. Change the wasm profile to disable BSD sockets.
* [wasm] Address reviewer feedback.
* [wasm] Disable test that requires multiple threads.
* [wasm] Add package target to wasm.
* [wasm] Modify the runner to exit(1) if the test suite fails.
* [wasm] Add CI configuration for WebAssembly.
* [wasm] Fix issues found over review.
* [runtime] Export mono_class_get_checked () for use in profilers.
* [runtime] Expand mono_method_get_header_summary () to collect more info.
It now collects all the trivially-accessible header data that doesn't require
chasing down other metadata.
* [profiler] Use mono_method_get_header_summary () in the coverage code.
We only need code start and size information, not all the data that is present
in the header. By switching to this function, we avoid all the side effects
that come with resolving local variables and exception clauses (which can even
result in loading assemblies in the worst case).
* [profiler] Write out all uncovered classes/methods in a loaded image.
Fixes: https://bugzilla.xamarin.com/show_bug.cgi?id=60225
This required a bit of refactoring and some workarounds for various special
cases. This also fixes some race conditions with respect to how data was
inserted into the lock-free hash tables and queues.
In c7d8d247c3 I unified how we're
passing -arch in CFLAGS to "-arch=XXX" since the original change
in 63a49e9eb8 mixed the formats.
Turns out the correct syntax is "-arch XXX" instead and it broke
the ccache build in bockbuild because it complained about the
unknown format.
Also add LDFLAGS in the amd64 case to match what we have in bockbuild.
When we had a jit info table for aot images loaded in the domain, we would queue jit infos for freeing at domain unload time. This means leaking during entire application life.
Add comment for jit info freeing when having multiple tables.
Fixes#60986.
This cute hack allow us to cut the budget of perf irrelevant blocks[1] while massively boosting those that are perf relevant[2].
It has a ton of missing features, like it doesn't detect nested loops, it doesn't take hints from inlined methods and it doesn't compute EH info.
Beyond that, inlining budget is all but horrible, so there's ton of room for improvement here.
Results are promising.
A marginal improvements in benchmarks like Roslyn (2% user) while as much as 30% in micro benchmarks where the now bigger methods are in loop bodies.
Code size with Roslyn changed from 5433242 to 5501751, IE extra 68.5k, or 1.2% more.
[1] those ending in throw or in a catch handler
[2] Loops
we return the address of the StackOverflowException object in
`restore_soft_guard_pages`, so it ends up in the architecture specific
result register (e.g. %rax) where the exception handler expects it.
fixes https://bugzilla.xamarin.com/show_bug.cgi?id=60862
* [test-runner] Record test duration in NUnit xml
This allows us to keep track of the time on Jenkins.
Also fix issue where we were recording .Seconds of a TimeSpan instead of .TotalSeconds.
* [tests] Bump timeouts in process-stress-?.exe runtime tests
We're seeing these fail sometimes on Linux Azure VMs, let's try
if bumping the timeouts helps.
* [class] Add Obsolete message to ICSharpCode.SharpZipLib.dll
Users should use the nuget package instead, we'll remove the assembly in Mono 6.0
Don't install it into the 4.7.1 reference assembly directory anymore.
* Bump API snapshot submodule
* [runtime] Allow access to protected default interface methods from classes which implement the interface.
* [interp] Add some automatic conversations between virtual and non-virtual calls that .net has. Fixes dim-valuetype.il.
* [bcl] Sort the MethodImpl table in PEAPI.
* [runtime] Enable dim-methodimpl.exe test.
* [runtime] Fix vtable construction tracing.
* [interp] Fix null checks on the receiver when converting virtual calls to non-virtual.
Rationale:
1. it asks for double faulting scenarios we can't do anything about
it anyway, exception just unmap yet another page
2. `mprotect(2)` behaves weirdly (at least on macOS) if you try to
change permissions for subsequent pages with different permissions.
With the previous code it happened that the requested memory range
would go from somewhere in the stack guard and overlap into the
regular, unprotected stack and end up with unpredictable behaviour.
We could be more careful about it, but it would complicate things
even more.
no longer needed. It remains only for register_icall.
Remove casts from void* to HANDLE, as HANDLE always and forever
will also be void*.
Add comments explaining the valid use of INVALID_HANDLE_VALUE (-1).
With CreateFileMapping, for the file handle, it means to
use physical memory / pagefile.
Previously, we tried to keep the intern status of a string consistent across domains. Meaning
that if you interned "FOO" in domain 0, it would return true for String.IsInterned in domain 1.
This behavior exists in the CLR because the string table is shared between domain as string are
what they call agile objects - those that can exit in multiple domains at the same time.
Mono appdomain isolation doesn't work that way and there's not visible advantage of keeping that property.
The reason for this change is to potentially reduce the amount of interned strings and, more importantly,
reduce the amount of domain lookups, which are quite expensive and unsafe.
This should speed up interning queries.
Follow up to https://github.com/mono/mono/pull/6431, we should
capture the exception that is passed to the methods.
Copied the SetResult() method that referencesource uses.
* [mini] factor out interp into a library
It enables us to ship the interpreter as an add-on to the runtime.
Embedder can statically link it into their application on demand.
Usage:
configure mono without the interpreter, such as:
```
$ ./autogen.sh --enable-minimal=interpreter ...
$ make; make install
```
run your favorite program with the interpreter and see it fail:
```
$ ./mono/mini/mono-sgen --interpreter ./mono/mini/basic.exe
Mono IL interpreter support is missing
```
despite `--enable-minimal=interpreter`, we can still build the interp
module:
```
% make -C mono/mini libmono-ee-interp-static.la
CC interp/libmono_ee_interp_static_la-interp.lo
CC interp/libmono_ee_interp_static_la-mintops.lo
CC interp/libmono_ee_interp_static_la-transform.lo
CCLD libmono-ee-interp-static.la
```
`libmono-ee-interp-static.a` can be statically linked into the target
application.
* [fixup] include libmono-ee-interp reference in runtime unit-tests
* [runtime] Mark mono_class_get and mono_class_get_full external only.
Runtime should use mono_class_get_checked and
mono_class_get_and_inflate_typespec_checked, respectively.
* [runtime] Mark mono_ldtoken external only
Runtime should use mono_ldtoken_checked
* [metadata] Mark mono_type_create_from_typespec external only
Runtime should use mono_type_create_from_typespec_checked
* [runtime] Remove mono_class_inflate_generic_method_full.
Mark mono_class_inflate_generic_method external only.
Runtime should use mono_class_inflate_generic_method_full_checked.
* [runtime] Mark mono_get_inflated_method external only
This function is obsolete. It should have no callers.
* [metadata] Mark mono_field_from_token external only
Runtime should use mono_field_from_token_checked
* [runtime] Add MonoError arg to mono_class_get_inflated_method
* [metadata] Mark mono_metadata_parse_method_signature external only
Runtime should use mono_metadata_parse_method_signature_full
* [metadata] Mark mono_metadata_interfaces_from_typedef as external only.
Runtime should use mono_metadata_interfaces_from_typedef_full
* [mini] Add MonoError arg to mono_class_get_method_generic
Also move its declaration from metadata/class-internals.h to mini/mini.h
since it's defined and used in mini/
* [class] Assert that mono_class_get_inflated_method never returns NULL
* [interp] Add missing param support for floating types in interp_entry
Remove some duplicated code
* [interp] Reenable thunks.exe on arm
It fails due to the known RGCTX register clobbering by trampolines.
* include netinet/in.h for in_addr_t
* there is no need for an openbsd specific implementation anymore
so you use the generic pthread one
* signal.h is required for sigaltstack
* add missing mono/utils/mono-threads.h include
* there is no malloc.h on OpenBSD either
* sys/socket.h is required for struct sockaddr
* add support for btls on openbsd and default to with_tls=pthread as there is only emultls support which is not enough for mono
* there is no need for pthread_attr_init/destroy anymore
* add -Wl,-zwxneeded to LDFLAGS on OpenBSD
W^X is strictly enforced by default on OpenBSD;
a program can only violate it if it is located on a filesystem mounted
with the wxallowed mount(8) option and has been linked with the
above flag
Since object-internals.h is included in a ton of places, we get one Centrinel warning
about mono_internal_thread_handle_ptr per translation unit every time the
header is included which is ridiculously noisy.
This commit will suppress the warning about the body of this function.
Note that uses of the function will still get a warning since it returns a
MonoInternalThread* and we haven't yet taught Centrinel that those calls are ok since
the thread object is pinned.
Otherwise we'd get a "directory not empty" exception in the
TestFixtureTearDown (which for some reason isn't shown in the log?).
This was added in https://github.com/mono/mono/pull/6272
They were set in https://github.com/mono/mono/pull/6272 but since
env vars are process wide we'd end up with non-existing paths once
the tests are done. It is safer to unset the variables after the test.
* [System] Add unit test for Xamarin-2315
* [System] Use temporary directory for saving settings files
This change modifies the ApplicationSettingsBaseTests so that they
store the settings files in a temporary directory. This reduces
the risk of failed tests because of stale files from previous test
run, or from a build that runs in parallel.
* [System] Improve Settings behavior (Xamarin-15818)
Improve behavior of ApplicationSettingsBase class to match Windows .NET
more closely.
* Implement Upgrade to allow Upgrading of settings
* Make SettingsPropertyValue serialization work for complex objects
* Make Save and Update throw in unimplemented configurations
* Changed Reload to clear PropertyValues so they are reloaded
and fire PropertyChanged event for all Properties
* Modified Reset to do what Reload used to do.
* Added a backup Type loading for custom SettingsProviders
* don't call SettingsSaving on Reset()
* [System] Fire SettingsSaving event (Xamarin-2315)
When calling ApplicationSettingsBase.Save() the SettingsSaving
event has to be fired.
* [System] Add unit tests for Xamarin-15818
* [interp] Check for exception at field address failure
For example if the static constructor throws an exception
* [interp] Run class cctor before allocating objects
Otherwise we could end up throwing TypeInitializationException from the finalizer thread. We do the same with jit (emit_class_init).
* [interp] Check for method access failure when doing a call
* Fix some ThreadPool performance counters.
https://bugzilla.xamarin.com/show_bug.cgi?id=41294
The bug is that some performance counters are always zero.
Because we do not update them.
This addresses two of them: Work items added and thread count.
There is PerformanceCounter class and you can Increment instances,
however its metadata and some of the implementation is in System.dll.
Most of the code is in native.
ThreadPool is in mscorlib.dll, so can't use System.dll.
A few options exist to address this.
We could move and forward the type. We could duplicate and rename
and possibly subset the type.
Here we add a new icall very specifically for the scenario.
There is slight cost for the icall, and for the atomic increment.
There is an attempt to measure but the results were unclear.
Note that the count of work items is not specifically for QueueUserWorkItem
as one might expect, but also for any async calls.
Fix a little bit of typos.
* Take command lines from command line per PR feedback.
* newline at end of file
* Adds support for nanosecond resolution file information where available.
This patch adds support to the runtime to use the nanosecond
information available on Mac and Linux on `struct stat`.
`stat.st_Xtimespec` strucutre on OSX, and `stat.st_Xtime` and
`stat.st_Xtim.tv_nsec` pair on Linux.
Additionally, this adds support in `Mono.Posix` for MacOS nanosecond stat
data, it already had Linux support before.
* Use ULL here to prevent the computation from overflowing
utf16 to ascii for equality.
g_utf16_ascii_equal takes lengths, which are checked first
and unequal length implies unequal strings, and then no characters are looked at.
"z"" for zero means nul terminated and requires scanning the string.
Still, an equality primitive is often desired vs. inverting inequality.
These can cleanup some code -- extracted from a larger not yet commited PR
that uses it.
I found out that we were packaging e.g. MonoPosixHelper.dll from
the gtksharp msi instead of the one we build in Mono :P
This only happened in the x86 build because we don't package
gtksharp in the x64 build.
* Remove duplicated code by factoring on endian parameter.
* Force inline to mimic previous.
* fix the forceinline part
* Do not forceinline utf32, we never use it.
This can happen when emitting code like:
```
class Foo<T> {
T elt;
public T getter () {
return elt; // ILGenerator.Emit (OpCodes.Ldfld, /*FieldBuilder of Foo::elt*/)
};
}
```
the old incorrect code emitted a fielddef token for Foo::elt, but it should be a
memberref for Foo<!0>::elt.
Likewise, if we have
```
class Foo<T> {
public T f () { /*...*/}
public void g () {
var x = f (); // ILGenerator.Emit (OpCodes.Call, /* MethodBuilder of Foo::f */)
/*... */
}
}
```
Fixes https://github.com/mono/mono/issues/6192
the old incorrect code would emit a fieldref token for Foo::f but it should be
a memberref for Foo<!0>::f
They contain files with very long names which causes issues with `tar`.
We simply remove them from the dist directory before creating
the tarball since we don't use them in the Mono build anyway.
Fixes https://github.com/mono/mono/issues/6349
On some distros the number of strings you can pass to execve()
is limited which means you get the following error when trying
to create the tarball:
```
make[5]: execvp: /bin/sh: Argument list too long
make[5]: * [../../build/rules.make:303: dist-default] Error 127
```
To solve this we split the DISTFILES variable into groups of 100
entries and invoke the shell for each group instead of adding all
into the same invocation. Also removed looking for 'makefile' and
'GNUmakefile' since those don't exist in Mono and simplifies the logic.
Found during investigation of https://github.com/mono/mono/issues/6349
Revert the embedding API behavior change introduced by dcdfb3c500
mono_string_new will:
* return NULL if the given byte sequence is not a valid UTF-8 sequence
* assert if there is not enough memory to allocate a new MonoString.
This only changes the behavior of the API function. The runtime will continue
to use mono_string_new_checked which sets MonoError* for both sorts of
failures.
* [runtime] Bring jemalloc to mono
Jemalloc is known to have much better performance than system memory
allocators, and is safe in concurrent/re-entrant situations.
To use, provide the following options to configure:
--with-jemalloc to enable optionally. To use at runtime,
export MONO_USE_JEMALLOC to the environment.
--with-jemalloc-always to enable and make the default
--with-jemalloc-assert to enable with assertions to catch memory
unsafety. It adds overhead, but an overhead that's much less than
valgrind or asan.
If you export
MONO_JEMALLOC_CONF="stats_print:true"
You will see detailed memory statistics for mono at exit.
Now note that jemalloc is used through an explicit registration, so
C libraries called through pinvoke calls will not use jemalloc unless
they configure themselves to do so separately.
To understand the build work, I'm statically linking jemalloc.a into
the compilation unit for mono/utils/mono-jemalloc.c, which is
responsible for registering it with mono at startup. No further
copying out of the submodule is necessary at installation time.
* [runtime] Fix OSX 32-bit build definition
* Unbreak XMM register handling on platforms without MonoContextSimdReg
Platforms like Haiku (and glibc-less Linux, but that was unbroken a few
weeks ago) don't have this implemented on Mono. (yet?) Restore old
behaviour behind an #ifdef (same one as on mono-context.h) - perhaps it
could be a nicer ifdef, but I'm keeping this consistent for now.
* Attempt at a universal ifdef for MonoContextSimdReg presence
Suggestion of @kumpera. I've put #ifdefs in the obvious places, and
verified that the commit ensures we're still in the same position as
before.
* Fix non-MonoContextSimdReg calls in tramp-amd64.c
Follow advice of @joncham wrt the type and function to use instead.
* "Fix" a case of an error being ignored.
* And then remove mono_string_to_utf8_image_ignore which is not used.
And then remove the gboolean ignore_error parameter which is always FALSE.
Unlike on the jit (where we set a local variable on the stack frame of the last finally block), use the simple explicit abort protecting code which is used also for cctors. We can't use handler block guard logic since we can't async unwind from the interpreter.
* cooperative suspend babystep wrt mono_domain_try_type_resolve(MonoObject*).
No reduction in warnings, but remove one call to a function that has
warnings, leaving sre.c alone for now.
We have:
mono_domain_try_type_resolve (MonoDomain *domain, char *name, MonoObject *tb)
mono_domain_try_type_resolve_checked (MonoDomain *domain, char *name, MonoObject *tb, MonoError*)
The MonoObject* tb parameter causes a warning under cooperative suspend static validation.
Between name and tb, only one is ever used -- i.e. the non-null one, favoring name.
The non-checked function is embedded, so it survives for the time being.
Internally, we have reflection.c calling _checked(name != null, tb == null) and sre.c the opposite.
So, this fix refactors the function such that one takes const char* and the other MonoObject* (or MonoReflectionTypeBuilder*).
Some calls to a function with a warning are therefore replaced by calls to a function without a warning.
sre.c is left alone for now, therefore the number of warnings does not go down.
The caching within of System.AppDomain.DoTypeResolve is refactored into mono_class_get_appdomain_do_type_resolve_method.
Should we have GENERATE_GET_METHOD_WITH_CACHE like GENERATE_GET_CLASS_WITH_CACHE? Or GENERATE_GET_METHOD_CACHED?
A few stylistic experiments:
ternary operator?
const?
Some name shortening?
Non-anonymous struct tags?
Forward declaration to increase type safety?
_checked suffix optional if not differentiating from other?
* Cleanup MonoError initialization and usage.
Thread MonoError through a bit -- add mono_class_get_method_from_name_checked.
Could also be named mono_class_get_method_from_name_flags_checked.
Rename tb to typebuilder.
rename _builder to _typebuilder.
Reduce but don't eliminate struct/typedef change.
Remove extra braces.
* More MonoError tweaking -- the existance of cleanup breaks the model.
* remove a newline that was added
* Remove line breaks.
Put struct forward declaration among others.
Restore g_warning.
i.e. code review feedback
* Remove some newlines.
* more newlines
* Move from public class.h to private class-internals.h.
* Move new forward declarations out of public header object.h
and into new internal header object-forward.h.
waitpid(-1,...) reaps all zombie child processes of the calling process (see `man waitpid`). After a child process is reaped, it can no longer be queried. Because this reaping step is invoked via the `SIGCHLD` signal, all zombie children of the calling process are reaped every time any child process terminates, regardless of whether that child process was tracked by Mono.
The impact of this bug is that apps using Mono that spawn their own child processes (outside of Mono's `w32process` API) cannot query the exit state of its children. For example, a call to `waitpid(my_child_pid,...)` will return `ECHILD` for "no such child" because Mono has already cleaned up the child the moment `SIGCHLD` was raised.
* Minor cleanup split out and expanded from another larger change.
- Spelling in comment.
- 'l' is a short identifier that looks like '1' -- use "len".
- Remove extra braces.
- Add some g_assert (error) before error_init (error).
* remove unuseful asserts
* [ios-sdk] Rename test-runner directory to 'runtime' to be consistent with xamarin.ios.
* [ios-sdk] Add missing xamarin_log () icall used by Console.Write ().
* [ios-sdk] Change the run-ios-sim target so it works on ios11 as well, the --console option to simctl appears to be broken.
* [ios-sdk] Add a test harness.
The test harness is resposible for starting the emulator, installing the app on the emulator, running it, and
collecting application output using the osx logging facilities.
* [ios-sdk] Fix detection of the app exiting with an unhandled exception.
* [ios-sdk] Add CI support for running some test suites on the simulator.
* [ios-sdk] Kill the log reader process on shutdown.
* [ios-sdk] Disable android on CI because the make targets error out if the android sdk is not installed.
* [ios-sdk] Fix error checking in make targets.
* [ios-sdk] Remove accidently commited binary.
* [ios-sdk] Switch to using os_log instead of NSLog (), the latter doesn't seem to show up in the logs anymore. Switch to using the default ios sdk instead of hardcoding 11.1.
* [ios-sdk] Don't hardcode the ios version when creating a simulator.
* [ios-sdk] Parse the output of simctl list runtimes as json.
* [ios-sdk] Use 'syslog' style logging, its supported by older osx versions.
* [ios-sdk] Fix logfile parsing.
* [ios-sdk] Fix log filtering.
* [ios-sdk] Add test exclusions file for System.
* [ios-sdk] Redirect runtime logging to os_log ().
* [ios-sdk] Link libMonoPosixHelper and zlib into the test runner.
* [ios-sdk] Fix the target64 and cross64 builds.
* [ios-sdk] Build target64/cross64 on CI.
* [ios-sdk] Add device support to the runtime lib. Mark strings in os_log () calls as public.
* [ios-sdk] Log stdout messages using a separate subsystem for easier filtering.
* [ios-sdk] Add an 'appbuilder' tool which can generate simulator and device apps.
* [ios-sdk] Build device tests on CI.
* [ios-sdk] Add a test-runner instead of using nunit-lite-console.exe. The two are identical right now, but they might diverge in the future.
* [ios-sdk] Add a script to download prebuild llvm binaries.
* [ios-sdk] Run the runtime initialization on a separate thread, not the UI thread.
* [ios-sdks] Fix the build.
* [ios-sdk] Build the cross compiler against llvm.
* [ios-sdk] Add missing file.
* [ios-sdk] Add llvm support, enabled by passing LLVM=1 to make build-ios-dev-<app>.
* [bcl] Enable System.Security tests on the MOBILE profile.
* [ios-sdk] Enable more test suites.
* [ios-sdk] Fix device builds.
* [ios-sdk] Make some test steps non-fatal.
* [ios-dev] Use ad-hoc signing to sign device apps.
* [ios-sdk] Decrease the timeout on run-sim to 20m.
* [ios-sdk] Send back the test results using a tcp connection, parsing the ios logs is too fragile.
* [ios-sdk] Mark System.Net.Http tests as notworking, they seem to fail on CI.
* [ios-sdk] Compile the 32 bit cross compiler against llvm as well.
* [ios-sdk] Package up the binaries which can be uploaded to storage.
* [ios-sdk] Fix the download-llvm.sh script.
* [ios-sdk] Compile cross32 on CI.
* [ios-sdk] Use Options.cs from the mcs sources instead of making a copy.
* [ios-sdk] Avoid hardcoding the xcode sysroot, obtain it using 'xcode-select -p'.
* [ios-sdk] Fix the previous change.
* [ios-sdk] Add an option to appbuilder to cache aot compilation results between building different apps.
* [ios-sdk] Build device apps with llvm as well on CI.
* [ios-skd] Use XCODE_ROOT in a few more places, update README.md.
Triggering a forced collection means that it should to an immediate full collection of that generation. If we were having a running concurrent collection we were only finishing it. We should also trigger a new serial gc.
After minor or concurrent collections, we can have dead objects (can not be referenced starting from the current root set) still alive on the heap which can confuse profiling tools.
If we have a heapshot requested and we can't do it on the current collection, defer it to the finalizer.
Lack of it causes a build error in XA:
CMake Error at [..]mono/external/boringssl/util/android-cmake/android.toolchain.cmake:800 (message):
Specified Android native API level 'android-12' is not supported by your
The set of minimum API levels in `configure.ac` is incorrect. The current
NDK (r16) requires minimum API level of 14 for the 32-bit targets and level 21
for the 64-bit targets.
For a m2n transition we expect that we are already in managed (interp) and the delegate's method_ptr expects an InterpMethod. Refactoring will be needed in the future.
Mirror mono_marshal_get_struct_to_ptr. These methods can also handle non valuetypes (with certain attributes), which CEE_UNBOX doesn't logically handle.
There is no need to use BSTR marshaling to convert a SecureString to a
string. On some platforms, BSTR marshaling is not implemented, but we
still want to be able to convert a SecureString to a string on those
platforms.
So instead, use Unicode string marshaling.
https://github.com/mono/mono/pull/5599 fixed a race condition during shutdown
when runtime threads have come parts of their way through detach, but still
depend on runtime resources, like GC memory. The fix added runtime threads
to the joinable thread list just before they vanished from mono_thread_manage
radar making sure shutdown waited upon the thread before cleaning up.
The above fix slightly changed the behavior of the finalizer thread since it
waits on joinable threads and will now potential block on threads still
executing code (that involves runtime resources). There’s was an assumption
around the threads on the joinable thread list that they should be very close
to complete when added, so join calls coming from the finalizer thread should
almost never block and if it does, the code that remains to execute should not
involve runtime operations risking deadlock situations. Adding the thread to
the list earlier than previously done expose the shutdown to some potential
theoretical problems.
To mitigate the risk and still solve the race condition this commit adds a
mechanism to keep track of active runtime threads until they park on joinable
thread list. The pending counter will be waited upon by the shutdown
thread, just before it does its regular wait on all joinable threads
(after finalizer thread has stopped) to make sure all runtime threads have
been added to the joinable thread list before waiting upon them. Threads are
added to the joinable thread as late as possible, exactly how it’s been done
in the past by sgen_client_thread_detach_with_lock. Shutdown thread will wait
on runtime threads to appear on the list for a short time and if timeout (pending
runtime thread count not reaching 0 before timeout), it will just print a warning
and continue shutdown.
Getting into a wait state during shutdown due to runtime threads not yet added to
joinable threads list should be very rare (hitting previous race condition that was rare),
triggering the timeout should be even more rare, and if that ever happens, we are exposed
to shutdown race condition as we have had in the past, but now we at least get a warning in
the log making it simpler to analyze further.
This commit also fixes a problem with the debugger thread hitting the same race condition as above.
The shutdown thread stopping the debugger thread didn't completely wait for it to stop using runtime
resources before continue shutdown sequence. This triggers the same race condition as when shutting
down regular runtime threads. This commit makes sure stop_debugger_thread waits on the debugger thread
handle to become signaled (happens at the very end of thread lifetime) before continuing the shutdown
logic.
* [jit] Remove unused mono_arch_instrument_mem_needs () function.
* [jit] Remove unused mono_arch_instrument_epilog_full () function, only the non-full version is used.
* [jit] Remove some unused arch specific functions previously used by the global regalloc prototype.
This is a follow on to mono/roslyn-binaries#3 which adds the Roslyn VB.NET compiler to the roslyn-binaries repo. This will then install the binaries to the mono installation.
This change re-implement GC roots reporting in a way that allows users to correctly track the source of a GC root.
The new design is based on emitting GC root information upfront and only report addresses during heap dumps.
When a GC root is registered we emit an event that is an address range, the root kind, a key and a text description.
A decoder can use this information to match a reported root address with all registration addresses to figure out what they mean.
A GC Root key is used to further its meaning. For example, if kind is thread, key is a tid, if kind is static variables, key is the vtable pointer and so on.
The build of the change is introducing this key argument across all root registration code and rework our root reporting code to encode their addresses.
Some roots use pseudo-addresses when they are not registrable. This is the case of thread stacks/registers and the finalizer queue.
Finally, root reporting was changed to happen only once per collection and at the end, leading to correct and useful data being produced.
* Compile on amd64 Haiku
Use sigcontext (somewhat like win32, or x86) on Haiku amd64.
On amd64, Haiku doesn't have issues with marshalling 64-bit values,
but it currently does have issues with SGen either causing a stall
or a core dump. As such, while it can compile the stdlib (further
than x86 got), it's still a work in progress.
* Use set_real_time_clock for sys-time.c on Haiku
* Get mono-boehm compiling on Haiku again
It still doesn't work. Initialization will call GC_mark_from, which
will cause a segmentation fault as it decrements pointers. (Mono
will enter an infinite loop in mono_get_hazardous_pointer as a result.)
For now, mono-sgen will continue to be used by default.
make update-solution-files works but actually throws an ArgumentOutOfRangeException and as a result - corrupted csproj (fails on System.Runtime.CompilerServices.Unsafe -
System.Runtime.CompilerServices.Unsafe.dll.sources is empty)
* [linker-analyzer] added --flat option
This options allows to see all dependencies per vertex at once, with
displayed distance in the graph between the vertex and dependent
vertex.
An example of flat output:
Loading dependency tree from: linker-dependencies.xml.gz
--- Type dependencies: 'Android.App.Activity' --------------------------
Distance | TypeDef:Android.App.Activity [total deps: 7]
------------------------------------------------------------------------
1 | TypeDef:XA.App.MainActivity
2 | Assembly:XA.App, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
3 | Other:Mono.Linker.Steps.ResolveFromAssemblyStep
3 | Other:Mono.Tuner.CustomizeActions
3 | Other:MonoDroid.Tuner.MonoDroidMarkStep
2 | TypeDef:XA.App.MainActivity/<>c__DisplayClass1_0
* [linker-analyzer] Get back to using "unnamed" tuples
Use unnamed tuples to workaround mcs bug. We can revert this change,
once mcs is updated.
The build with mcs was failing like this, because of mcs bug:
```
MacBook:linker-analyzer rodo$ make
/Applications/Xcode.app/Contents/Developer/usr/bin/make all-local
MCS [net_4_x-darwin] linkeranalyzer.exe
Unhandled Exception:
System.NotImplementedException: named tuples for .interfaceimpl
at Mono.CSharp.TypeDefinition.Emit () [0x00028] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.ClassOrStruct.Emit () [0x00025] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeDefinition.Emit () [0x002e8] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.ClassOrStruct.Emit () [0x00025] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.Class.Emit () [0x00000] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeDefinition.EmitContainer () [0x0000f] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeContainer.EmitContainer () [0x0001e] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.NamespaceContainer.EmitContainer () [0x00007] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeContainer.EmitContainer () [0x0001e] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.NamespaceContainer.EmitContainer () [0x00007] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeContainer.EmitContainer () [0x0001e] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.ModuleContainer.EmitContainer () [0x0009c] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.AssemblyDefinition.Emit () [0x00098] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.AssemblyDefinitionStatic.Emit () [0x00126] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.Driver.Compile () [0x002f3] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.Driver.Main (System.String[] args) [0x00052] in <e953cb7042ea446195951c3e14c2cc5a>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.NotImplementedException: named tuples for .interfaceimpl
at Mono.CSharp.TypeDefinition.Emit () [0x00028] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.ClassOrStruct.Emit () [0x00025] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeDefinition.Emit () [0x002e8] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.ClassOrStruct.Emit () [0x00025] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.Class.Emit () [0x00000] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeDefinition.EmitContainer () [0x0000f] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeContainer.EmitContainer () [0x0001e] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.NamespaceContainer.EmitContainer () [0x00007] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeContainer.EmitContainer () [0x0001e] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.NamespaceContainer.EmitContainer () [0x00007] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.TypeContainer.EmitContainer () [0x0001e] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.ModuleContainer.EmitContainer () [0x0009c] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.AssemblyDefinition.Emit () [0x00098] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.AssemblyDefinitionStatic.Emit () [0x00126] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.Driver.Compile () [0x002f3] in <e953cb7042ea446195951c3e14c2cc5a>:0
at Mono.CSharp.Driver.Main (System.String[] args) [0x00052] in <e953cb7042ea446195951c3e14c2cc5a>:0
make[1]: *** [../../class/lib/net_4_x-darwin/linkeranalyzer.exe] Error 1
make: *** [do-all] Error 2
```
Bug was caused by wrong values in enum because `string` is parsed only when type is `SpecificTrampoline` but with mismatching values between C and C# enums it didn't parse string when it should causing parsing next event throwing random exceptions because there was still unexpected string data.
* [w32handle] Don't enter GC SAFE around calls to w32handle_wait_{one,multiple}
On non-Win32, the mono_w32handle_wait_{one,multiple} implementation is
coop-aware, so there's no need to enter/exit GC Safe.
On Win32, mono_win32_wait_for_{single_object,multiple_objects}_ex is not coop
aware (and can't be - because it's called from utils/os-event-win32.c which is
not supposed to use coop machinery), so do GC transitions around these calls.
Fixes cooperative GC regression due to f5fc773512
* [w32process] Use coop concurrency primitives
for exit_sem and processes_mutex.
With OS semaphores we could deadlock under coop GC if a GC happens at the same time that
a thread is waiting on the exit_sem - the finalizer thread gets suspended and
the incoming SIGCHLD never posts, so the waiting thread never suspends and the
GC STW never happens.
fixup! [w32process] Use coop semaphore for exit_sem
* [test] assembly_append_ordering.cs: mark methods with NoInlining
if TriggerLoadingSystemCore is inlined into Main, System.Core will be loaded
when Main is JITed, which throws off the assembly loading ordering that the
test cares about: that the SRE assembly is loaded before System.Core.
When we leave a try block and invoke finally blocks, we need to add try holes also for catch handlers, since they can invoke the previously handled finally blocks.
This has the following advantages:
* There is only one implementation instead of two
* The C version no longer needs to be compiled/recompiled.
The disadvantage is the additional build time dependency on python.
The windows build will keep using the C version for now.
* [jit] Extract AOT definitions from mini.h to aot-runtime.h.
* [jit] Remove some dead declarations from mini.h.
* [jit] Extract some non-JIT related functions and MonoJitDomainInfo/MonoJitTlsData into mini-runtime.h
- 1 pixel for right and bottom to compensate cells CellBounds overlapping;
- one more pixel for top, right and bottom to have one pixel gap between text and border. Left border had a good gap already (why?).
No call DrawText for cell if there is no rectangle at all.
The AOT profiler is not meant to be loaded during AOT compilation.
The coverage profiler does not currently support instrumentation of AOT code.
The log profiler does support enter/leave instrumentation of AOT code, but no
other functionality should be enabled in this case. We only want to set the
call instrumentation filter callback and then return control to the runtime.
* [interp] disassembler for mint instructions should return a string instead of printing char by char
otherwise logs are unreadable on products like XI
* [fixup] free `ins`
With the revamped GC root reporting work, some GC root unregister events will
arrive after the thread_stopped event. This will cause the thread to be
re-added to the thread list in the profiler, and never be removed until program
exit. This meant that if such a thread had actually exited and a new thread
would reuse its thread ID, that new thread would fail to add itself to the
thread list, leading to failures like this one:
init_thread: failed to insert thread 0x70000b761000 in log_profiler.profiler_thread_list, found = true
By using the new thread_exited event, we remove the thread from the thread list
after these GC root unregister events have arrived, thereby ensuring that the
thread won't be incorrectly 'resurrected'.
thread_stopping occurs earlier than thread_stopped, before any of the detach
code has run. thread_exited occurs after thread_stopped, once all detach logic
has finished.
* [runtime] Implement a few broken getters on ModuleBuilder
* [runtime] Implement ModuleBuilder.GetCustomAttributes
* [runtime] Test GetMethods, GetCustomAttributes, and GetFields for ModuleBuilder
* [runtime] Specify and test use of typebuilders with Custom Attributes + add more tests
* [w32find] Remove use of w32handle
* [w32handle] Ref handle when looking it up so it doesn't get destroyed while using it
* [w32handle] Ref handle when accessing its MonoW32HandleBase
* [w32handle] Make MonoW32Handle public
* [w32handle] Return MonoW32Handle as part of mono_w32handle_lookup_and_ref
* [w32handle] Pass MonoW32Handle from mono_w32handle_ops_own
* [w32handle] Pass MonoW32Handle from mono_w32handle_ops_isowned
* [w32handle] Pass MonoW32Handle from mono_w32handle_ops_signal
* [w32handle] Pass MonoW32Handle from mono_w32handle_ops_prewait
* [w32handle] Pass MonoW32Handle from mono_w32handle_ops_specialwait
* [w32handle] Pass MonoW32Handle from mono_w32handle_ops_details
* [w32handle] Pass MonoW32Handle from mono_w32handle_foreach
* [w32handle] Pass MonoW32Handle to own_if_{owned,signalled}
* [w32handle] Pass MonoW32Handle to mono_w32handle_issignalled
* [w32handle] Pass MonoW32Handle from mono_w32handle_set_in_use
* [w32handle] Pass MonoW32Handle to mono_w32handle_{lock,trylock,unlock}_handle
* [w32handle] Remove dead mono_w32handle_ref
* [w32handle] Pass MonoW32Handle from mono_w32handle_set_signal_state
* [w32handle] Pass MonoW32Handle to mono_w32handle_test_capabilities
* [w32handle] Remove dead mono_w32handle_get_type
* [w32handle] Pass MonoW32Handle to mono_w32handle_ops_signal
* [w32handle] Pass MonoW32Handle to mono_w32handle_ops_isowned
* [w32handle] Pass MonoW32Handle to mono_w32handle_ops_specialwait
* [w32handle] Pass MonoW32Handle to mono_w32handle_timedwait_signal_handle
* [w32handle] Fix some typos and ref/unref imbalance
* [w32handle] Rename mono_w32handle_{trylock,lock,unlock}_handle to mono_w32handle_{trylock,lock,unlock}
* [w32handle] Rename numhandles to nhandles
* [w32handle] Return MonoW32Handle instead of index when creating the handle
* [w32handle] Remove gpointer handle parameter for mono_w32handle_{ref,unref}_core
* [w32handle] Remove gpointer handle parameter for mono_w32handle_timedwait_signal_handle
* [w32handle] Remove gpointer handle parameter for mono_w32handle_duplicate
* [w32handle] Remove gpointer handle parameter for w32handle_destroy
* [w32handle] Remove gpointer handle parameter for mono_w32handle_unref
* [w32handle] Remove dead function
* [w32handle] Remove gpointer handle parameter for own_if_{owned,signalled}
* [w32handle] Remove gpointer handle parameter for mono_w32handle_{wait_one,wait_multiple,signal_and_wait}
* [w32handle] Remove gpointer handle parameter for mono_w32handle_foreach callback
* [w32handle] Remove gpointer handle parameter for mono_w32handle_ops_{signal,own,isowned,specialwait,prewait,details}
* [w32handle] Make mutex and cond coop friendly
* [w32handle] Check for ref before type in mono_w32handle_lookup_and_ref
* [w32handle] Allocate the private_handles array on the heap, to reduce mono executable and library size
If nodefaults is passed as the first argument, we would print `Could not parse argument: nodefaults` due to how it's parsed differently.
If nodefaults is passed after the first argument we would not print a warning that this was wrong.
This commit fixes both usability issues.
* [sdks] Fix Android pick of mono runtime
* [android] Have Console.{Out,Error} go through the runtime log mechanism to ease their interception
* [sdks] Intercept runtime logs instead of Console to send back for instrumentation
* [sdks] Intercept Android test runner logging
[profiler] Some documentation improvements
* Update and rewrite profiler-related `man` pages.
* Update profiler API documentation for the new API.
* Extend the `exdoc` tool to support some more Doxygen features.
* Document the AOT profiler's file format.
* Clean up the sample profiler module and add a makefile.
* Include context/domain reports in `mprof-report`'s default report set.
* Exit the process when the `help` option is passed to the profilers.
* Remove the IOMap profiler.
* Remove some deprecated options from the log profiler's `help` output.
* Clean up the AOT profiler and bring its user interface in line with the others.
* Allow comments in coverage filter files.
In 22f0977132 it was disabled
but we can actually just run a shorter version in PRs.
Also reenable the precompilation target for the managed CoreCLR tests.
[LogProfiler] Removed GcRoot events logging from start
GcRoots should only be reported/captured during heapshot. We already set callback when heapshot collection starts and unset it when heapshot is finished. Which means after 1st heapshot is taken we don't log them outside heapshot. Hence we shouldn't be logging them from start...
GcRoots should only be reported/captured during heapshot. We already set callback when heapshot collection starts and unset it when heapshot is finished. Which means after 1st heapshot is taken we don't log them outside heapshot. Hence we shouldn't be logging them from start...
The test was added in https://github.com/mono/mono/commit/375471820c02ff0bab025bff75b5da7efc95d3cd.
We were seeing some flakyness in the this test, looking at it I
noticed that we were passing executeOnlyOnce = false to
(Unsafe)RegisterWaitForSingleObject. This means that the delegate
would be executed again whenever the AutoResetEvent `evt` is signaled or
the timeout elapsed. The problem is that evt is never signaled by design
and we set a timeout of 1ms which means we'd execute it in a tight loop.
Setting executeOnlyOnce = true fixes this and I verified it doesn't
change the intent of the test (i.e. the test still fails after the
original commit is reverted).
Bumped the timeout for the CountdownEvent as well to be safe
since it's quite short.
When doing an OP_CALL_HANDLER for a clause (from a leave opcode), all following instructions, up until the actual branch out of the try block, should be part of a hole for that clause. We were failing to account for a single leave instruction invoking multiple finally clauses sequentially, in which case a basic block can be a try hole for multiple clauses.
* [bcl] Build some assemblies with -warnaserror
This ensures that we keep the build warning free.
We'll only opt-in a few assemblies that already have zero warnings.
We also only apply this when using csc as mcs might raise different warnings.
For now just opt-in assemblies in the net_4_x profile.
* Use the same option parsing logic as the other profilers.
* Support the same output file syntax as the other profilers.
* Use output.aotprofile as the default output file name.
* Open the output file on startup rather than shutdown.
* Use runtime logging functions instead of printf/fprintf.
* Don't print anything unless the verbose option is given.
* Fix an endianness issue with writing ints to the output file.
* Move all profiler state into MonoProfiler structure and store it statically.
* Remove outdated comments and includes.
* Separate profiler module documentation into a new mono-profilers(1) page.
* Add documentation for the aot and coverage profilers.
* Rewrite the mprof-report(1) page to only talk about mprof-report itself.
* Rewrite and update the profiler-related sections of mono(1).
* Conform to man page formatting conventions.
* Move doc comments to profiler.c so they're picked up by exdoc.
* Rewrite mono-api-profiler.html for the new profiler API.
* Clarify some aspects of the doc comments.
Some generic instances were not generated because they were only referenced by METHOD_RGCTX patches, and the gsharedvt
fallback didn't work because the method in question Unsafe.Add<T> uses a sizeof opcode on a gsharedvt type which is currently
not supported.
Testcase:
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
using System;
using System.Runtime.CompilerServices;
public class Tests
{
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public void Foo55<T> () {
byte[] arr = new byte [10];
ref byte data0 = ref arr [0];
Unsafe.Add (ref data0, 0);
}
interface IFace {
void Foo55 <T> ();
}
class AClass : IFace {
public void Foo55 <T> () {
byte[] arr = new byte [10];
ref byte data0 = ref arr [0];
Unsafe.Add (ref data0, 0);
}
}
public static int Main () {
IFace iface = new AClass ();
iface.Foo55<int> ();
return 0;
}
}
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
* [ci] Fix testing of msbuild in run-test-mac-sdk.sh
It contained the old version number and failed on bots that didn't
have leftover old build result.
* [ci] Fix msbuild paths in Windows packaging
They changed with 73bd521c07.
mono_class_setup_interface_offsets and mono_class_setup_interface_id should
only be called for interfaces.
mono_class_setup_interface_offsets is incorrect for classes, and
mono_class_setup_interface_id would be a no-op.
* [ci] Add Jenkins pipeline script for building OSX and Windows packages
This replaces the current Jenkins freestyle jobs.
We no longer need the signing inside of the MacSDKRelease profile
since we're now signing on a separate service and having the signing
certificates locally is discouraged anyway.
* [ci] Update embedded gtk-sharp in Windows msi to 2.12.45
This matches what we ship on www.mono-project.com
* [sdks] Match xamarin-android targets flags and parameters
* [sdks] Only compile BCL profiles that are needed
* [sdks] Add release and debug out directories for android
* [sdks] Add Android SDK and NDK paths from xamarin-android
* [sdks] Match xamarin-android x86 SDK version
* [sdks] Use make_standalone_toolchain.py to provision the Android toolchain
* Bump nuget-buildtasks
cherry-pick 304d785bd0
* [msbuild] Install importbefore/after hooks for nuget
cherry-pick 4c935964b2
* [msbuild] Fix build - create the directories before installing .. (#5980)
.. to them.
cherry-pick d711efdd90
* [msbuild] Fix build (#5981)
- Don't copy 14.0/Imports to 15.0 now, as we do that in nuget-buildtasks.
- And don't create symlinks for Microsoft.NuGet.targets as it is not
required anymore.
cherry-pick ef1ea85c0f
* [tools] Fix .apps generated by MacPack not running when Mono 5 is installed on macOS
The current script used by the generated .app only checks for Mono in /usr/local/bin, but not in /Library/Frameworks/Mono.framework/Versions/Current/Commands (the default location for new installations of Mono 5 on macOS)
* [tools] Fix WinForms .apps generated by MacPack not running when Mono 5 is installed on 64-bit macOS
Latest Mono now defaults to running mono64 on a 64-bit OS but there is currently no WinForms support on 64-bit Mono. Pass --arch=32 to mono when wrapping a WinForms app with MacPack.
* Localized * FileDialog. Fixed missing Locale.GetText for the displayed strings.
* Fixed padding and size of buttons in the PopupButtonPanel class. This was done to remove the workaround "Recently\nused" and similar in futher localizations.
* Changed width of PopupButtonPanel to prevent sticking buttons to the separator.
Instead of using find_method which relies on method name and exact signature
matching (and thus can't work for variant interfaces), use the vtable and the
interface offset to find the constrained method.
Terminology:
base method - a method of the base class to be called
base class - some general class or interface that declares a method
constraint class - a more specific class that also implements the method.
constrained method - the version of the base method in the constraint class.
To find the constrained method given the base method:
- if the base class is a class:
the constraint class can't be an interface. it's either the base class or
some subclass of it. If the base method isn't virtual there's nothing to do
the constrained method is the same one.
If the base method is virtual, get its vtable slot and find the corresponding
method in the constraint class's vtable.
- if the base class is an interface:
in this case the constraint class is either another interface or a class.
if the constraint class is an interface, since interfaces can't have
implementations, there's nothing to do.
if the constraint class is a class, then to find the constrained method
get the interface slot offset of the base method and find the base interface offset
of the base interface and look in the constrained class vtable.
(the base interface offset gives the starting vtable slot for the base
interface in the constraint class vtable; the slot offsets go consecutively
for each of the methods of the interface).
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=60545
They are not generated by a ruby script.
The commit includes the generated file and the generation script for now to ease development.
We can later discuss generating it at build time.
In Unix, assume our current directory contains:
`test`, a directory
`test/test2`, another directory
`test/test2/test_file`, a file
`test3`, a symbolic link pointing to `test/test2`
Then the path "test3/../test3" has two interpretations depending on the processor:
* The OS (the `lstat` syscall, `ls`, etc.) will find it invalid (as it evaluates to: enter `test/test2`, go up one level, try to enter `test3` which is another level down
* We (.NET, at least CoreCLR) should find it valid (enter `test3`, go up one level, enter `test3`).
This ensures that for Directory.Exists, we process the path `..`'s on the .NET level before passing it for native processing.
this test case was broken for an unknown time, but surfaced with a
recent change in nunit-lite (2255c54966)
that runs every test in a new `ExecutionContext`. Previously, the
pre-condition for this test was implicility fulfilled by another test.
The test failed already when executed only on its own. With the change
around `ExecutionContext`, each test is "isolated" regarding said
pre-condition.
The fix is to explicitly fulfil the pre-condition in the test.
ModuleBuilder::GetArrayMethod returns a fresh MonoArrayMethod instance each
time it's called, even if you ask for the same method multiple times. On the
other hand, mono_image_get_array_token caches tokens by method signature.
Therefore mono_image_create_token should expect collisions.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=60238
* [runtime] Fix mkbundle compilation on OSX
* [runtime] Add aot arguments to mkbundle
* [runtime] Enable compiling aot with mkbundle
* [runtime] Add new dedup interface to mkbundle
* [runtime] Fix path resolving for mkbundle
* [runtime] Use mkbundle in BCL tests
* [runtime] Skip building System.Security, System.IdentityModel tests on testing_aot_full
* [runtime] Fix in-tree building for mkbundle
* [runtime] Move testing dll into profile
* [runtime] Add target to mkbundle all tests before CI
* [runtime] Build stripper and use with mkbundle
Preliminary linker support ran into dependency-finding bug
with the monolinker.exe binary. Fix postponed until later.
* [runtime] Skip not supported tests with mkbundle
* [runtime] Don't re-aot when running BCL tests
* [runtime] Provide config to mkbundle
* [runtime] Fix mkbundle internationalization test results, build all
* [runtime] Clean up temp mkbundle aot directory
* [runtime] Add mkbundle support for dedup
* [runtime] Fix tracking of dedup module in mkbundle
* [runtime] Document mkbundle AOT options in man pages
* [runtime] Fix CADMessage generic method argument marshalling
* [runtime] Support excluding or choosing to emit only inflated methods
* [runtime] Only write cache if changed, so can be used by Makefiles
* [runtime] Thread state through multiple mono_compile_assembly calls
* [runtime] Emit skipped methods in dedup module
* [runtime] Use AOT attribute to mark dummy dedup module
* [runtime] Expose and use can_dedup for AOT compiler+runtime
* [runtime] Add missing cases to the mangler
* [runtime] Fix direct calls with dedup
* [runtime] Implement runtime support for finding deduped code
* [runtime] Refactor dedup state setup into new function
* [runtime] Add in dedup debugging aid / external visibility
Gives a demo on how to make mangled method names externally visible
* [runtime] Log dedup statistics
This fix is a bit weird but it's due to some restrictions of the managed API.
MissingMemberException & friends require both ClassName and MemberName to be supplied independently, so the signature
can't simply be applied to MemberName. So we pass it on a separate field.
The next thing is that we want C#'esque signatures, where the return type comes before ClassName.MemberName, so we pass
a format string and apply it in managed.
it was fine on CI, but developers can run into build errors if they
don't follow a strict order (due to autotools fighting with
`winconfig.h`).
`basic.exe` passes, but everything involving native transitions crashes.
This introduces the following changes.
By default, enable more events. Exceptions and Counters are on by default.
By default, if alloc or heapshot are enabled, we emit root events as well.
New `nodefaults` argument that disables the above changes to default arg processing.
Added "nocalls" argument for compat only purposes.
Restored "cycles/" prefix to sample frequency argument. It was already a dead argument, but kept for compat.
We restored that as existing clients pass that flag.
* [tests] Appdomain assembly loading regression test for #49308
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=49308
We try to trick the remoting code into causing an assembly from a bad directory
to be loaded too eagerly into an appdomain. If we succeed, we call a method
that doesn't exist. Expected behavior is that the bad assembly is not loaded
and instead we can do an Assembly.LoadFrom of a good assembly.
* [tests] Add appdomain-marshalbyref-assemblyload.exe to KNOWN_FAILING_TESTS
This is a regression test for
https://bugzilla.xamarin.com/show_bug.cgi?id=49308, it should be re-enabled
when the bug is fixed.
.. of 15.x. It doesn't really affect anything and makes it simpler on
wrench to specify directory from which to run the tests!
(cherry picked from commit 3f3b106aca)
# Conflicts:
# packaging/MacSDK/msbuild.py
* [Tests] Make Mono.Data.Sqlite tests more robuts.
There are cases in which the tests are ran in parallel and the files
used for the db are writte/read by several tests at the same time. This
changes ensures that we do have a diff test file per test case to ensure
that we do not have false negatives.
Any translation unit that includes a Mono header should include <config.h>
first to ensure that all of our configuration defines are available.
In particular, config.h defines MONO_INSIDE_RUNTIME which, in mono-publib.h causes
MONO_RT_EXTERNAL_ONLY to be defined to an attribute that causes a compilation
error if you use a function that is internally deprecated for the runtime.
Also change a couple of places that used non-_checked functions.
Handles macro bodies are allowed to operate on raw pointers to managed memory.
The macro arguments must be UNSPUPPRESSed because we want warnings if the
arguments are doing bad things.
Marking a struct definition or a typedef with MONO_RT_MANAGED_ATTR will cause
Centrinel to treat pointers to the struct as residing in managed memory and to
issue warnings when raw pointers to such managed objects occur in the runtime.
(Also Centrinel knows that if the first field of a struct is a `MonoObject`,
then the struct is definiting a subtype of a managed object and so pointers to
_that_ struct also point into managed memory)
This is a candidate fix for:
https://bugzilla.xamarin.com/show_bug.cgi?id=60317
The bug was introduced by 1b5e0f7331.
Preliminary verification
========================
If I make just this _one_ change to a "bad" commit of Mono from after
commit 1b5e0f7, rebuild System.dll in the `xammac` profile, and then
overwrite that file in the MonoBundle directory of a Xamarin.Mac test
app, then I restore the old "good" behavior. (I started with
38da0b3b49 as the "bad" version for my
tests.)
I believe this confirms that the cause of bug 60317 was the usual
deadlocking issue when awaiting Tasks on the UI thread. As discussed on
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html, if
any Tasks awaited anywhere up the call stack are missing
`ConfigureAwait (false)`, then you can run into trouble on the UI
thread.
Additional little checks
========================
1. Do the other `await` statements in commit
1b5e0f7331 all look OK? Yes, it looks
like this was the only `await` statement that was missing
`ConfigureAwait (false)`:
```
$ git show 1b5e0f7331 | grep await
+ await ProcessOperation (cancellationToken).ConfigureAwait (false);
+ var ret = await InnerRead (cancellationToken).ConfigureAwait (false);
+ await Parent.InnerWrite (RunSynchronously, cancellationToken);
+ var ret = await Parent.InnerRead (RunSynchronously, requestedSize, cancellationToken).ConfigureAwait (false);
+ result = await asyncRequest.StartOperation (CancellationToken.None).ConfigureAwait (false);
+ result = await asyncRequest.StartOperation (cancellationToken).ConfigureAwait (false);
+ var ret = await task.ConfigureAwait (false);
+ await task.ConfigureAwait (false);
```
2. Is it a concern that mcs/class/System did not contain any calls to
`ConfigureAwait ()` until commit 1b5e0f7:
```
$ git grep ConfigureAwait 1b5e0f73316ee7b83c8947bc738015443fabd7af^ -- mcs/class/System || echo 'None'
None
```
I do not think this is a concern. For example,
System.Net.Http.HttpClient has been using `ConfigureAwait (false)` for
several years, so there is a precedent for it.
This occasionally happens:
```
System.NullReferenceException : Object reference not set to an instance of an object
at System.Diagnostics.Win32EventLog.NotifyEventThread (System.Threading.ManualResetEvent resetEvent) [0x00001] in D:\j\workspace\w\mcs\class\System\System.Diagnostics\Win32EventLog.cs:739
at System.Diagnostics.Win32EventLog.<EnableNotification>b__44_0 () [0x00000] in D:\j\workspace\w\mcs\class\System\System.Diagnostics\Win32EventLog.cs:729
at System.Threading.ThreadHelper.ThreadStart_Context (System.Object state) [0x00014] in D:\j\workspace\w\mcs\class\referencesource\mscorlib\system\threading\thread.cs:68
at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00071] in D:\j\workspace\w\mcs\class\referencesource\mscorlib\system\threading\executioncontext.cs:957
at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00000] in D:\j\workspace\w\mcs\class\referencesource\mscorlib\system\threading\executioncontext.cs:904
at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state) [0x0002b] in D:\j\workspace\w\mcs\class\referencesource\mscorlib\system\threading\executioncontext.cs:893
at System.Threading.ThreadHelper.ThreadStart () [0x00008] in D:\j\workspace\w\mcs\class\referencesource\mscorlib\system\threading\thread.cs:105
```
We'll get it because there's a race as the lamdba capturing
_notifyResetEvent in EnableNotification() is outside of the
_eventLock so _notifyResetEvent can be null by the time it is called.
We need to check for that case in NotifyEventThread().
* [interp] clear stack on resuming into the main loop
fixes `System.Collections.Generic.DictionaryTest.IDictionary_Add3`.
The problem is that resuming into an handler requires the evaluation stack to be emptied, which didn't happen with the new unified exception handling.
The frame layout looks like this in memory:
| sp | vt_sp | locals | ... |
|----|-------|--------|-----|
If we don't empty `sp` properly, we will eventually overflow into the `vt_sp` area (which is the evaluation stack for value types). So things get funny if `sp == vt_sp` and you do stuff like this:
```c
sp->data.p = vt_sp;
```
Kind of amazing that it almost passed the whole test suite with that bug.
* [interp] clear eval stack for value types as well when entering a handler
* [interp] disable more tests in corlib suite
* [Facades] Use same assembly company/product/copyright attributes as other BCL assemblies
We can't use Consts.cs since it'd bloat up the facades too much.
Also remove ".dll" suffix from AssemblyTitle/Description to match
what the Facades in the .NET Framework Reference Assemblies pack
are using.
* Bump API snapshot submodule
* [interp] enable it by default in configure
can be disabled via --enable-minimal=interpreter, like other components in the
runtime.
* [interp] use DISABLE_INTERPRETER in Makefile.am.in so it is closer to what we had before
* [interp] improve handling of interpreter flag and also check if we are on a cross-compile runtime
* [configure] add interpreter to the list of --enable-minimal
* [ci] remove --enable-interpreter from script
* [windows] disable interpreter for now
* [driver] add output about availabilty of interpreter in --version
* [man] add entry to mono.1 about --interpreter
* [driver] update --interpreter handling
Race only observed on Windows and current solution adds dependency between detach
and finalizer thread. Disable on none Windows platforms until we have an alternative
solution to the race condition. Keep on Windows until we have alternative solution
since race is manifesting itself on Jenkins builds.
This removes the duplicate code from the interpreter and makes it possible to support exception debugging.
Also fix the the basic block construction code so CEE_THROW begins a new bblock.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=59909
WebChannelFactory doesn't add the WebHttpBehavior on mobile:
https://github.com/mono/mono/blob/4272b68b769951c221ec39d3e844f8f715e1df62/mcs/class/System.ServiceModel.Web/System.ServiceModel.Web/WebChannelFactory.cs#L87-L90
This makes the WebInvokeAttributeTest.RejectTwoParametersWhenNotWrapped
test fail on mobile since it doesn't reach the normal validation
method where it'd fail with InvalidOperationException, e.g. here''s
the stack on net_4_x profile:
```
System.InvalidOperationException : Operation 'Join' has multiple message body parts. Add parameters to the UriTemplate or change the BodyStyle to 'Wrapped' or 'WrappedRequest' on the WebInvoke/WebGet attribute.
at System.ServiceModel.Description.WebHttpBehavior.ValidateOperation (System.ServiceModel.Description.OperationDescription operation) [0x000f9] in /Users/alexander/dev/mono/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/WebHttpBehavior.cs:249
at System.ServiceModel.Description.WebHttpBehavior.Validate (System.ServiceModel.Description.ServiceEndpoint endpoint) [0x00028] in /Users/alexander/dev/mono/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/WebHttpBehavior.cs:268
at System.ServiceModel.Description.ServiceEndpoint.Validate () [0x0007f] in /Users/alexander/dev/mono/mcs/class/System.ServiceModel/System.ServiceModel.Description/ServiceEndpoint.cs:129
at System.ServiceModel.ChannelFactory`1[TChannel].CreateChannel (System.ServiceModel.EndpointAddress address, System.Uri via) [0x0002b] in /Users/alexander/dev/mono/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory_1.cs:148
at System.ServiceModel.ChannelFactory`1[TChannel].CreateChannel (System.ServiceModel.EndpointAddress address) [0x00000] in /Users/alexander/dev/mono/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory_1.cs:115
at System.ServiceModel.ChannelFactory`1[TChannel].CreateChannel () [0x00006] in /Users/alexander/dev/mono/mcs/class/System.ServiceModel/System.ServiceModel/ChannelFactory_1.cs:110
```
We can fix this by adding the WebHttpBehavior in the test manually.
NB: I'm actually not sure why this isn't done by default on MOBILE?
According to MSDN it should.
rpm-find-provides is a mess, this makes it a bit less of a mess by adding not only stuff from the GAC, but also Facades and 4.5 directories. Doesn't help with version mismatches for facades though.
This fixes bug #60435, where the DataGridViewRow.CreateCellsInstance method is never invoked. Now value of the Cells property is initialized by calling the CreateCellsInstance method.
Removed unused localization resource files.
Added default resources for English locale. Updated makefile and System.Windows.Forms-net_4_x.csproj.
Class Locale now uses ResourceManager.
The zip tests were not using temp files which created bug #60480 when
trying to read the embeded resources. This also fixes the situation in
which tests are run in parallel for the Mac since we could have tests
that step on each other files.
Both on jit and interp, the full corlib message sink path does not work on some testcases. Apparently we rely on the xdomain wrappers for correctness there.
The object creation of some types (like ContextBoundObject) can return a transparent proxy. When calling the constructor on the returned object we might need to go through the remoting wrappers.
* [interp] Add infrastructure code needed for unified exception handling between the interpreter and the JIT.
* Pass the clause to mono_interp_set_resume_state ().
* Add a mono_interp_run_filter () function to run filter clauses.
* Add a 'ji' field to ExceptionTraceIp which is used to avoid an ip->ji lookup in ves_icall_get_trace ().
* Rename mono_handle_exception_internal_first_pass () to handle_exception_first_pass () and make it return the
StackFrameInfo for the frame which caught the exception.
This allows the removal of the duplicate and hard to understand interpreter EH code
and makes it easier to add debugger support to the intepreter.
* [sdb] Pass the already computed StackFrameInfo to mono_debugger_agent_handle_exception () so it doesn't have to be recomputed in ss_create (). This approach works both for the JIT and the interpreter.
* [interp] Generate seq points for async methods too.
* [interp] Rename ves_exec_method_with_context () to interp_exec_method_full (), add a interp_exec_method () helper with less arguments.
* [interp] Set ctx->sp for interpreter frames to the address of the InterpFrame structure, code in debugger-agent.c uses it to order frames.
* [sdb] Fix the support for filter clauses in the interpreter by running them in a new interpreter frame.
* [sdb] Add DEBUGGER_INVOKE frames for the interpreter.
* [interp] Add a mono_interp_frame_get_parent () function, use that instead of the 'new_sp' argument to mono_interp_frame_iter_next ().
* [sdb] Run the test code for the ClassLocalReflection () test only for that test since it doesn't work with the interpreter.
* [interp] Fix the build.
* [jit] Move the code handling the MonoLMFExt structures from exceptions-<ARCH>.c to mini-exceptions.c, its the same on all platforms.
* [jit] Remove mono_arch_init_lmf_ext (), it does the same on every platform.
Use getrandom() instead of /dev/urandom on Linux
getrandom() was introduced in version 3.17 of the Linux kernel and glibc has implemented it since version 2.25.
After a user requested minor collection we need to check if the new size of the heap exceeds the allowance, in which case we need to also do a major collection.
Fixes bug (#60168) where, if user triggers minors repeatedly, we never get to collect the major space (which is normally checked after the nursery is full, which never happens in this case)
d9922895d4 removed Mono.Unix.Native/SocketTest.cs
from the exclude list on the monodroid profile.
It turns out that some tests don't work there however,
they fail with an ArgumentOutOfRangeException on some socket options.
The latest NDK doesn't support platform 9 anymore, the minimum it accepted was 14 thus I changed both arm and x86 to it.
This is harmless as 14 covers all but gingerbread which XA plans on stopping to support.
Added a android-toolchain target that configure all android toolchains.
On my system, XS installs android sdk/ndk on different places.
This patch probe the default places and fallback to the places I got.
It does verify if the paths are bad and fail building ASAP.
Finally, in includes sdks/Make.config that will include defines to trim what things you actually want to build.
When matching a class in match_class() debug helper, avoid maching the class
if the matched-against descriptor's class name is only
a prefix of the class name, but the class name is actually
longer (e.g. don't match Foo2 against Foo).
Add a unit test for callspec parsing and evaluation.
call specifications are being used with the --trace command line
argument and with the log profiler 'callspec' parameter. This test
suite verifies that call specifications are correctly parsed and matched
against methods at runtime.
Jemalloc is known to have much better performance than system memory
allocators, and is safe in concurrent/re-entrant situations.
To use, provide the following options to configure:
--with-jemalloc to enable optionally. To use at runtime,
export MONO_USE_JEMALLOC to the environment.
--with-jemalloc-always to enable and make the default
--with-jemalloc-assert to enable with assertions to catch memory
unsafety. It adds overhead, but an overhead that's much less than
valgrind or asan.
If you export
MONO_JEMALLOC_CONF="stats_print:true"
You will see detailed memory statistics for mono at exit.
Now note that jemalloc is used through an explicit registration, so
C libraries called through pinvoke calls will not use jemalloc unless
they configure themselves to do so separately.
To understand the build work, I'm statically linking jemalloc.a into
the compilation unit for mono/utils/mono-jemalloc.c, which is
responsible for registering it with mono at startup. No further
copying out of the submodule is necessary at installation time.
* Exclude a couple of sources currently not building anything useful on Windows.
* Added MONO_EMTPY_SOURCE_FILE to a couple of source files ending up empty by default.
* Excluded API's not included on UWP targets.
* Explicitly declared import project paths in target files.
* Added support to define x64 MASM build outside default targets file.
Roslyn looks only inside `$msbuild_bin/Roslyn/` and does not fallback to
the framework path. msbuild worked around this by setting `CscToolPath`:
https://github.com/mono/msbuild/commit/157a0f4d1a7aadd4e561e3ca8c784cbc2529926f
But this kicks in only if the default msbuild target files are imported!
If the `Csc` task is being used without importing them, then we fail
with
`error MSB3082: Task failed because "csc.exe" was not found.`
`Microsoft.CodeAnalysis.VisualBasic.dll` is the only file not being
symlinked, after this change. So, instead we will symlink all the files.
Fixes bxc #60340 .
Preserve
`System.Runtime.Remoting.Activation.ActivationServices.CreateProxyForType`. It
is called from `object.c:mono_object_new_specific_checked` when
constructing remoting or com objects.
I didn't add `feature="remoting"` because it is used also for com
objects.
Added linker test. Without the LinkerDescriptor addition, it fails
like this:
Unhandled Exception:
System.NotSupportedException: Linked away.
at (wrapper managed-to-native) System.Object.__icall_wrapper_ves_icall_object_new_specific(intptr)
at C.Main () [0x00001] in /Users/rodo/git/mono/mcs/tools/linker/Tests/mscorlib/test-remoting.cs:11
[ERROR] FATAL UNHANDLED EXCEPTION: System.NotSupportedException: Linked away.
at (wrapper managed-to-native) System.Object.__icall_wrapper_ves_icall_object_new_specific(intptr)
at C.Main () [0x00001] in /Users/rodo/git/mono/mcs/tools/linker/Tests/mscorlib/test-remoting.cs:11
* Only null check target for delegate if method is not static. Fixes regression introduced by 1cfd52452a.
* [interp] pass first stack arg to transform, so we get the correct delegate wrapper
the wrapper logic detects if the target method of a delegate is a static
method with an argument bound, and handles it properly in the generated
code.
fixes mono/tests/delegate14.cs
This broke "make dist" after 61559965a1
because comments were added to System.Data_test.dll.sources
and they weren't stripped when TEST_FILES was computed so it tried
to include them in the tarball as files.
We count on the fact no threads are created or switched to foreground between the time we waited for all foreground threads to exit and the time we abort all running threads (except for the finalizer and DONT_MANAGED threads). This is racy and we should suspend all threads, them being foreground or background.
Removing the thread from the `threads` array in `remove_and_abort_threads` goes against the lifetime expectation that a thread is removed from `threads` when it is being detached. This 2 ways of having the thread removed complicates the lifetime management and expectations of the thread.
* [mini] Fix spiller when the dest membase optimization intereferes with lvreg caching. Fixes#20562
Given this IR sequence:
int_add R18 <- R18 R18
move R37 <- R18
The spiller would use the dest membase optimization and change the `add` to `add_membase_reg` and assume that the value in R18 would still be valid afterwards. This was the case cuz the code handling sreg2 won't check whether R18 would be mutated but not kept in a register.
The fix is to disable lvreg caching if the dest membase optimization is used. It forces later uses to reload from memory, which is not great, but it's correct.
* [mini] Add regression test for #20562 and re-enable ratests.cs.
* [runtime] Rename atomic functions from the win32 style naming to mono_atomic_<op>_<type>, with a consistent signature on all platforms. This fixes a large number of warnings on windows.
* Add Windows implementaiton of mono_atomic_*.
* Windows implementation of mono_atomic_* inline functions.
* Changed naming typo in mono_atomic_xchg_i32Add and mono_atomic_xchg_i32Add64.
* Fixed some additional signed/unsigned/volatile warnings when using mono_atomic_*
* Fixed some smaller additionl warnings.
* Fix Interlocked* to mono_atomic_* name change in signal.c
* Additional name adjustment of atomics.
Aligning more towards C11/C++11 standard namings:
mono_atomic_xchg_add_i32|i64 -> mono_atomic_fetch_add_i32|i64
Changed from mono_atomic_add to mono_atomic_fetch_add in cases when return
type is not used.
Also includes small mingw build fix on Windows.
* Aligned loads with C++11 implementation using explicit compiler barrier.
On x86/x64 Windows, reading a properly aligned 8,16,32 bit volatile variable
(using /volatile:ms extension) should have acquire semantics. On x64
this also includes 64-bit properly aligned volatile variables.
The C++11 implementation does however include an explicit _ReadWriteBarrier in
its sequentially consistent implementation to instruct compiler to not reorder
load/stores. Since compiler supports two modes of volatile behavior (ms/iso)
this additional barrier is probably there for consistency, independent of the
behavior of volatile keyword.
NOTE, the x86/x64 CPU architecture has strong guarantees regarding load/store of
memory operations, so issuing a CPU memory barrier for loads should not be needed
(and is not done in C++11 atomics implementation).
This commit also adds a couple of optimizations for 32-bit loads and for x64,
64-bits loads. The C++11 implementation uses the same pattern loading them as 8
and 16 bits variables, so no need for Interlocked* calls to load 32-bit and for x64
64-bit variables.
These tests classes are already included in the corlib test assembly.
Having them duplicated in System.Core causes issues in XA because
both test assemblies are in the same process.
To solve this we introduce abstract *TestBase classes that we can
share between the test assemblies and only mark the concrete test
class implementations with [TestFixture]
* [bcl] Remove AssertExtensions helper classes
Since we're on nunitlite now we can use the proper `Assert.Throws<>()`
instead and remove the helper class (which we actually duplicated!)
This may not be the final fix; the Mono-only workaround was introduced in b5dc9a4951 to fix a crash with Unicode paths in TryCreate. However the test case for that issue now succeeds without the workaround.
* [test] ILGenerator test for duplicate methodspec tokens
Regression test for [Bugzilla #60233](https://bugzilla.xamarin.com/show_bug.cgi?id=60233)
* [sre] mono_dynamic_image_register_token: Change asserts to warnings
This partly relaxes the changes in 792b5367cd
which added the assertions.
In practice the assertions introduced a crash in heavy uses of
System.Reflection.Emit such as unit testing frameworks and dynamic languages.
We still want to know if there are surprising uses of
mono_dynamic_image_register_token, but we don't need a crash. SRE used to work
before 792b5367cd, so no need to break it.
* [sre] Register a canonical reflected method for a methodspec token (Fixes#60233)
This is like the fix for [bugzilla
59364](https://bugzilla.xamarin.com/show_bug.cgi?id=59364) but this time it's a
methodspec token, not a memberref token.
quote from the darwin man page:
> The functions getpwnam_r(), getpwuid_r(), and getpwuuid_r()
> return 0 if no error occurred, or an error number to indicate
> failure. It is not an error if a matching entry is not found.
> (Thus, if result is NULL and the return value is 0, no
> matching entry exists.)
* [System.IdentityModel] Add excludes for tests that don't compile on monodroid profile
Also add a new test for X509CertificateValidator so the assembly
isn't empty on monodroid.
* [System.ServiceModel] Add excludes for tests that don't compile on monodroid profile
* [System.Security] Add excludes for tests that don't compile on monodroid profile
Also reduce duplication between common.sources and System.Security.dll.sources
* [System.Web.Services] Add excludes for tests that don't compile on monodroid profile
* [System.ComponentModel.DataAnnotations] Make tests compile on monodroid profile
* [mini regressions] enable aot-tests.cs also on non-fullaot
* [interp] handle Nullable in cee_unbox
* [interp] fix cee_ldobj when top of stack is a value type
fixes test_0_dyncall_nullable
* [mini] require aot-tests regression tests to run only with OPT_INTRINS
Just over a year ago Xamarin.Android switched to running BCL tests straight
from the Mono sources but at the time we decided we didn't want to enable
a number of "new" tests (in the sense - never previously ran on XA) to avoid
introducing new failures in time which required focusing on more important
goals.
Currently, Xamarin.Android no longer uses Mono **sources** to build its tests
but, rather, it uses test **assemblies** built by Mono. This commit restores
the previously excluded tests in preparation for full BCL test coverage in
the near future.
There was very little test coverage of the I18N encodings before.
This adds a bunch of tests based on Latin1EncodingTest.cs since
latin1 is quite similar to these encodings.
A few of the added tests fail in some encodings due to what looks
like bugs in the implementation, disabled those temporarily, see FIXME's.
(filed https://bugzilla.xamarin.com/show_bug.cgi?id=60216 for tracking)
When I added temp dir handling to SaveTest in https://github.com/mono/mono/pull/5727
I copied the Setup/TearDown from TypeBuilderTest.
However that class doesn't actually save+load the assemblies so
it doesn't run into the issue on Windows where assemblies can't
be deleted because they're still loaded in the AppDomain.
To fix this follow CustomAttributeBuilderTest and ModuleBuilderTest,
i.e. just catch all Exception's in teardown...
We need this because XA is now starting to use the test assemblies
we build in the Mono repo instead of using the .cs source directly
and this would conflict.
ARMv8 ARM [cf. C6.2.65] says:
> All other encodings of CRm that are not listed above are reserved, and can
> be encoded using the # syntax. It is IMPLEMENTATION DEFINED whether options
> other than SY are implemented. All unsupported and reserved options must
> execute as a full system barrier operation, but software must not rely on
> this behavior
That means, before we would rely that chip implementations fall back to
SY, which is explicitly stated that software must not rely on. Also, ISH
is enough, as a "inner shareability domain" contains all PEs controlled
by a single hypervisor or operating system. That is what GCC, linux
kernel and so forth do as well.
Some broken versions of WSL don't set the mcontext_t::fregs field to a valid
pointer. We work around this by checking if the pointer is NULL, and if so,
not making the fpstate available. This is not ideal as we won't scan XMM
registers on these broken WSL versions, but accessing the
ucontext_t::__fpregs_mem layout is more complicated than it seems, so this
workaround will have to do.
Random failures in Jenkins tests, more frequent in sgen stress test due to the following assert:
Assertion at ..\mono\mini\mini-trampolines.c:842, condition `mono_thread_is_gc_unsafe_mode ()' not met
When investigating this a little deeper revealed a race when switching thread states from ASYNC_SUSPENDED
to RUNNING. The assert would fire on a running thread due to having a ASYNC_SUSPENDED state, but when thread
state was inspected in debugger it was showing correct RUNNING state.
Looking through the code indicated that this should not be possible, since caller would suspend thread before
setting ASYNC_SUSPENDED using atomic ops and set back to RUNNING before thread was resumed using atomic ops.
So based on this the only way to get wrong state and fire assert would be if the thread was not immediately
suspended when Win32 SuspendThread API returned, and read the ASYNC_SUSPEND value before really suspended by
the kernel. Nothing in the API documentation indicates that the SuspendThread actually behaves this way, but
current implementation assumes that SuspendThread actually suspends the thread and only return when no more
user mode code is executed by the thread.
Turns out that this is not 100% accurate and SuspendThread is just a suspend request to the scheduler, so when
SuspendThread call returns the “suspended” thread might still execute user mode code and that breaks the assumption
in current implementation opening up for the observed race condition triggering the assert. This behavior of SuspendThread
has been described in this article, https://blogs.msdn.microsoft.com/oldnewthing/20150205-00/?p=44743/.
The fix is to make sure thread is really suspended before continue executing. The way to do so is by requesting the threads
context right away after SuspendThread call returns. This will force the kernel to wait until thread has really been suspended
since it need to return back a valid context record to the caller.
Fix also includes a smaller optimization. Since we retrieved the context later in the execution of mono_threads_suspend_begin_async_suspend,
the fix opens the possibility to pass a sigctx to thread_state_init_from_handle and then the implementation of thread_state_init_from_handle
could use passed sigctx in its work instead of request it again (if passed in). Since we need to get the context early on Windows, we could
reuse that, passing it into thread_state_init_from_handle aving us from several unnecessary kernel mode context switches otherwise needed
to open thread and get thread context. NOTE, this optimization is only used on Windows and other platforms will use default behavior.
When I simplified MONO_CORLIB_VERSION to only include major.minor
instead of major.minor.build in https://github.com/mono/mono/pull/5449
I forgot to apply the same change to the msvc copy of that logic.
Application hosting self-hosted website over https crashes when attempting to access a webpage over http. The patch described in the bug report below resolves the crash, and the commit in this pull request implements the fix.
https://bugzilla.xamarin.com/show_bug.cgi?id=52675
in some scenarios the reference could be loaded via some unsafe
constructs (i.e., it doesn't live on `vt_sp`), so we have to
distinguish that use case, otherwise we could underflow `vt_sp`.
fixes test-301.cs and test-305.cs
In the C parser check for empty at the outset.
In the managed parser, copy an empty string component to the built-up TypeSpec
and handle it in the Type.GetType (..., asmResolver, typeResolver) implementation
Field types are now lazily resolved and this breaks the RuntimeHelpers::InitializeArray icall.
The solution is to use mono_field_get_type_checked to ensure the type is there.
ASan has very few false-positives, quoting the ASan documentation
(https://github.com/google/sanitizers/wiki/AddressSanitizer#turning-off-instrumentation):
> In some cases a particular function should be ignored (not instrumented)
> by AddressSanitizer:
>
> [...]
>
> * Ignore a function that does some low-level magic (e.g. walking through
> the thread's stack bypassing the frame boundaries).
>
> [...]
Assume you have something like this:
```
$ cat invokecrasher.cs
using System;
using System.Reflection;
public class InvokeCrasher {
readonly static object[] default_args = new object[1] { new string[] {} };
public static void Main (string []args) {
Assembly assembly = Assembly.LoadFile ("crasher.exe");
try {
assembly.EntryPoint.Invoke (null, default_args);
} catch {
}
assembly.EntryPoint.Invoke (null, default_args);
}
}
```
```
$ cat crasher.cs
using System;
public class Crasher {
unsafe public static void Main (string []args) {
int i = 1337;
CrashMe (&i);
throw new Exception ();
}
unsafe static void CrashMe (int *p) {
// p = (int *) 0;
*p = 0;
}
}
```
On the first `Invoke ()` the interpreter goes through `ves_pinvoke_method`:
```
interp_push_lmf (&ext, frame);
mono_interp_enter_icall_trampoline (addr, margs);
interp_pop_lmf (&ext);
```
The LMF is needed for unwinding by mini. In this situation though,
`Crasher` throws an exception and goes through the exception handling machinery
of the interpreter which leads to missing out of the `interp_pop_lmf ()` call.
On the second `Invoke` we would therefore push the same address as an LMF
again, which leads to a LMF that points to itself as `previous_lmf`. If we
encounter a native crash in this state (as hinted with `p = (int *) 0; *p = 0;`),
the unwinding machinery would end up in an infinite loop.
It'd fail to find System.Runtime.dll and System.ValueTuple.dll.
Changed the csi.rsp to include those from the Facades/ dir and added a test.
Workaround for https://bugzilla.xamarin.com/show_bug.cgi?id=58965
[profiler] Clean up the makefile and address some issues with it.
* Don't link the profilers to libmono, except on mobile.
* The coverage profiler doesn't use zlib. Don't link to it.
* Fix the LIBADD variable for the VTune profiler.
* Add some comments for certain non-obvious aspects.
* Some style cleanup.
Also introduce a HOST_IOS variable in the build system which covers iOS, watchOS, and tvOS.
WSL, being Linux, declares IP_MTU_DISCOVER in its headers, but does not
actually support it. This is fixed in newer (preview) builds of WSL, but add
this workaround so Mono will work on older (stable) WSL versions.
https://github.com/mono/mono/pull/5680 added mmap/sendfile prototypes
but we should only use those when ANDROID_UNIFIED_HEADERS is defined
to avoid getting errors like:
```
/Users/alexander/dev/xamarin-android/external/mono/mono/utils/mono-compiler.h:157:7: error: conflicting types for 'mmap'
void* mmap (void*, size_t, int, int, int, __mono_off32_t);
^
/Users/alexander/android-toolchain/toolchains/arm-linux-androideabi-clang/bin/../sysroot/usr/include/sys/mman.h:47:15: note: previous declaration is here
extern void* mmap(void *, size_t, int, int, int, off_t);
^
/Users/alexander/dev/xamarin-android/external/mono/mono/utils/mono-compiler.h:166:9: error: conflicting types for 'sendfile'
ssize_t sendfile (int out_fd, int in_fd, __mono_off32_t* offset, size_t count);
^
/Users/alexander/android-toolchain/toolchains/arm-linux-androideabi-clang/bin/../sysroot/usr/include/sys/sendfile.h:36:16: note: previous declaration is here
extern ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);
```
It was writing to the current working directory before which
doesn't work on platforms where that directory is read-only.
Using the same setup/teardown methods as TypeBuilderTest we
instead create a directory in the temporary location and put
the files there.
* Don't link the profilers to libmono, except on mobile.
* The coverage profiler doesn't use zlib. Don't link to it.
* Fix the LIBADD variable for the VTune profiler.
* Add some comments for certain non-obvious aspects.
* Some style cleanup.
Also introduce a HOST_IOS variable in the build system which covers iOS,
watchOS, and tvOS.
* [jit] Don't insta-fail on faulty cominterop invocations.
* [runtime] New test for bug 8477.
* [jit] Implement mono_error_get_exception_name() and mono_mb_emit_exception_for_error()
* [jit] Throw an exception when a static method on a ComImport class is called.
Emit very basic codeview information into full AOT builds on Windows x64. The codeview information is far from complete and
is currently just initial work needed to get function symbol names to appear in native callstack that includes managed functions.
Described functions does not include parameters, local variables or line info at the moment, but could be extended in the future.
Fix also make sure linker will emit PDB files including information that can be picked up by debuggers. It is possible to disable
codeview info by passing "nodebug" to AOT compiler, this will also disable the generation of PDB files, if a DLL would have been build.
Emit needed sections when building Windows x64 full AOT targeting Clang for MS codegen in order for linker to
include entries in process unwind tables for full AOT:ed managed functions and trampolines. Implementation also includes
a cache used to minimize the number of duplicated unwind data section in each object file, reducing final image size.
On the CLR, two enumerators containing zero elements will
have reference equality if they are inflated with the same
generic type.
If comparing two enumerators which are not inflated (Array.Empty, for
instance), they are not equal when they contain zero elements.
This reference equality behavior is not compatible with treating
the enumerators as structs, as value types will not have reference
equality.
* [runtime] Avoid collecting coverage data for wrappers.
* [runtime] Return sensible information for methods which have no coverage info in mono_profiler_get_coverage_data ().
* [profiler] Emit coverage info for uncovered methods as well.
* Add new profile for monodroid tools
This allows the XA build to use these instead of needing to build net_4_x.
We build the assemblies against the .NET 4.6 reference assemblies.
* Skip monodroid_tools in verify (aka mcs-compileall)
Exclude it from the test_profiles since running tests makes no sense there.
Also refactor to exclude binary_reference_assemblies as well,
it was already excluded manually in mcs-compileall before.
TestHelper was previously excluded because the XA tests weren't built
as part of Mono but rather as part of XA test suite which included
its own version of the helper. Now, however (https://github.com/xamarin/xamarin-android/commit/e9daf5ea35709ce1bc6ba81c7c37d72d385bace2),
XA uses BCL+friends test assemblies built by Mono itself and so
we need to restore TestHelper in the build.
* [coverage-profiler] Collect coverage data at IL seq point locations.
* [coverage-profiler] Emit IL offsets instead of offsets between IL offsets. Bump format version.
Up until NDK release 14 Android SDK included a separate set of C header
files for each supported platform. NDK 14 introduced a new set of those
headers (they are NOT the same as the old ones) which unifies support
for all of the platforms so that bug fixes are available for all the
API levels without having to backport etc. With NDK 15 the unified headers
become the default ones (including when creating standalone toolchains)
and with NDK 16 (in beta currently) the old per-platform headers are removed.
Unfortunately, the new headers introduce breaking changes which made it
impossible to build Mono with NDK configured to use them. This commit makes
a handful of changes to Mono which make it build with unified headers.
Make libmono-static lib file include all needed runtime libs making it easier to
link and distribute as part of Mono SDK.
Commit also updates linking of vcxprojs in mono.sln to use merged static lib.
* [ci] Allow setting custom mono flags for test runs via MONO_TEST_FLAGS.
* [ci] Make the handling of CFLAGS a bit more flexible in run-jenkins.sh.
* [ci] Generalize collect-coverage to handle more targets.
* [trace] remove code that has no effect
* [trace] move program assembly out of MonoTraceSpec
The assembly member represents the program assembly. It's
information the trace spec is matched against, not part of
the trace spec per-se (if two trace specs exist for two purposes
we would still have one program assembly)
* [trace] remove side effects from get_string()
On the way towards supporting multiple trace specs,
remove side effects from get_string() function.
* [trace] remove side effects from get_token()
Remove side effects from get_token() to allow handling
multiple trace specs.
* [trace] fix handling of double exclusion and disabled
When encountering "disabled", do not add an entry to
the trace spec
Fix error handling around double "-" - get_spec()
never returns TOKEN_EXCLUDE and the recursion can
be easily avoided.
* [trace] remove side effects from get_spec()
Another step in making the trace options reusable.
* [trace] rename mono_trace_parse_options() to mono_trace_set_options()
This routine actually sets the tracing options, not just parses an
option string, so set_ is more suitable. This frees up the
mono_trace_parse_options() name for pure parsing, when we later
reuse the parsing code.
* [trace] make tracing options API reusable
Add APIs that parse tracing options and evaluate a method
against the parsed options. The tracing functionality now uses
this API, but other components can use this to apply an operation
to a method based on policy (e.g. profiling)
* [trace] rename MonoTraceSpec to MonoCallSpec
In preparation for reusing call specification beyond the
tracer, rename the data structure - it now only specifies
a set of calls, without indication what should be done with
them.
* [trace] rename mono_trace_set_assembly to mono_callspec_set_assembly
As it becoming a reuse candidate, we remove the "trace" component
from the name.
* [trace-metadata] move callspec code into its own module
Introduce callspec.c/h which encapsulate the call specification
functionality.
* [profiler] add "callspec" option to log profiler
The callspec option define which methods get instrumented
at JIT time with entry/exit calls to the profiler. The
syntax is same as the tracer (--trace=) syntax. To
distinguish between profiler options and callspec, wrap the
callspec with double quotes, as in:
--profile=log:callspec="all-mscorlib",calls
Since this typically runs from a shell, the double quotes have to be
escaped or wrapped in single quotes, as in:
mono '--profile=log:callspec="all-mscorlib",calls' prog.exe
* [metadata] add an error return string to callspec parsing
Instead of printing parsing error messages to standard error,
return an error string. That allows the client to do the right thing
with the error.
Current implementation of Windows builds in mkbundle is not supporting
Visual Studio toolchains and Windows SDK's in a working way. Windows version
of mkbundle also lacked support for 64-bit builds together with a dependency on
GCC assembler etc.
This commit improves things in many different areas. The following toolchains
are intended to work together with this commit:
VS2013, VS2015, VS2017.
NOTE, default Mono SDK distribution is build targeting VS2015/VS2017 and static
version of libmono-static.lib won’t work with VS2013. If static use case is needed
with VS2013, a custom build mono under VS2013 must be used. Dynamic use case is
working as expected for all three versions.
The commit also improves the support for Cygwin GCC compatible toolchains on Windows.
The commit adds support to use installed versions of both Windows 8.1 as well
as Windows 10 SDK's together with all above VS toolchains.
The commit extends support to include 64-bit mkbundle builds (using all supported
Windows toolchains). The target is decided based on mkbundle process type, 32-bit
mono builds 32-bit bundle and 64-bit mono builds 64-bit bundle.
mkbundle might still need to have a working GCC as.exe when running, but this commit
also adds support for Clang for VS CodeGen as assembler available in VS2015 Update3
and VS2017 (separate option in VS setup). When using this option there is no needed
for available GCC toolchains when running mkbundle on Windows.
A recommended way of running mkbundle on Windows is by using one of the targeted toolchains
development consoles. This way mkbundle will get all needed paths and installation folders
directly from the development consoles environment, matching a predefined setup.
Old mkbundle environment variables on Windows will continue to work. There are also a number
of new variables that can be set (or are set by the VS development consoles). The important ones
are:
VisualStudioVersion: set to pick a specific VS version, like 12.0, 14.0 or 15.0. If a none existing
version is specified, mkbundle will fallback to latest installed version.
WindowsSdkVersion: set to pick a specific Windows SDK version, like 8.1, 10.0.10240.0, 10.0.15063.0 etc.
If a none existing version is specified, mkbundle will fallback to latest installed version.
AS: If Clang for VS CodeGen is not installed this must point to a working as.exe assembler.
MONOPREFIX: set to pick a custom Mono SDK install root directory (need to match the architecture of mkbundle
process running). If not set, mkbundle will look for installed Mono SDK’s matching targeted architecture.
MONOLIB: if a different library name is used, it can be specified here. It is also possible to add an absolute
path to the mono library used in linking. NOTE, correct library needs to be supplied for static/dynamic use cases.
INCLUDE: override all custom include path handling, normally set by VS developer consoles.
LIB: override all custom lib path handling, normally set by VS developer consoles.
VCCRT: Gives possibility to use static or dynamic C-Runtime linking. By default mkbundle will use dynamic C-Runtime
linking on Windows to be compatible with default Mono SDK distribution. If a custom build Mono
using static C-Runtime linkage is used, setting this variable to MT (default MD), will link using static
C-Runtime.
VCSUBSYSTEM: mkbundle will by default use windows subsystem. If console subsystem is preferred this variable
can be set to console.
Should resolve:
https://bugzilla.xamarin.com/show_bug.cgi?id=57893
and partial resolves (needs https://github.com/mono/mono/pull/5656 as well):
https://bugzilla.xamarin.com/show_bug.cgi?id=57892
null is a valid value in a JSON array, so there is no reason forbid
adding null to the array. JsonArray.Save() already handles null values in
the array.
* [corlib] Make Marshal.BufferToBSTR(Array, int) non-public again
It was accidentally made public in https://github.com/mono/mono/commit/c5cdfaec1e0973ced3f97ef589cd0bece56067ad.
Unfortunately this was before we had the API diff check on Mono and the manual checks in XI/XA integration didn't catch it either.
* Bump API snapshot submodule
In mono_image_create_token we are passed in a managed reflection object and we
need to create a token for it and optionally register it so that we can resolve
that token back to a runtime structure and managed object later.
For a MonoReflectionMethod object that refers to a method from outside the
current dynamic image, we need to generate a memberref token. It will be the
same token for the same underlying MonoMethod*. When we go to register the
token with mono_dynamic_image_register_token we need to pass a managed object.
Unfortunately two MonoReflectionMethod objects could refer to the same
MonoMethod* but differ in their ReflectedType, so just registering the
passed-in MonoReflectionMethod means we could assert in
mono_dynamic_image_register_token because previously we may have registered the
same method via a different ReflectedType.
So what we do is we cal mono_method_get_object_handle with NULL for the
reflected type - which corresponds to just using the DeclaringType of the given
MonoMethod*.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=59364
Previously, we mapped fieldref tokens to MonoReflectionField managed objects,
But the object is just used as a key for caching the token so we may as well
use the native field instead of a managed object.
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=59364
We need to cause SRE to generate the same methodref/fieldref token from two
different reflection objects. That happens if you get the same method or field
via a base and a derived class so that the MemberInfo:DeclaredType is different
but the underlying MonoMethod* or MonoClassField* is the same.
HttpRequestListener throws on incorrect cookie name. It throws CookieException ("Name contains invalid characters"). There are many cookies out there that unfortunately do not conform to the guidelines and HttpRequestListener will kill the request in such a case. The .Net framework under windows lets the request through however.
Included is a patch HttpListenerRequest as well as a test with a bad cookie name.
I have tested this under linux(master branch) and .net (4.0), they now both have the same behavior.
Without it you get errors like the following in old-style mkbundle:
```
Undefined symbols for architecture x86_64:
"_CFLocaleCopyCurrent", referenced from:
_ves_icall_System_Globalization_CultureInfo_get_current_locale_name in libmono-2.0.a(libmonoruntimesgen_la-locales.o)
"_CFLocaleGetIdentifier", referenced from:
_ves_icall_System_Globalization_CultureInfo_get_current_locale_name in libmono-2.0.a(libmonoruntimesgen_la-locales.o)
"_CFLocaleGetValue", referenced from:
_ves_icall_System_Globalization_CultureInfo_get_current_locale_name in libmono-2.0.a(libmonoruntimesgen_la-locales.o)
"_CFRelease", referenced from:
_ves_icall_System_Globalization_CultureInfo_get_current_locale_name in libmono-2.0.a(libmonoruntimesgen_la-locales.o)
...
```
We actually documented this in the 3.4 release notes: http://www.mono-project.com/docs/about-mono/releases/3.4.0/#breaking-changes
However this means that you had to use the "-c" mkbundle option
to only generate the .c stub so you could pass those additional libraries.
* [jit] Add a mono_arch_dyn_call_get_buf_size () arch specific function which returns the size of the buffer required for a given dyn call. Use this instead of a fixed size buffer, to allow backends to use variable sized buffers later.
* [amd64] Add support for unlimited size/number of arguments to the dyncall code.
* [arm64] Add support for unlimited size/number of arguments to the dyncall code. Part of the fix for #59184.
In case StringToHeap (string, Encoding) was called with a null string, it would unconditionally reference the string when trying to query the string's length.
Bug 10074 - Error while updating status of command: MonoDevelop.Ide.Commands.ViewCommands.LayoutList
Suppose we want to know C.IsAssignableFrom (T1):
```
class C { }
class G<T1, T2> where T1 : T2, T2 : C { }
```
Previously, we would get `False`, because we only checked the constraints of T1
if C was an interface or another gparam. Now Instead we always consider the
constraints in `A.IsAssignableFrom (B)` whenever `B` is a gparam.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=58809
Check that generic parameters's constraints properly affect the subclass and
interface relationships even when the constraints relate several of the generic
parameters themselves.
* Add support for mono_threads_add_joinable_thread and friends on Windows.
Current Windows implementation doesn't have support for the joinable thread
implementation in threads.c. Joinable threads are used by the runtime during
shutdown to coordinate with exit of platform threads.
Since threads detaching and exiting during shutdown could still use or provide
important resources, like GC memory, lacking support for this feature could
potentially expose the implementation to various shutdown race conditions.
Commit also change requested permission on a thread handle when opening it for
synchronization purposes. No need to request all thread access when handle is only
used for synchronization, like in WaitForXXX API calls.
* Fix race between mono_thread_detach_internal and mono_thread_manage.
There is a race during shutdown when main tread is running mono_thread_manage and
attached threads are running mono_thread_detach_internal. The problem is related to
the removal from the registered threads list since mono_thread_manage will pick
threads to wait upon from that list. If a thread removes itself from the list
using mono_thread_detach_internal it will then race against runtime shutdown
and the removal of used resources still in used by mono_thread_detach_intenral,
like MonoInternalThread.
This race could trigger the assert seen in bugzilla:
https://bugzilla.xamarin.com/show_bug.cgi?id=58770
or other undefined behavior depending on where the detached thread resume execution
after main thread has shutdown the runtime, but not yet terminated the process.
The fix makes sure threads that are detaching during shutdown ends up on the joinable
threads list. Threads on that list will be waited upon by the main thread during shutdown,
mono_thread_cleanup. This will make sure the detached thread finishes the remaining of
mono_thread_detach_internal and potential other code still using GC memory during shutdown.
Threads already on the threads list will already be waited upon by mono_thread_manage during
shutdown (if not removed by mono_thread_detach_internal triggering this race), so this change
won't add additional threads to be waited up by the runtime. It just makes the shutdown more
reliable using already available concepts (like the joinable threads list).
* Fix warning C4141 on Windows MSVC compiler.
* Updated with review feedback.
* Prevent race between finalizer and main thread to join same thread multiple times.
Checking against joinable_threads list in mono_threads_add_joinable_thread is not enough.
There is a small chance that the same runtime thread could get on the list twice since
mono_threads_add_joinable_thread could be called multiple times for the the same tid.
This will work under Windows but is undefined behavior on POSIX's platforms.
This could happen if the finalizer thread calls mono_threads_join_threads when a thread
is detaching and have added itself to the joinable_threads, but before unregister_thread
has been called. Finalizer thread will then take tid from list and wait, this will cause
the second call to mono_threads_add_joinable_thread to not find itself in the joinable_threads
and add tid a second time. NOTE, this race only applies to runtime threads added to the
joinable_threads list.
Fix adds an additional method to add runtime threads to the list. This method will only add to
list if its indeed a runtime thread and doesn’t already have an outstanding pending native join
request. This method is called by code previously checking runtime_thread flag before adding to
joinable_threads list. This will prevent the scenario when the same MonoThreadInfo add its tid to
the joinable_threads list multiple times due to above race condition.
A DynamicMethod can be placed in a SRE module and it must respect any RuntimeCompatibilityAttribute set on that assembly.
We do that by updating the runtime side list of cattr in the AssemblyBuilder when a RuntimeCompatibilityAttribute is set using SetCustomAttribute.
and also setup_interface_offsets.
A gparam is never a real interface so we can just short circuit
if we see a gparam during interface collection. (A gparam may be instantiated
with an interface --- but ginst interface offsets are processed anew when the
ginst is initialized in mono_class_init, not somehow extracted from the gtd and
the MonoGenericContext).
Introduce MonoDynamicMethod that holds the assembly of a DM (and TB).
Use it to determine the RuntimeWrappedException policy for exceptions.
This is needed cuz the assembly of a MonoMethod is normally found using method->parent->image->assembly.
But this doesn't work with DynamicMethods that don't define an owner type as they are forced to corlib's policy.
The default policy for DM's is to not wrap those exceptions and in the case a Module is provided, the policy of that module must be respected.
This commit handles all cases but when a Module is a SRE module.
Mono.Debugger.Soft has low frequency hangs in InspectThreadSuspenedOnWaitOne test.
This method launch the debuggee (dtest-app.exe), sets a breakpoint on a method just
doing an infinite OS wait, validate that the breakpoint gets hit and resumes debuggee.
After resume from breakpoint debuggee will hit the infinite OS wait and the debugger test
will suspend and shutdown the process.
In order for mono debugger to handle the shutdown request it will suspend all managed threads
using mono_thread_suspend_all_other_threads. This method uses a pooling schema until all threads
have reported that they are suspended. Since one of the threads are doing an infinite OS wait we
entered the land of APC (Asynchron Procedure Calls) used on Windows to alert waitable threads.
The reason for the hang is the fact that the OS won’t return from the wait until all queued APC’s
have been executed. Since the loop sending async suspend requests to the
threads mono_thread_suspend_all_other_threads can run faster (including suspending/resuming the
thread that need to consume APC’s in the process) then the dequeue and execute of the queued APC’s, the
wait won’t break, meaning that the thread won’t be able to set the mono suspend state causing the
mono_thread_suspend_all_other_threads to run forever. This is highly timing dependent and will only reproduce
sporadic, but I was able to isolate and do a solid repro locally while working on the fix.
The fix makes sure we don’t post a new suspend APC if there is already one in flight with a pending unhandled
interruption. This will make sure we won’t flood the APC queue on Windows preventing the thread from suspending.
Tests that we can unload domain where the threads reset the abort exception and that this exception is converted to AppDomainUnloadedException in the caller domain.
- have all counters in a global place and initialise them in `mono_trampolines_init ()`
- use `Unlocked* ()` and `mono_trampolines_lock ()` to mark / synchronise all racy counters
[TSan] Unlock mono_g_hash_table_max_chain_length
I would suggest using `Unlocked* ()` here. `mono_g_hash_table_find_slot ()` is called relatively often and, unlike increment or add operations, read and write operations (without a global surrounding lock) do not gain much (if anything) by being interlocked as long as they can be read and written by one instruction. That should be true for 32-bit integers and Mono's supported platforms.
[TSan] Unlock fastpath when checking domains_to_finalize
I understand that the affected line is a fastpath which seems absolutely fine to me as it is properly checked later. It is, however, rightfully, detected as a data race by Clang's ThreadSanitizer. I would, therefore, suggest using `UnlockedReadPointer ()` to mark this race as known + accepted.
This should reduce the amount of I/O system calls we do, and should be fine
in terms of memory usage since the profiler tries to keep buffers small (64k),
and latency since the profiler flushes buffers every second.
This changes the API somewhat so that users no longer have to construct a
LogReader; this is now done internally, and the type is no longer public. Also,
the LogProcessor now leaves the given stream open, so it's up to the user to
close it.
The problem was that the base Stream.ReadByte () method allocates a temporary
byte array and then calls Read (..., 1) on it. To solve this, we override
ReadByte () in LogStream and use a private buffer to hold the result.
It's a bit of a mystery to me why Stream.ReadByte () does it this way. The
documentation for Stream explicitly says that instance methods aren't thread
safe, so it would be perfectly fine for Stream.ReadByte () to do what we do
here...
* [loader] If signaling recursive type initialize, don't double free
If we detect that a recursive type initialization is happening, we should leave
without removing the class from the init_pending_tld_id list. Otherwise we get
a double-free when the outer recursive call finally finishes and tries to
remove the same element.
Also re-load the init_list from TLS since a recursive call to mono_class_init could
have modified it between the time the current mono_class_init call started and
when it is finishing.
* [loader] Improve error message when a field's type is a failed class
Add the class failure to the field failure error message.
* [tests] Check that runtime can represent recursive structs
Regression tests for https://bugzilla.xamarin.com/show_bug.cgi?id=43563
* [loader] Init MonoClass:sizes.element_size lazily (Fixes#43563)
Originally mono_bounded_array_class_get () would populate
MonoClass:sizes.element_size as soon as the MonoClass for the array was needed.
This is a problem because we cannot call mono_class_array_element_size () on
the element class on a valuetype until mono_class_layout_fields () finishes
initializing it.
That means that structs which contain an array of themselves would hit the
recursive initialization check in mono_class_setup_fields and the MonoClass for
the element class would be marked as failed to load.
Instead we rely on the MonoClass:size_inited bit to tell us whether the array
class has been initialized and if not, we set the array element size in
mono_class_layout_fields.
This is possible because MonoClass:sizes.element_size is only really needed to
know how to allocate space for an array. When laying out a class that contains
an array we don't need the element size - they array is just a reference type.
Example:
```csharp
struct S {
static S[][] foo;
}
```
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=43563
This change fixes a crash we get in resgen when building without
X11 installed. The bug got introduced when fixing Xamarin-395.
Change-Id: If81a4a3ca4db7a1b0156480ad49bd61610ecebf0
Internal version number (not in any way related to the TLS Version).
Used by the web-tests to check whether the current Mono contains certain
features or bug fixes.
Negative version numbers are reserved for martin work branches.
This comes in reverse order, compared to other backtraces in the MLPD, so
reverse it before sending it to visitors, so that it comes in the same
format as the rest of backtraces.
Running the MonoTests.System.Net.HttpRequestStreamTest under debugger reveals this
problem. WSACleanup is freeing an invalid handle as part of network shutdown.
This happens since mono_w32socket_close calls incorrect win32 API when closing sockets.
It currently calls CloseHandle, while it should call closesocket. This probably cause
problems in winsock book keeping of active sockets, and when closing the network layer,
winsock will try to close handles that it still open, but since the handles have already been closed
by incorrect call to CloseHandle, it will close an “invalid handle” either causing the exception
or even worse, close a different handle currently in use, causing undefined behavior
during the rest of mono shutdown.
Fix is to switch to correct API when closing sockets on Windows, closesocket instread of CloseHandle.
MonoTests.System.Net.HttpRequestStreamTest suite has sporadic failures on Windows x64
with following exception:
System.Net.Sockets.SocketException : An operation was attempted on something that is not a socket.
This happens due to a data type and constant size mismatch. w32socket.h defines
INVALID_SOCKET and SOCKET_ERROR for all platforms. On Windows x64, SOCKET is defined
by winsock2.h as 64-bit type as well as INVALID_SOCKET constant, but above code will
define INVALID_SOCKET as a 32-bit constant value. This will in turn cause code to sporadically
fail to detect invalid sockets as returned by win32 API's. This will in turn cause the socket
exception when code continues to use socket as argument to win32 socket API’s.
Current “invalid” x64 codegen for expression:
if (sock == INVALID_SOCKET)
mov eax,0FFFFFFFFh
cmp rsi,rax
and with fixed defines, correct 64-bit cmp instruction:
cmp rsi,0FFFFFFFFFFFFFFFFh
Fix makes sure we get the defines of INVALID_SOCKET and SOCKET_ERROR from winsock2.h
on Windows platforms to be consistent with define of SOCKET type.
The differences from v14 are small, and given it is the current "stable"
MLPD version, it's worth supporting it. The differences are:
* ImagePointer field not present in v13 Assembly*Event's
* In MonitorEvent, LogMonitorEvent is not in a separate field, but included
as a flag in the extType field.
* SampleHitEvent's have a type field in v13, which was removed in v14, because
only cycles samples are emitted.
* MONO_GC_EVENT_{MARK,RECLAIM}_{START,END} were removed in v14
* SampleUnmanagedBinary's SegmentPointer is not based on ptr_base in v13
* In v13, HeapRootsEvent's Attributes is (wrongly) a byte, in v14 this was
fixed and changed back to a uleb128
We had previously responded to bad performance on android by stubbing out
ves_icall_System_Runtime_CompilerServices_RuntimeHelpers_SufficientExecutionStack
on android. This was necessary because the call to pthread_attr_getstack ()
will read /proc/self/maps. When used inside of a hot function, the performance is terrible.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=58911
Globally loaded modules would previously call LoadLibrary on Windows, but never FreeLibrary. This would result in said library keeping an internal reference counter of 1 until the application exited its entry-point, resulting in possible shutdown issues.
This commit makes sure that we correctly free modules (and unload them in the platform-specific APIs) whenever Mono itself is shutting down, ensuring the expected result of Mono-loaded libraries being correctly freed.
The verification algorithm is inspired on internal specs by the Roslyn team but adapted to what it generates today.
Here's how this patch works:
We introduce a new verification type, SAFE_BYREF, that's used for a byref value that is safe to return from the stack.
It's unverifiable to return a byref value that is not marked SAFE_BYREF.
We mark the following values are SAFE_BYREF:
- byref arguments, unless it's the `this` arg of a valuetype instance method
- return values of method calls when all byref arguments have SAFE_BYREF values - the this arg is ignored.
- the address of a static field (LDSFLDA)
- the address of an array element (LDELEMA)
- the address of a field if the receiver is either a SAFE_BYREF value or a reference
Notoriously from the above is the value of local variables. We took a conservative approach of unsafe tainting.
We do this by associating 3 states to a local: unassigned (initial value of zero), assigned and safe (SAFE_BYREF_LOCAL), assigned and unsafe (UNSAFE_BYREF_LOCAL)
When loading a local, we set its value as SAFE_BYREF if the local is in the SAFE_BYREF_LOCAL state.
When storing to a local, we set it to SAFE_BYREF_LOCAL if, only if, it's not marked as UNSAFE_BYREF_LOCAL and the value is SAFE_BYREF.
If we store a non-safe value to a local, we mark it as UNSAFE_BYREF_LOCAL.
If we store a non-safe value to a SAFE_BYREF_LOCAL local, we mark the method as unverifiable.
This algorithm makes sure we don't mix safe and unsafe byref and side with safety in case of control-flow dependent values.
[TSan] Interlock and unlock MonoJitStats
This is the first part of telling TSan what to do with `MonoJitStats`; I dealt with all the `gint32` values and partly touched the `gboolean` value (see `FIXME`). However, `MonoJitStats` also contains `gdouble` which can (1) probably be interlocked and (2) will be updated in a later step, together with the `FIXME`, as soon as an updated version of the atomic interface exists.
I did my best to distinguish between perf. critical parts and parts where `Interlocked* ()` seems to work perfectly fine. As before, if I misjudged anything, I would kindly ask to comment the affected operations, and I will update them accordingly.
More (technical) details can be found in the commit messages.
The ManualResetEvent wouldn't be signaled when an exception happens
in the reader loop so we'd deadlock in Read().
I'm still investigating where the exception comes from but this
should at least help unblocking CI.
https://bugzilla.xamarin.com/show_bug.cgi?id=46683
* Revert "[threads] Fix leaking threads: SGen Worker and Finalizer (#5284)"
The sgen-specific cleanup cannot be run before the sgen-agnostic cleanup
This reverts commit 7db0fb0c88.
* [threads] Make sure we do not leak the finalizer and sgen threadpool threads
* [Tests] Fix Mono.Data.Tds tests on iOS
The modified tests failed on iOS following PR:
https://github.com/xamarin/xamarin-macios/pull/2580 that adds support
for Xharness to run the Mono.Data.Tds on Xamarin.iOS. With the changes
the tests run a expected.
* Close Listener when done.
[TSan] Tackle MonoPerfCounters
With `MonoPerfCounters` taking part in many races, I thought it's finally time to attend to it. If I am not mistaken, most (if not all) load / store operations can be interlocked. If I am wrong, I would kindly ask to quickly comment the respective perf. critial operations and I will change them to `Unlocked* ()`.
Furthermore, a few details:
* updated all fields to signed types as `Interlocked* ()` functions exist for these types already
* upgraded a few values to `64-bit` as other `64-bit` values are assigned to them
* fixed a few `FIXME`s in `predef_writable_update ()` that were connected to `Interlocked* ()` functions
[TSan] Mark racy counters in metadata.c
- using `gint32` instead of `int` should not be an issue
- `img_set_count` is interlocked by `image_sets_lock ()` - `UnlockedIncrement ()` is just used for completeness / documentation
- `++img_set_cache_(hit|miss)` is called quite often and is connected to caching: it seems to me as if interlocking these counters would be a bad idea (at least for cache hits)
* Fix leaking threads: SGen Worker and Finalizer
- https://bugzilla.xamarin.com/show_bug.cgi?id=58317
- stop SGen workers before the finalizer stops
- clean up SGen workers with the Finalizer
- remove `mono_thread_join (GUINT_TO_POINTER (gc_thread->tid));` as we detach the Finalizer with `mono_threads_join_threads ()` within `mono_gc_cleanup ()`
* [fixup!] Move counting variable into the loop initialiser and add a `(gpointer)` cast
* Reorganise counters:
- use `Interlocked* ()` and `Unlocked* ()` to fix / mark (possible) races
- change the initialisation location and the visbility of some counters
- fix a few typos
* Extend the warning when re-registering counters
* also print counter address if we have a duplicate
Make sure all events have all fields initialized. This was missing setting
Buffer and Timestamp properties when creating the different LogEvent* subclasses.
* [Mono.Security]: Remove some unused `Mono.Security.Interface` classes.
* Mono.Security.Interface: removed `IBufferOffsetSize` and `BufferOffsetSize`
(these were not general-purpose BOS APIs, but depend on the internal
`SecretParameters` class).
* Mono.Security.Interface: removed `SecretParameters`, `SecureBuffer`,
`IMonoTlsEventSink`, `TlsBuffer` and `TlsMultiBuffer`.
* Bump API snapshot submodule
[TSan] Interlocking loader.c
`loader.c` contains four statistics counters and all of them are invovled in data races. This PR focuses on dealing with them:
- All of them can be `gint32` as they are registered as `MONO_COUNTER_INT` anyways.
- Since there is already a lot of locking involved in `loader.c` (including an approved usage of `Interlocked* ()` with with `mono_stats`), I think that `Interlocked* ()` can be used here instead of `Unlocked* ()`. If this assumption is wrong, I would kindly ask to correct me by commenting the affected rows and I will change it to `Unlocked* ()`.
* [bcl] Use RuntimeHelpers.GetHashCode () for getting the hash code of the delegate target to avoid calling user defined hash code implementations which can throw exceptions. Fixes a regression introduced by a48bc43985.
* add test for #59235https://bugzilla.xamarin.com/show_bug.cgi?id=59235
* [fixup] RuntimeHelpers.GetHashCode handles null
This is the behavior of .NET. After this patch the code on Mono for Windows
will make sure the underlying native thread of a managed thread has died
before Thread.Join() returns.
This PR builds on PR #5454 but makes it Windows specific. PR #5454 was
reverted since it caused crashes on some Unix platforms.
With the introduction of magic array interfaces, they must be handled as if they
were variant if they are being dispatched against an array.
This was not being done in common_trampoline and resulted in the IMT thunk never
getting rebuilt and getting decent perf.
With this patch, dispatch to simple methods such as Array::Count over a magic interface
in a covariant case (such as IList<object> dispatch onto string[]) will accrue gvi's.
On a trivial benchmark of executing Count 1M times, perf goes from 760ms to 50ms.
- use `Unlocked* ()` for `class_gparam_count`, `classes_size` and `inflated_methods_size`
- dead code: `class_ext_size`
- fix a typo: "the the" -> "let the"
Whenever a test fails we retry it five times and then decide the
overall result based on that. If three or more of the five retries
fail too then the overall result is FAIL, two or lower means PASS.
We're modifying nunitlite here so this only works for those tests
right now, we'd need to add it to the other test runners too.
The cominterop_get_function_pointer icall has a wrapper which has a
trampoline. When we enter the trampoline mono_marshal_emit_native_wrapper
already switched us to blocking.
This fixes assertions due to d0e103fcb4 in
cooperative GC mode.
mono_marshal_set_last_error is called from a P/Invoke wrapper just after the
pinvoked method returns before we transition the thread state back to running
from blocking. If mono_marshal_set_last_error had a wrapper, we would invoke
the trampoline (mono_magic_trampoline) to JIT the wrapper while in blocking
mode, which would trigger the assertion.
* [System] Fix a few hardcoded socket ports in tests
Those could've shown up as "address already in use" in CI.
* [System.Runtime.Remoting] Fix a few hardcoded socket ports in tests
Those could've shown up as "address already in use" in CI.
Additionally remove a copy of RemotingServicesTest.cs from corlib
which also exists in System.Runtime.Remoting in updated form.
* [System.ServiceModel] Fix a few hardcoded socket ports in tests
Those could've shown up as "address already in use" in CI.
* [System.Net.Http] Fix a few hardcoded socket ports in tests
Those could've shown up as "address already in use" in CI.
The additional "keep-alive" header in Send_Complete_NoContent() and
Send_Transfer_Encoding_Chunked() is because we were using the same
port for all tests before so other tests would clear the header.
This doesn't happen now that we use distinct test ports.
* [System.ServiceModel.Web] Fix a few hardcoded socket ports in tests
Those could've shown up as "address already in use" in CI.
* The sizes of `glong` and `gsize` differ on 64-bit Windows.
* In order to avoid uninitialized data in the high four bytes of the `bytes` argument to `mono_unicode_from_external`, call `g_utf8_to_utf16` with a `glong`, then copy the result.
They are implemented via a global lock, which can lead to deadlooks in
some situations, e.g.
```
-0 0xb6c92e14 in sigsuspend () from /lib/arm-linux-gnueabi/libc.so.6
-1 0x0043f3b4 in suspend_signal_handler (_dummy=35, info=0xb4afe6d0, context=0xb4afe750) at mono-threads-posix-signals.c:177
-2 <signal handler called>
-3 0xb6de6bc4 in __pthread_mutex_unlock_usercnt () from /lib/arm-linux-gnueabi/libpthread.so.0
-4 0x00440f00 in InterlockedCompareExchange64 (dest=0x530700 <worker+64>, exch=0, comp=0) at atomic.c:578
-5 0x002f228c in InterlockedRead64 (src=0x530700 <worker+64>) at ../../mono/utils/atomic.h:398
-6 0x002f29a0 in COUNTER_READ () at threadpool-worker-default.c:194
-7 0x002f3320 in worker_park () at threadpool-worker-default.c:426
-8 0x002f3774 in worker_thread (unused=0x0) at threadpool-worker-default.c:488
-9 0x002e66b0 in start_wrapper_internal (start_info=0x0, stack_ptr=0xb4b00000) at threads.c:982
-10 0x002e6894 in start_wrapper (data=0x5a8f38) at threads.c:1044
-11 0xb6de31a8 in start_thread () from /lib/arm-linux-gnueabi/libpthread.so.0
-12 0xb6d3a1bc in ?? () from /lib/arm-linux-gnueabi/libc.so.6
Backtrace stopped: previous frame identical to this frame (corrupt stack?)
Thread 4 (Thread 0xb40ff440 (LWP 10198)):
-0 0xb6deb56c in __lll_lock_wait () from /lib/arm-linux-gnueabi/libpthread.so.0
-1 0xb6de584c in pthread_mutex_lock () from /lib/arm-linux-gnueabi/libpthread.so.0
-2 0x00440e6c in InterlockedCompareExchange64 (dest=0x559868 <gc_stats+8>, exch=2855648, comp=2844091) at atomic.c:570
-3 0x0039bdcc in InterlockedAdd64 (dest=0x559868 <gc_stats+8>, add=11557) at ../../mono/utils/atomic.h:392
-4 0x003a1b50 in collect_nursery (reason=0x5083f4 "Nursery full", is_overflow=0, unpin_queue=0x0) at sgen-gc.c:1865
-5 0x003a3794 in sgen_perform_collection (requested_size=4096, generation_to_collect=0, reason=0x5083f4 "Nursery full", wait_to_finish=0, stw=1) at sgen-gc.c:2539
-6 0x003a35f0 in sgen_ensure_free_space (size=4096, generation=0) at sgen-gc.c:2505
-7 0x00389db0 in sgen_alloc_obj_nolock (vtable=0xb4d174d0, size=64) at sgen-alloc.c:256
-8 0x0036e330 in mono_gc_alloc_vector (vtable=0xb4d174d0, size=64, max_length=12) at sgen-mono.c:1743
-9 0xb6c16a38 in ?? ()
Backtrace stopped: previous frame identical to this frame (corrupt stack?)
```
fixes https://bugzilla.xamarin.com/show_bug.cgi?id=59039
Encountered this message while running the new mkbundle simple-cross functionality introduced recently. "Function not supported" is seen on both Mac OS X and Ubuntu. Will possibly file a separate bug since HAVE_MKDTEMP should be true... but it should be "Function mkdtemp not supported" in any case.
It's causing unnecessary complexity because we need to create a new
monolite when bumping the .build number in a major.minor.build
version like from 5.2.0 -> 5.2.1
corlib version bumps are very rare in those cases and even then
you can just increment the MONO_CORLIB_COUNTER variable.
* Cleanup debugging and use the same technique from the new web stack.
* The MARTIN_DEBUG conditional has been renamed into MONO_TLS_DEBUG.
* Moved the actual implementation into MNS.MonoTlsProviderFactory.
* We now use an environment variable called 'MONO_TLS_DEBUG' to
enable debugging (so to get debugging, you need to both compile with
-define:MONO_TLS_DEBUG and set that environment variable).
The new web stack has a conditional and environment variable called
'MARTIN_WEB_DEBUG'.
* Use [Conditional] instead of #if.
Fixes ParameterDirection.InputOutput type parameters not sending
the "output" modifier to server which creates a conflict resulting
in an exception server side.
* [btls]: Bind new native APIs to support renegotiation.
* mono_btls_ssl_set_renegotiate_mode(), mono_btls_ssl_renegotiate_pending():
New native methods.
* MonoBtlsSsl: Added SetRenegotiateMode() and RenegotiatePending().
* MonoBtlsSslRenegotiateMode: New internal enum.
* [System]: Cleanup internal Mono.Net.Security.MobileTlsContext APIs.
Use tuple `(int ret, bool wantMore)' return value instead of out variables.
* [System]: Check for pending exceptions in MobileAuthenticatedStream.
This should fix some issues where we're hanging instead of throwing
an exception if something went wrong.
The wasm backend is inspired on the x86 one with a few key differences:
1) It assumes a different aot runtime will be used to deal with all the weirdness of wasm.
In particular, it can run under MONO_AOT_MODE_INTERP_LLVMONLY without an actual working AOT compiler.
2) It's the only non-ISA based backend, so lots of weird things.
Like, no registers or addressable stack - for realsies.
The z13 supports some useful instructions that can be exploited
by the JIT. Most notably the compare-and-branch instructions can
reduce a two instruction sequence to one. The load-and-add command
eliminates the more complex compare-and-swap sequence.
The z13 also supports three operand instructions dst,src1,src2
which eliminate checks and loads for instructions like add and subtract.
The unaligned.cs test has been changed to cater for big-endian platforms.
For s390x only, the --trace option will result in a file per thread
being created rather than the traces being written to stdout and
sometimes intermixing incomplete trace entries.
[TSan] Unlocking MonoStats, GCStats and JITGCStats
As the `Unlocked* ()` functions have been approved in https://github.com/mono/mono/pull/5310, I used them to blacklist some of the most obvious counting variables whose data races should be ignored: `MonoStats`, `GCStats` and `JITGCStats` (more to follow if approved).
Please find details about all changes within the commit messages.
Added -t:library since mcd does not interpret output filename for dll suffix.
Without -t:library option, it fails to compile.
{code}
mono$ mcs -debug+ -r:System.Core Options.cs -o:Mono.Options.dll
error CS5001: Program `Options.exe' does not contain a static `Main' method suitable for an entry point
Compilation failed: 1 error(s), 0 warnings
{code}
The exception message of a MethodAccessException was changed in 7b88115737.
This caused the method-access.exe test to fail since it checked for the old format.
Unfortunately using mono_set_assemblies_path is not much of an option as it disables the MONO_PATH env var
and that's needed when working with an in-tree pedump - cuz having to `make install` all the time is BS.
Originally we used a C90-style struct initializer `{ (index), (offset), (type)
}`. Unfortunately, SpecialStaticOffset is defined with fields in a different
order on big-endian and little-endian machines. Using a designated
initializer, we don't have to care about the order.
This fixes Xamarin-10321. This change fixes the problem in SWF rather
than in libgdiplus which has the advantage that it works with both
Cairo and Pango renderers.
Without the additional NoWrap flag the text will wrap at a word boundary,
which results in the combo box showing lines with potentially a lot of
empty space at the end. With the NoWrap flag we render only one line,
displaying as many characters as possible in that one line.
... assemblies.
msbuild tries to filter out the denied assemblies, which mono refuses to
load, during a build. It uses the `deniedAssembliesList.txt` installed
to `$mono_prefix/lib/mono/xbuild` to identify them.
This was generated with:
`$ mono tools/nuget-hash-extractor/nuget-hash-extractor.exe nugets guids_for_msbuild > mcs/tools/xbuild/data/deniedAssembliesList.txt`
This file needs to be kept in sync with any changes in the assemblies
denied by the runtime.
msbuild PR that adds support for this -
https://github.com/mono/msbuild/pull/23 .
Commit message: Allow for non-fatal shell execution, and turn “install_name_tool” staging failures to warnings as we find a more permanent solution to AOT dylibs not always having enough field space for the new path (all other dylibs made in the build with the XCode toolchain typically do, as they are built with the “-headerpad_max_install_names” flag.
interface Type, not MarshalByRefObject. (Fixes#17325)
If a RealProxy instance is created (using the protected RealProxy(Type)
constructor) for an interface, mono internally sets up a MonoRemoteClass which
looks like a proxy for a MarshalByRefObject instance that happens to implement
the given interface. However mono_class_proxy_vtable just does a memcpy() to
setup the MonoVTable:type field of the transparent proxy's vtable. That type
field is hit by the JIT when System.Object.GetType() is called - and on .NET
Framework GetType for a transparent proxy of an interface returns the interface
not (as Mono used to) typeof(MarshalByRefObject).
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=17325
.. directory, which is `$mono_prefix/lib/mono/msbuild/15.0/bin/Roslyn/`
Mono installs `csc.exe` but the corresponding
`Microsoft.Build.Tasks.CodeAnalysis.dll` required for supporting msbuild C#
projects is installed by msbuild. But these two can get out of sync,
like they did and had to be worked around in
https://github.com/mono/msbuild/pull/19 .
Instead, we now install all the relevant roslyn bits (C# and VB) from the same
source. Only the msbuild specific files are copied to the Roslyn folder.
VBCSCompiler, csi and their dependencies are symlinked from `lib/mono/4.5`.
Also:
- csi.exe is included since the tool is surfaced as an msbuild task,
and that requires the *Scripting.dll assemblies.
- VBCSCompiler* - shared compiler is installed
- vbc.exe doesn't work on mono currently, so skipping that
- And `Microsoft.DiaSymReader.Native.{amd64,x86}.dll` are dropped.
- add USE_STRERROR_R_XSI to use the feature test macros conveniently later
- deal with the GNU-specific version of `strerror_r ()` separately (leave the code for the XSI-compliant version untouched)
- make `buff_len` size_t as this is ISO compliant (even though it should not really matter in this case)
- export TSan flags that are used by the compiler and the compiled program
- introduce `make_timeout` to set individual timeouts for `make` based on the config (e.g. TSan will only get 30 minutes to complete)
* Introduce racing.h
- introduce the `RacingIncrement* ()` functions
- test the `RacingIncrement* ()` functions with races of `mono_stats` in class.c
- add racing.h to Makefile.am, libmonoutils.vcxproj and msvc/libmonoutils.vcxproj.filters
* [fixup!] Rename "racing" to "unlocked"
- rename racing.h to unlocked.h
- update new file name in Makefile.am and *.vcxproj* files
- rename the functions from Racing* to Unlocked*
- update the macro logic
The checked in test files which the test suites in mono-symbolicate
and mdoc verify their output against have a few roslyn-specific
things in them and would fail when running in mcs mode.
While in theory we could check in both mcs- and roslyn-specific
test files it seems not worth the effort and we should just skip
the tests in mcs mode so we get greener builds on platforms
where we still use mcs by default.
* [mini] fix xdebug null pointer dereferencing
Some trampolines are nameless, avoid crashing when generating their
debug info.
This change is released under the MIT license.
* [mini]: image-writer - move definition of USE_BIN_WRITER to header file
USE_BIN_WRITER is being used by xdebug for conditional compilation.
This change is released under the MIT license.
* [mini]: xdebug - obtain definition of USE_BIN_WRITER from header file
This re-enables xdebug on supported platforms.
This change is released under the MIT license.
With this, profilers can distinguish between the two, and also know what the
target method of a tail call is.
The call instrumentation flags have been renamed accordingly and a new flag has
been added for instrumenting tail calls. I've also added a flag for exceptional
leave events, and method_exception_leave is only raised if this flag is given
for a method.
Also refactored the relevant JIT code a bit so it's easier to follow.
Code coverage must now be explicitly enabled. This simplifies initialization
of some coverage-related structures and also lets us enable debug info which
is needed to produce good data.
Also change the signature of mono_profiler_get_coverage_data so it returns a
value indicating whether coverage data was available.
[mono-threads-posix] Fix a buffer overflow (rather an information leak / over-read)
While testing Clang's AddressSanitizer, I found and fixed a buffer overflow.
Up for discussion: it might be worth importing `strlcpy` (http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/lib/libc/string/strlcpy.c?rev=1.11) for similar purposes as it provides additional safety and also helps with the readability?
An inlined method does not require instrumentation (if it
did, it would not have been inlined). The flags that
control instrumentation options are valid for the caller
method and are not to be consulted.
This patch replaces an assertion with a check and early
return. A method that "wants to be instrumented" does not
get inlined, but a method that "doesn't want to be instrumented"
can get inlined. However, the flags that control instrumention
options have been calculated against the caller method, hence
they should not be consulted at all. The extra check renders
the assertion unnecessary.
* [w32file] Remove io_ops indirection
* [w32file] Replace use of w32handle by a GHashTable for File, Console and Pipe
* [Socket] Avoid relying on MonoIO.DuplicateHandle
* [w32socket] Remove force closing of sockets on shutdown
* fixup! [Socket] Avoid relying on MonoIO.DuplicateHandle
* [w32socket] Replace use of w32handle by a GHashTable
* [w32handle] Remove dead function mono_w32handle_new_fd
* fixup! [w32file] Replace use of w32handle by a GHashTable for File, Console and Pipe
* [w32handle] Remove dead variable mono_w32handle_fd_reserve
* [fdhandle] Factor w32file and w32socket common fdhandle code
* fixup! [Socket] Avoid relying on MonoIO.DuplicateHandle
* [w32socket] Fix GC safe/unsafe transitions
* fixup! [w32handle] Remove dead variable mono_w32handle_fd_reserve
- Fix the Linux build instructions.
- Remove eglib dependencies, as they complicate the build of an
extenral module.
- Make instance static instead of heap-allocated.
- Make the call counter 64 bits.
- Adjustments to accommodate the new profiling API.
* [w32file] Remove io_ops indirection
* [w32file] Replace use of w32handle by a GHashTable for File, Console and Pipe
* [Socket] Avoid relying on MonoIO.DuplicateHandle
* [w32socket] Remove force closing of sockets on shutdown
* fixup! [Socket] Avoid relying on MonoIO.DuplicateHandle
* [w32socket] Replace use of w32handle by a GHashTable
* [w32handle] Remove dead function mono_w32handle_new_fd
* fixup! [w32file] Replace use of w32handle by a GHashTable for File, Console and Pipe
* [w32handle] Remove dead variable mono_w32handle_fd_reserve
* [fdhandle] Factor w32file and w32socket common fdhandle code
* fixup! [Socket] Avoid relying on MonoIO.DuplicateHandle
* [w32socket] Fix GC safe/unsafe transitions
* fixup! [w32handle] Remove dead variable mono_w32handle_fd_reserve
1. Fix off by one in size check.
Largest usable size is 0x3effff, first unusable size is 0x3f0000
(Also change order of ArgumentException arguments - param name is second.
Set it to null because of misguided CoreFX SRE test that expects a null name)
2. Check for empty string field name.
.NET Framework says:
> If you specify 0 (zero) for iSequence, this method returns a ParameterBuilder
> instead of throwing an exception. There is nothing useful that you can do
> with this ParameterBuilder.
So let's do that.
* [bcl] Grab free ports randomly in NetworkHelpers
We're frequently seeing "address already in use" errors on Jenkins.
The theory is that when we're running tests and grab the next free
port via our custom NetworkHelpers we're getting a port which will
also be returned to a simultaneously running test (e.g. another chroot)
because we're closing the TcpListener and thus releasing the port until
we start using it in actual test code. By that time the other test
might've already opened the port, causing our test to fail.
Instead we now try to use a random port in the range 10000-60000
and try if it's available. This doesn't completely fix the inherent
race but should hopefully make it way less likely.
In principle, mono_verifier_verify_cattr_content should prevent malformed custom
attribute blobs from being passed in here.
In practice:
1. The verifier is not on by default
2. System.Reflection.Emit allows an arbitrary byte[] to be passed in which
means that code like this can cause mono to read past the end of the array.
```
// "1 1-byte constructor argument and then 65280 named properties follow"
assembly.SetCustomAttribute(constructor, new byte[] { 1, 0, 1, 0x00, 0xFF });
var attributes = assembly.GetCustomAttributes(true);
```
On llvm aborts can happen during finally blocks. This test was not failing before because the method in question had llvm disabled, which has recently changed.
[metadata] Fix racy next_generic_inst_id
Like suggested by @luhenry, I would like to propose this fix which was discussed in https://bugzilla.xamarin.com/show_bug.cgi?id=58423. As `next_generic_inst_id` is `int`, `InterlockedIncrement64 ()` seems to be the right choice.
Also, I cannot add any reviewers or assignees, which is why I would kindly ask @lambdageek to review this as well :)
These symbols weren't being properly exported in the final mono executable on
Mac because no code in the runtime called these functions. As long as they're
defined in an object file that contains used functions, they'll be exported.
When this feature is enabled for a method, the enter/leave event receives an
additional argument, a so-called 'call context'. This call context contains
enough information about the stack frame of the instrumented method to allow
the enter/leave callback to inspect the 'this' reference, method arguments,
local variables, and the return value (for non-void methods).
This feature enables some interesting scenarios that were not possible with
the regular enter/leave events. For example, a profiler could instrument
well-known methods in the managed thread pool code to get an idea of how an
application is using the thread pool, or it could instrument network-related
methods to gather statistics or even log all network traffic.
This is implemented by storing a MonoProfilerCallContext on the stack, whose
MonoContext field is populated by executing an OP_FILL_PROF_CALL_CTX opcode
which stores the stack pointer, frame pointer, and all callee-saved registers
to it. For the epilogue, a pointer to the return value (for non-void methods)
is also stored in the MonoProfilerCallContext. An address to this context is
then passed to mono_profiler_raise_method_enter/leave. Based on debug info,
all arguments and locals can then be looked up in the instrumented method's
stack frame.
For the interpreter, we just store an InterpFrame pointer on the
MonoProfilerCallContext and look everything up from that. We don't need debug
info in this case.
This feature is currently not supported with LLVM (for regular LLVM mode, it
will fall back to Mono's JIT, while for LLVM-only mode, it's not available).
I also refactored the interpreter code so that enter/leave events are generated
not only when interpreter debugging is enabled. Also, the interpreter will only
call mono_profiler_get_call_instrumentation_flags () once per method now.
Finally, I made the interpreter also generate exception leave events.
GenericTypeParameterBuilder:InternalResolve (Fixes#58454)
When the parameter belongs to a method builder, we need to pass the declaring
type (appropriately resolved) to GetMethodFromHandle to avoid an
ArgumentException.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=58454
* [runtime] Integrate eglib's configure into mono's configure to simplify and speed up the configure process.
* [runtime] Delete some duplicate eglib configure code.
Cause the creation of a token for an EnumBuilder object. Test both typedef
tokens (EnumBuilder from same assembly) and typeref token (EnumBuilder in another assembly)
The new argument controls what should happen when the given token is already
present.
In some situations it's expected that we either see the same object, or we
unconditionally want to replace it (for example if we previously registered a
TypeBuilder or a MethodBuilder, after the type or method is created, we will
re-register the RuntimeType or MonoMethod in its place). In other cases (for
example when a module references a MonoMethod from a different assembly), we
may still call `mono_image_create_token()` multiple times but we expect to see
the same MonoMethod object.
* [runtime] Move the sre source files to 'common_sources', they no longer have compile time gc dependencies after the Boehm GC root changes. sre.c still depends on the gc dependent caching code in reflection-cache.h.
* [runtime] Remove compile time gc dependencies from the reflection caching code.
* [runtime] Move reflection.c/sre.c to 'common_sources', they no longer have compile time gc dependencies.
* [runtime] Remove compile-time gc dependencies from domain.c/appdomain.c.
* [runtime] Move domain.c/appdomain.c to 'common_sources' since they no longer have compile time gc dependencies.
Instead of hijacking the return address when suspending a thread in a finally block for an abort, do an explicit check in managed code when we are returning from the handler in order to see if we need to abort. Hijacking the return address is arch specific and it doesn't work if we are suspended before it is initialized in handler start.
Fixes#5798
* [mempool] Annotate functions for ThreadSanitizer
Whitelist `mono_mempool_alloc`, `mono_mempool_new_size` and `mono_mempool_destroy` according to https://bugzilla.xamarin.com/show_bug.cgi?id=57936
* [fixup!] Test the NO_SANITIZE_THREAD macro
* [fixup!] Merge comments / documentation
This follows the reference source in understanding `EndpointBehaviors` to be an alias of `Behaviors` with a more general type.
Note that although an alias might not seem necessary to implement, when using netstandard1.3 the [`System.ServiceModel.Primitives`](https://www.nuget.org/packages/System.ServiceModel.Primitives) package exposes `EndpointBehaviors` but not `Behaviors`.
These are used by XA/XI/XM and because XM in particular needs to work with
both old and new versions of system Mono, we need to make sure these functions
still exist.
Using the cardtable scan and finish_gray_stack start and end events is cumbersome to parse and require a lot of logging, especially in the case of the parallel collector.
If a worker is stuck doing work in another context, it might not be very responsive in transitioning its own state from WORK_ENQUEUED to WORKING and finally to FINISHING. When joining worker threads, we check whether we have any threads working in the corresponding context and, if there aren't any, change their state directly from the gc thread.
We can do this because work is distributed from centralized pools (worker_distribute_gray_queue and the job_queue), instead of per worker. Therefore we don't need all the workers to perform actual work in the context.
fixes this compilation error
MonoAotOffsetsDumper.cs(279,59): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
The runtime has ~always supported having multiple profilers loaded, so it
didn't make much sense that only the last --profile option given would be used.
I intend to move code coverage support to a separate profiler module, so these
events will eventually be removed from the log format. As such, I'd rather not
commit to having these event classes in the API.
This won't affect users of the library who don't enable code coverage.
So mono_profiler_init becomes e.g. mono_profiler_init_log.
This allows us to link together multiple profilers into a single module and
load them selectively. This is especially useful for XA/XI/XM.
Calling this function could cause us to miss some profiler events.
In the past, we needed to call this function so that SMR and mono-threads were
initialized. Since then, 8dec9848f6 changed
profiler initialization to happen later during startup, so this is no longer
necessary.
TypeTest.GetGenericMethodDefinitionOverInflatedMethodOnGTD accesses
List<T>.ConvertAll() via reflection but doesn't use the method
elsewhere so the linker can remove it. Added some usage to avoid that.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=56242
MONO_GC_EVENT_START is actually sent _after_ all the 'stop world' events. The
heapshot logic being in this switch case only worked by accident previously.
* Remove the mark/reclaim events as they've been broken for a long time and
aren't particularly useful.
* Reorder the enum member declarations to the order they actually arrive in.
ValueAdd was added over a decade ago and all the tests marked with this category are passing now.
We have *tons* of tests that rely on working DNS/Internet that aren't marked with
InetAccess (and they actually provide good value so we don't want to exclude them).
Since these categories don't really make sense and just causes confusion
it's better to just remove them.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=57691
For keys longer than 1024 bits, we encoded the length incorrectly as
0x80 (length & 0xff)
instead of the correct algorithm:
if (length < 0x80)
length
else if (length < 0x4000)
0x80|(length>>8) (length & 0xff)
else
0xc0|(length>>24) (length>>16)&0xff (length>>8)&0xff length&0xff
which is provided by mono_metadata_encode_value.
See ECMA-335 II.24.2.4 #US and #Blob heaps
N.B.: we now always allocate the memory for the key as (keylen + 4) which
over-allocates by a couple of bytes in the cases where the key is shorter.
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=57691
We build a library that has an InternalsVisibleTo attribute that references an
executable that is signed with a long (>128bytes) public key. Previously we
were using an incorrect method of encoding the key length.
This commit does a few different things.
First, metadata event options have been removed. We now always emit these
events. This is done because they contain important data that must be present
in order for dynamic event mask changes at runtime to result in useful data.
Also, almost all uses of the profiler require this data to be present, so
letting it be turned arguably just adds confusion for users.
Second, the PROFLOG_*_FEATURE flags have been removed. These made the code a
bit confusing because it was unclear whether code in log.c should be checking
the PROFLOG_*_FEATURE flag or the PROFLOG_*_EVENTS flag for a particular kind
of event. For heapshot in particular, the heapshot mode is now a separate enum
configuration variable. For enter/leave and coverage, switching those on and
off in the log profiler at runtime is not something we want to support at this
time.
As a result of the above change, some options are now processed manually rather
than being part of the event_list array.
Third, the way we turn off GC root events when needed is now by setting the
callback to NULL. This is more efficient as it signals to the runtime that it
doesn't have to gather root information. This will especially matter later on
when the profiler root info revamp lands, as it collects a lot more data than
we do today. Also, GC roots are no longer gathered unless we're doing a
heapshot.
Fourth, the profiler now always starts the sampling thread in idle mode. This
is so that we can reconfigure and enable/disable it at runtime as needed.
Finally, the alloc alias option now includes GC move events, and GC resize
events are only emitted if the gc option is given.
We've seen this test failure a few times:
```
MESSAGE:
#2
Expected: greater than or equal to 00:00:01
But was: 00:00:00.9544900
+++++++++++++++++++
STACK TRACE:
at MonoTests.Microsoft.Build.Execution.BuildSubmissionTest.EndBuildWaitsForSubmissionCompletion () [0x000d8] in /mnt/jenkins/workspace/test-mono-mainline-linux/label/ubuntu-1404-amd64/mcs/class/Microsoft.Build/Test/Microsoft.Build.Execution/BuildSubmissionTest.cs:110
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in /mnt/jenkins/workspace/test-mono-mainline-linux/label/ubuntu-1404-amd64/mcs/class/corlib/System.Reflection/MonoMethod.cs:305
```
Rewriting the test to use Stopwatch instead of DateTime
for measuring elapsed time should make it more reliable.
Previously, the profiler's state was spread all over the place. Some stuff was
in the MonoProfiler structure, some stuff was in global variables littered
throughout log.c. Now everything is stored in MonoProfiler and ProfilerConfig.
The call to GetDiskFreeSpaceEx passes uninitialized pointers to GetDiskFreeSpaceEx
instead of pointers to stack variables. This will cause random memory corruption and random
crashes on Windows builds.
This is a regression caused by the refactoring work done in this PR:
https://github.com/mono/mono/pull/4255
Location of ml.exe and ml64.exe is different in VS2017 compared to VS2015.
By removing the partial path from the command, the VS environment will locate
the tool depending on selected build configuration and VS version.
This should work for both VS2015 and VS2017.
LanmanWorkstation and SamSs services don't depend on the Browser
service anymore, at least in the Windows Server build that our
Azure VM agents on Jenkins are using now. This started failing a
few days ago so I assume a new build was rolled out.
It shouldn't throw in that case.
Helps cover https://bugzilla.xamarin.com/show_bug.cgi?id=57629
(note that we don't explicitly test on a readonly FS as that is hard
to do in a unit test, but running this test on Android should suffice).
Instead of using fragile lockless code in the sigchld signal handler, wake up the finalizer thread and make it call back
into the process code to signal finished processes.
* Profiler callbacks can now be changed and disabled at any point.
* API users no longer have to set event flags. The API instead uses a counter
internally for each type of callback.
* Filter functions for enter/leave instrumentation can be installed, and they
can choose whether to instrument the prologue, epilogue, or both.
* Managed allocators can now be instrumented for allocation profiling.
* A profiler must now declare that it wishes to use allocation profiling and/or
sampling in its init function.
* Sampling parameters can now be changed at any point, and the sampling thread
can be put into an idle mode when no sampling is needed.
* Only one profiler can have control over the sampling parameters. Whichever
profiler enables sampling first gets control.
* Adding new events is now very easy: One line in profiler-events.h and one
line wherever the event should be raised.
* Lifted the restriction that enter/leave instrumentation would cause an abort
in full AOT mode.
* Support for call chain sampling has been removed.
* Support for the old, platform-specific code coverage mode has been removed.
* The new profiler module entry point is mono_profiler_init. If a module has
a mono_profiler_startup symbol (the old entry point), a warning will be
printed and the module won't be loaded.
* Updated the profiler test suite to work with instrumented managed allocators.
After the refactoring in 9aaa0083d0
CppCheck complained about using 'result' uninitialized (looks like
it can't deduce that g_error will abort the process anyway).
Console.Error.WriteLine ("Got a bad hardware address length for an AF_PACKET {0} {1}",...
This Console.WriteLine interferes with Apache Storm that reads from the console I/O.
See bug: https://bugzilla.xamarin.com/show_bug.cgi?id=57887
[sre] Deal with ResolveEventHandler returning an AssemblyBuilder (Fixes#57850, #57851)
Fix a couple of bugs in the situation where a `ResolveEventHandler` happens to return an `AssemblyBuilder`.
* [#57850](https://bugzilla.xamarin.com/show_bug.cgi?id=57850) - if the `ResolveEventHandler` returns a reflection only assembly, throw a `FileNotFoundException`
* [#57851](https://bugzilla.xamarin.com/show_bug.cgi?id=57851) - don't look for a `ReferenceAssemblyAttribute` on assemblies returned by a `ResolveEventHandler` if they happen to be an `AssemblyBuilder`. (the native code path to get there is to try and instantiate a custom attribute in some other assembly, hence the fairly convoluted test in `assemblyresolve_event5` and its helper files)
In particular this makes sure that AssemblyBuilderAccess.ReflectionOnly aren't
allowed to run. And AssemblyBuilderAccess.CollectAndRun aren't allowed to save.
mono_w32handle_new_fd: We must hold scan_mutex while initializing an unallocated handle otherwise
mono_w32handle_foreach might think it's a valid handle.
mono_w32handle_timedwait_signal_handle: We must increment the refcount before installing the interrupt handle
as the other end can be called right after we finish installing and would trigger a failure.
* [w32handle] Fix handle dumped ref
* [w32handle] Replace exposing mono_w32handle_{ref,unref} by mono_w32handle_{duplicate,close}, it is closer to what the win32 API exposes.
* [w32handle] Remove unrefing of handles on shutdown
If one of the handle is a file handle for example, then w32file has already be cleaned up, so we cannot guarantee that the handle we are going to close is not going to call into w32file code.
We're checking out a specific commit for both now so the git branch
is no longer required.
Also fixes warnings that a 2017-06 branch doesn't exist in mono-extensions.
While this is not an issue yet, sgen_thread_pool_wait_for_all_jobs is logically expected to be called by the main thread and resume execution after all jobs have been executed. Concurrent M&S can enqueue additional jobs as part of its finishing phase, which means that we could detect early that no more jobs are to be processed. Make sure this is not the case.
* Fix compiler warnings (w32)
- add explicit (long long (unsigned)) type casts
- change %ld to %lld once, to match the general style of these logging messages
* Fix compiler warnings (threadpool)
- add explicit (void *) type casts
* Fix compiler warnings (boehm)
- add an explicit (long) type cast; the values are defined as gint64, an upgrade to at least "%ld" seems like a good idea
- about dropping const: const does not seem to be necessary as g_getenv() returns pointers to freshly allocated buffers whenever called. const might have been used to protect the return value of g_getenv() on unix systems with earlier versions of Mono (as a comment in gmisc-unix.c suggests). keeping const here causes a compiler warning, as the const qualifier gets dropped when *env is being used with g_free(). that led to the decision to drop the qualifier altogether.
* Fix compiler warnings (sgen)
- specify the arguments (void) to avoid -Wstrict-prototypes warnings
* Fix compiler warnings (misc - metadata)
- specify the arguments (void) to avoid -Wstrict-prototypes warnings
* Fix compiler warnings (misc)
- specify the arguments (void) to avoid -Wstrict-prototypes warnings
- add an explicit (void *) type cast; changing the return type to char* might be more usable and could be discussed
- ret is not being used and can be removed; fixes a -Wunused-but-set-variable warning
* Fix compiler warnings (mini)
- specify the arguments (void) to avoid -Wstrict-prototypes warnings
* [fixup!] Correct indentation
* [fixup!] Correct (void *)
- use GUINT_TO_POINTER and MONO_NATIVE_THREAD_ID_TO_UINT instead of (void *) to cast mono_native_thread_id_get () to %p
* [fixup!] Correct indentation of boehm-gc.c and add FIXME
* include <inttypes.h> and test the G_GINT64_FORMAT macro
* [fixup!] Use G_G*_FORMAT and PRIx32 macros instead of type casts wherever possible
Reuse the existing icall infrastructure to give the same handle back.
This PR implements all OpenExisting methods (with the access rights parameter discarded) and the SafeHandle property.
In the runtime, we don't check the capacity parameter if we try to open a mmap file, and we fallthrough the handle refcount case.
- Had to borrow a gchandles implementation from mono/metadata/boehm-gc.c
- Added coop handles support for NULL GC
- Fixed typos in configure.ac
- To use: `./configure --with-libgc=none --without-sgen --enable-boehm`
You get a mono-boehm which actually is not collecting anything.
We need to run jobs on the thread pool threads for parallel minor, parallel major, concurrent mark and concurrent sweep, some of which can run simultaneously. Instead of making separate threads reserved for each type of work, we create a work context abstraction (this contains a set of pending jobs to run and the sgen-worker callbacks). When a thread pool thread looks for work, it searches for work (jobs and idle work) through all contexts and finishes work from each one of them, from the highest to the lowest priority.
This is implemented by having different thread pool contexts (which contain the job list, work callbacks that indicate whether it should work and its ineherent priority), overall unrelated to the GC. The sgen worker infrastructure also creates separate worker contexts (which contain the object ops to be used and information about each worker, like the state and the private gray queue). We use at most two worker contexts (for minor and for major) and each worker context makes use of a sgen thread pool context.
Concurrent mark doesn't normally scan objects in the nursery since they can be moved. At the end of the concurrent mark, we were locking over the entire gc pause in order to make sure that the we can scan the latest pinned object list (aka none of those objects can be moved). Lock only over the pinning phase of the collection, since it is enough.
This reduces regressions for switching from MS_BLOCK_SIZE compile time constant
to ms_block_size variable by 85% on the tests where this was showing up. In the
future we should implement a block allocator, which would, amongst other benefits,
enable us to remove the block-size/page-size dependency.
The block size must be a multiple of the system page size. Page size simply
cannot be determined reliably at compile time, so we must obtain the page size
through a system call on startup and use it as the block size. We still enforce
a minimum block size of 16kb on systems where the page size is smaller than
that.
The old code hardcoded page sizes for certain architectures with large pages.
THe problem is that those architectures don't necessarily have to have large
pages and on systems where this wasn't the case, we'd end up with a block size
much larger than needed.
Rebase of @alexrp's work.
Linux has this particular behavior of returning ENOFS when unlinking from an read only FS.
Even if the file doesn't exists! Darwin does the sane thing and return ENOENT in this case.
To workaround this, if unlink returns EROFS, we stat the file and deal with that.
This fixes an issue we see on the BCL test suite when run in the context
of Xamarin Android:
```
I/mono-stdout( 2534): Certificate1 [FAIL] : TearDown : System.UnauthorizedAccessException : Access to the path "temp.b64" is denied.
```
It seems like those files aren't generated anymore. Not sure why this
starts to be a problem now.
This avoids situations where we could end up filling the signal queue
completely, leading to the undocumented EAGAIN return value from pthread_kill,
which breaks ~everything in the STW/GC code because it thinks an error return
value from pthread_kill means the thread has exited.
The actual reason why this happened is that when a thread is suspended, we mask
all signals except the restart signal for that thread. This means that a
program with a large number of threads or where GC collections could take
longer than usual would end up with tens of thousands of sampling signals
queued up, eventually reaching the limit of the user-level signal queue (see
`ulimit -i` and `RLIMIT_SIGPENDING`).
We only do this on systems where we use real time signals. Non-RT signals do
not have this problem as the kernel will throttle them.
These will be used in the log profiler.
Also, make mono_thread_info_register_small_id () only allocate a new small ID
if one isn't already allocated for the current thread. This is necessary so
that we can allocate a small ID for a thread and not have it be overwritten
if/when that thread is later attached probably (which also results in this
function being called).
This hardens the profiler against cases where an unattached thread causes some
event callback to be invoked. This is particularly relevant when embedding.
If a program is idle, we likely won't get enough samples to prompt the dumper
thread to send its log buffer to the writer thread. This can make it seem like
the profiler isn't working when it actually is. So, just send the dumper
thread's log buffer every second to make sure data is delivered in a timely
fashion.
* [threads] Make mono_thread_attach_full static
* [threads] Remove prefix on MonoThreadInfoCallbacks callbacks
* [threads] Rename mono_threads*_init functions to mono_thread_info*_init
* [threads] Remove dead method mono_runtime_is_critical_method
* [threads] Move MonoThreadInfoCallbacks to metadata/threads
* [threads] Store MonoInternalThread in MonoThreadInfo for use when detaching
When the native thread would exit, the TLS keys are destroyed. There is a TLS destructor for MonoThreadInfo, but not for MonoInternalThread. If MonoInternalThread is destroyed before MonoThreadInfo, then MonoThreadInfoCallbacks.thread_detach wouldn't successfully detach the current MonoInternalThread as mono_thread_internal_current would return NULL. This would lead to MonoInternalThread still laying around, while their corresponding MonoThreadInfo has already been destroyed. This fixes this problem, since we now rely on MonoThreadInfo to store the MonoInternalThread for detach.
- Create a unique temporary directory for each test in TypeBuilderTest and delete
it on TearDown.
- Change tests to use tempDir instead of Path.GetTempPath ()
- Change IsSerializable () test to how it was 11 years ago and have it write to a
file with a simple name (but now in a directory where noone else is writing)
- Change FieldsWithSameName (), FieldsWithSameNameAndType () and
MethodsWithSameNameAndSig () to use the default temp assembly (now in a
unique tempDir) instead of using the CreateTempAssembly ()
- Remove CreateTempAssembly function. It is dead code.
* [threads] Use MonoThreadInfo.{stack_start_limit,stack_end} in more places
* [threads] Remove dead code
* [threads] Rename MonoThreadInfoCallbacks.thread_{register,detach,unregister} to MonoThreadInfoCallbacks.thread_{attach,detach,detach_with_lock} respectively
This error can occur on mobile devices during network operations
as evidenced in https://bugzilla.xamarin.com/show_bug.cgi?id=56653
and having an actual description of the error printed in this case
makes it easier for the user to discover what's going on.
mono_thread_info_suspend_lock () can be called from boehm-gc.c
on_gc_notification before the new thread's start_wrapper calls
mono_thread_info_attach but after pthread_create calls the start wrapper.
As a result, the asserts in mono_thread_info_suspend_lock_with_info can catch
the new thread in an inconsistent state.
They now are produced every time a GC spills heap events such as roots, moves and objects.
Additionally, I changed GC syncpoints to happen in case any GC events are active.
It's a safer choice with little penalty. Figuring out the actual combinations that would require them is non-trivial.
Suppose we have two versions of an assembly: AsmA 1.0.0.0 and AsmA 2.0.0.0 that
we want to load into the same domain at the same time (for example we want to
load AsmB and AsmC that statically reference the two versions, respectively, or
maybe we used reflection). Suppose version 1 got loaded first (and we found it
on our MONO_PATH in "somepathdir/AsmA.dll"). Now we want to load version 2.
The problem is that if version 1 is on MONO_PATH first, we'll find a filename
that matches ("somepathdir/AsmA.dll") and try to open that image. Then we'll
end up here in mono_assembly_open_predicate() after the mono_image_open_a_lot()
call hits the image cache. So we get back an image and image->assembly is
version 1.
The old behavior would just return any non-NULL image->assembly. The new
behavior is to check the predicate and reject opening the propose file if the
predicate doesn't match. (If we're not using the strict loader, or if there's
no predicate set, return the existing image->assembly as before).
They lived in https://github.com/mono/release before, moving them
into the main repo allows us to version them more easily.
Note: I intend to do more cleanup on those scripts in the future,
this is just the first step.
Group gc params configurations into general gc modes. The default mode (SGEN_MODE_NONE) is what we've been using so far, meaning old default features. The other modes can include experimental features.
We the profiler now emiting a lot less events by default, all the existing polling no longer makes sense as they won't matter in the common path.
Instead we make sure the finalization end callback is always installed and poll from it.
This introduces the risk of a heapdump never happening or experiencing long delays because there are either too many finalizers or one of them hung.
It's an acceptable risk.
* Fix System.Numerics xunit tests and add them to CI
Xunit.Extensions.NetCore.dll is available as a net46 version now
so we can just use it instead of building it from our buildtools fork.
This also allows us to remove the fork from our submodules.
We were missing running the System.Numerics xunit tests in CI,
this adds them so we catch breaks like these earlier.
* Skip tests on Windows, they seem to fail there
Regression test for https://bugzilla.xamarin.com/show_bug.cgi?id=57222
Although methods aren't affected by this bug, I added a regression test for
this case anyway in case the implementation changes.
Currently MethodBuilder.RuntimeResolve() goes through a different codepath - it
calls RuntimeType.GetMethod (MethodInfo) which calls into an icall which looks
for a method with a matching token rather than a matching name.
We can't pass RuntimeMethodHandle across AppDomains since that can lead to memory corruption.
The way this happens is that when Domain (A) passes a method handle (M) to Domain (B), (B) will get the reflection object for
which will add that MonoMethod to the per-domain reflection hashtable. This won't cause the assembly of (M) to be registered with (B).
When (A) is unloaded, it might be the only domain referencing the assembly of (M), cause it to unload resulting in (B) having a dangling
pointer to (M) on its reflection hashtable.
The fix is to serialize enough lookup data across the wire so we can do type/method lookup using reflection on the target domain.
It might be slower, but this only happens on some remoting slowpaths anyways.
Finally, we can't simply register the assembly of (M) into domain (B) as that list (MonoDomain::domain_assemblies) is used for type loading,
thus breaking the target domain in some scenarios.
RuntimeType:GetField (FieldInfo) looks up the field by name and attributes,
which doesn't work for SRE because it is legal to create multiple fields with
the same name and type and attributes. So lookup using the
RuntimeFieldHandle (aka MonoClassField*) instead.
* [System]: Correctly implement close and shutdown in SslStream.
* Cleanup.
* Cosmetic.
* More ReferenceSources/SR2.cs into common.sources to make it build.
When creating a bundle on Windows to run on Android, macOS/iOS or Linux we need
to use the target system's path separator when storing satellite assemblies in
the bundle instead of the host system's one. Failing to do so will embed (on
Windows) the satellite assemblies with paths like
fr_FR\myassembly.resources.dll
while at runtime Mono will try to look up the assembly by
fr_FR/myassembly.resources.dll
and fail to find it, obviously. The `--style` parameter is now consulted to see
what path separator character should be used.
Fixes https://bugzilla.xamarin.com/show_bug.cgi?id=55603
MonoInternalThreadHandle is not really needed - all MonoInternalThread
instances are supposed to be pinned. But for uniformity, the icall marshaller
makes handles anyway. This function lets us get back to a raw ptr.
- Use coop handles for create_object_from_sockaddr
Eventually want to rewrite its callers to use
create_object_handle_from_sockaddr directly.
- Use coop handles for
- LocalEndPoint_internal
- RemoteEndPoint_internal
- inside create_sockaddr_from_object
Eventually callers should be updated to use create_sockaddr_form_handle
directly.
- Use coop handles for
- ReceiveFrom_internal
- Bind_internal
- Connect_internal
- SendTo_internal
- Remove dead code (create_object_from_sockaddr, create_sockaddr_from_object)
- Use coop handles for
- Receive_internal WSABUF[]
- Receive_internal byte[]
- Send_internal
- Send_array_internal
- SetSocketOption_internal
- GetSocketOption_arr_internal
- GetSocketOption_obj_internal
- IOControl_internal
- SendFile_internal
- Remove more dead code
- Use coop handles for
- Socket_internal
- Select_internal
- Trivial coop handles conversion for several icalls in System.Net.Sockets.Socket
None of these functions use managed objects, so just add a MonoError* argument.
Previously we only had "out" reference args working - they get a handle that's
initialized to NULL on entry and then writes back to the out arg on icall
return.
For "ref" reference args, do the same thing but initialize to the initial
argument value.
* [Mono.Options] Fix test and add suite to CI
We missed running Mono.Options tests on CI so we didn't catch
this error which was introduced with: https://github.com/mono/mono/pull/4719
```
CSC [net_4_x-darwin] net_4_x_Mono.Options_test.dll
Test/Mono.Options/CommandSetTest.cs(231,16): error CS7036: There is no argument given that corresponds to the required formal parameter 'error' of 'CommandSet.CommandSet(string, TextWriter, TextWriter, Converter<string, string>)'
```
* [Mono.Options] Stop hardcoding \n to fix tests on Windows
With the new bockbuild in place we can finally remove the
implicit dependency on a point-in-time state of mono-extensions
and instead explicitly pin the desired revision.
This removes all [no]foo weirdness and flag dancing in favor a simpler model.
Users can enable/disable both events and profiling modes. We expose pretty much all individual events.
A profiling feature is a group of flags that enable a specific profiling scenario.
Right now we have code coverage, perf sampling, gc alloc and heap dump as features.
All events can be prefixed with 'no' and cause them to be disabled. We'll later introduce some sanity
checking around misconfiguration.
Finally, this changes the default set of enabled events to threads and gc. Everything else must be added on top.
Experience has shown that the vast majority of those events are just noise when profiling and the current configuration
design made it quite awkward to introduce quieter modes.
We would previously mix 2 SocketAsyncResult, and in case we would succeed asynchronously, we would return one that would not be updated afterwards.
The solution consists in using only 1 SocketAsyncResult that we ensure to update accordingly.
After looking at https://github.com/mono/mono/pull/4949 I did a
quick pass through the other config sections and found two more
cases where we missed adding to the properties list.
Otherwise, while we are clearing the domain, another domain might be created that has the same id as the current one. This would lead to crashes due to releasing of data from the newly created domain (ex gchandles).
* [S.R.I.RuntimeInformation] Fix FrameworkDescription on Android
It turns out using `DllImport ["__Internal"]` doesn't work on
XA (and other cases where Mono is embedded) because it searches
for the method in the host which embeds Mono and doesn't find it,
resulting in an EntryPointNotFoundException.
We need to switch to an icall instead. However there's already
an existing icall+BCL wrapper: Mono.Runtime.GetDisplayName().
Added IVT from corlib to S.R.I.RuntimeInformation so we can call it.
* Update API snapshot
we got a couple of bug reports, all with the same failure:
https://bugzilla.xamarin.com/show_bug.cgi?id=44907https://bugzilla.xamarin.com/show_bug.cgi?id=46482https://bugzilla.xamarin.com/show_bug.cgi?id=51791
The bugs are private, therefore here what I wrote:
```
Thank you Matthias, this was very helpful.
>>> 09-30 12:24:50.347: A/DEBUG(6211): pid: 6191, tid: 6209, name: Thread-4 >>> com.distech.x50.ui.droid <<<
>>> 09-30 12:24:50.347: A/DEBUG(6211): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x8
>>> 09-30 12:24:50.347: A/DEBUG(6211): r0 d6b58728 r1 00004001 r2 00000000 r3 d6b58738
>>> 09-30 12:24:50.347: A/DEBUG(6211): r4 00000008 r5 ea97427c r6 00001f3c r7 00000015
>>> 09-30 12:24:50.347: A/DEBUG(6211): r8 00001f38 r9 00000015 sl d6b58728 fp d67fed90
>>> 09-30 12:24:50.347: A/DEBUG(6211): ip ea9742c0 sp d67fed60 lr ea7a4504 pc ea716a58 cpsr 800e0010
The crash happens on this assignment:
https://github.com/mono/mono/blob/de1865dad5c0350f391fedcaa08f02f610530d3f/mono/mini/mini-generic-sharing.c#L418
Here the according disassembly:
https://gist.github.com/lewurm/b1094749027c9e5ea19fdc4fac7905a7
The crash happens in the last loop iteration (`r9=i`, `r7=slot`). Looking
at the machine code it just _cannot_ happen, which is confirmed by the C
code as well: `*oti` successfully happens in the if check, but after
returning from `alloc_oti()`, `oti` doesn't contain a valid address anymore.
I suspect some weird hardware issue that fails to restore all registers
properly from the stack.
```
[...]
```
Thanks again Matthias. Unfortunately, I'm out of ideas, and I can't
blame anything but the hardware. The situation we see is too weird. We
segfault at offset `0xdda60: str sl, [r4]`, but really we should
already segfault at offset `0xdda2c: ldrge sl, [r4, #8]!"`. So I
suspect two things why this could happen:
(1) The instruction at `dda2c` fails to do the post-increment correctly
for *whatever* reason.
(2) Something along the execution path corrupts the stackslot, where
`r4` is saved, in such a way that it *exactly* masks it with `0xf`.
Everything else on the stack looks fine, so this is sort of very
unlikely to be honest.
This only happens on a very specific device: The Nexus 9 is the only
device that was ever shipped with the Tegra K1 T132. I suspect an issue
in the binary translation layer of `armv7` instruction set to the internal
micro-ops of the CPU. I tried to stress test the instruction in
question (see https://github.com/lewurm/ldrinsntest), however I was not
able to trigger a crash. So either, I'm missing some context in order
to trigger the bug or I'm on a completely wrong track.
That said, even if we could proof that it is indeed a hardware issue,
the workaround is also non-trivial (it would then either need a fix in
gcc or require a microcode update by the chip vendor).
```
And then we saw:
https://github.com/golang/go/issues/19809#issuecomment-290804472
Another hint that this device is buggy.
This change massively improves reflection query scalability.
Given this benchmark and my 4 cores laptop:
```
const int T_C = 4;
var list = new List<Thread> ();
bool done = false;
int count = 0;
for (int i = 0; i < T_C; ++i) {
var t = new Thread(() => {
while (!done) {
typeof (Driver)
.GetMethods (
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Static);
Interlocked.Increment (ref count);
}
});
t.Start ();
list.Add (t);
}
Thread.Sleep (5000);
done = true;
foreach (var t in list)
t.Join ();
Console.WriteLine ("Got {0} lists done", count);
```
This change makes us go from 166.725 queries/s to 5.140.821 queries/s. Or 30x faster.
* [interpreter] Add beginnings of debugger support.
Handle debugger support similarly to the JIT:
- Add a MINT_SDB_SEQ_POINT instruction to the debugger IR. Replace it with a MINT_BREAKPOINT instruction when a breakpoint is placed.
- Store the sequence point information in the existing sequence point data structures.
* [interp] Add support for debugger stacktraces.
* [interp] Add support for debugger frame info.
* [interp] Connect seq points inside the same basic block so simple single stepping works.
* [interp] Link sequence points in different basic blocks the same way the JIT does it.
* [interp] Allocate some bitsets from a mempool.
* [interp] Rewrite the patching in the transform pass to make it a bit easier to understand.
* [interp] Add interruption support for sdb.
* [interp] Add support for mkrefany,refanytype and refanyval.
* [interp] Fix debugger failures.
* Add support for setting byref variables.
* Fix thread interruption when the top frame is an interpreter frame.
* Allow stack walks when a thread is suspended while transforming a method.
* Implement method entry/exit events.
* Fix ldstr+dynamic methods.
* [interp] Implement support for Debugger.Break.
* [interp] Change the offsets in MonoJitInfo/seq points into byte based from short based to reduce the amount of special casing needed in other parts of the code.
* [interp] Factor out the push/pop lmf code into a pair of helper functions.
* [mixed] Fix mixed mode EH.
* [interp] Implement support for MONO_VERBOSE_METHOD. Improve sequence point placement.
* [interp] Implement support for SetIP ().
Pass the target thread as an additional argument to mono_interp_set_resume_state (). Check the resume state after single
stepping/breakpoints in the interpreter.
* [interp] Disable the usage of the STLOC_NP opcodes when running under the debugger, it doesn't work if the ip is changed when the execution is stopped.
* [interp] Fix async stack walks in the debugger when the thread is in native code called from interpreter code.
* [interp] Fix the disable interpreter build.
* [interp] Fix the calculation of native offsets in the line number info.
* [interp] Fix the build.
* [interp] Make CMD_STACK_FRAME_GET_THIS behave the same when called on managed-to-native frames, with the interpreter, frame->has_ctx is set.
* [interp] Fix typos, remove some dead code, use g_print instead of printf in a few places, move some interpreter stubs to interp-stubs.c.
- Make a new mono_w32event_create_full on unix
- Convert the MonoString to utf8 (unix) or utf16 (win32) in the icall, then
call an implementation func.
- transition to GC safe mode around the win32 api call on Windows
When an AssemblyLoad event fires in a domain, a System.Reflection.Assembly
object is created in that domain for the assembly being loaded. The bug left
this object alive after the domain was unloaded, which lead to a GC crash.
After fixing my windows setup, I managed to properly test MS's behavior, which is a lot saner and it's the following:
Opening fails with ERROR_CANT_RESOLVE_FILENAME (1921).
Testing and Deleting works.
Fixing File.Delete required removing the lstat we do before deleting, which no longer serves any purpose.
Fixing File.Exists requires handling ELOOP when stat fails and we retry with lstat.
* Create mono_delegate_handle_to_ftnptr for the implementation
* Use coop handles for
System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegateInternal
* Move most of the logic to mono_ftnptr_to_delegate_handle
* Use handles for
System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointerInternal
Most of the removed files weren't touched in the last decade
and are unused so it's better to remove them to avoid confusion
about what they do.
I also went over and removed the most outdated info from readme
files, we probably want to do a more thorough overhaul in the future.
mscorlib.dll etc will be platform specific in the future. This also
means that we need to adapt monolite since it'll become platform
specific once we start the divergence.
monolite is essentially a repackaging of the "build" profile which
means we need to turn that profile into multi-platform profile
like net_4_x. We'll still have a symlink from build -> build-darwin
and the monolite which is downloaded or packaged in the tarball
is expanded into mcs/lib/monolite-<platform> depending on the platform
you're building on.
I had to move the get-monolite-latest target from the top-level
Makefile.am into mcs/class/Makefile so it has access to HOST_PLATFORM,
but it arguably should've been there anyway before.
Bring in the change that makes building the "tool" subdirectory
in BTLS off by default - we don't need it in Mono and it fails
to build on some platforms with older C++ compiler.
Remove 10000 size check in mini_emit_memory_copy_bytes, this is no longer needed now that the memcpy expansion logic in mini_emit_memcpy_internal was fixes.
Use a define for 10000.
Remove useless debug spew.
Problems with the current code:
It's wrong on 64bits if align == 4
It's wrong on 64bits if offset is not 0 or 4.
It generates bad code if align > 1 && align < SIZEOF_VOIDP
This PR implements unaligned based on the following set of assumptions that are true for the current set of platforms we support:
- A load/store of size X works with data aligned on X. IE, a short store can handle addresses aligned to 2
- Unaligned access is either disallowed or plain slower.
- Both source and dest abide to the supplied alignment.
The way we emit unaligned access is by emitting the widest possible access based on alignment and offset.
TBH: use unaligned access on targets like x86 that support it and are profitable.
It's both racy and not necessary.
Beyond that, it will produce the wrong exception if opening the file fails for a different reason that it's missing.
This is an issue in case of bad permissions or symlink loops.
When using "fat" session (~2MB) and multiple (~20) simultaneous calls
the retrieval sometimes fails and lock the session.
The original code blocks on the calling thread (AutoResetEvent.WaitOne())
and uses another thread with the timer to do the polling.
If the polling succeeds, the TimerCallback AutoResetEvent.Set(),
with no guarantes that it will wake up the thread.
(see Remarks in http://msdn.microsoft.com/en-us/system.threading.eventwaithandle.set%28v=vs.110%29)
In this patch we simply replace all this code with an equivalent
loop + sleep, which give us the same behaviour
(we still block the calling thread with the sleep, but we didn't use another one)
Signed-off-by: Frederic Mestayer <[email protected]>
Signed-off-by: Etienne CHAMPETIER <[email protected]>
2014-12-22 09:20:01 +01:00
4309 changed files with 172327 additions and 173197 deletions
If you are new to contributing to Mono, please try to do your best at conforming to our coding guidelines http://www.mono-project.com/community/contributing/coding-guidelines/ but don't worry if you get something wrong. One of the project members will help you to get things landed.
Does your pull request fix any of the existing issues? Please use the following format: Fixes #issue-number
Loaded 100 of 4309 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.