Skip to content

.NET 6 C++/CLI runtime generates InvalidProgramException when large stack-allocated variables are used #60852

@lstrudwick

Description

@lstrudwick

Description

I am porting some code to .NET 6 and encountered some issues running C++/CLI code. After narrowing it down, it seems that using large stack-allocated arrays (larger than 65536 bytes) will generate a System.InvalidProgramException when the method with the offending variable is called for the first time.

Reproduction Steps

A minimal repro is to put the following code into a CLR Class Library and call it from a C# program:

namespace ClassLibrary1
{
	public ref class Class1
        {
        public:
	        static System::String^ BrokenFunction()
	        {
		        unsigned char block[16 * 1024 * 4 + 1] = { 0 };
		        return gcnew String("unused");
	        }
	        static System::String^ WorkingFunction()
	        {
		        unsigned char block[16 * 1024 * 4 + 0] = { 0 };
		        return gcnew String("unused");
	        }
	        static System::String^ WorkingFunction2()
	        {
		        unsigned char block[16 * 1024 * 4 + 0] = { 0 };
		        unsigned char block2[16 * 1024 * 4 + 0] = { 0 };
		        return gcnew String("unused");
	        }
	        static System::String^ AlsoWorkingFunction()
	        {
		        unsigned char* block = (unsigned char*)alloca(16 * 1024 * 4 + 1);
		        memset(block, 0, 16 * 1024 * 4 + 1);
		        return gcnew String("unused");
	        }
        };
}

As can be seen, it looks like there's a fundamental limit in the compiler-generated types which back the arrays. Note that prior to .NET 6, this appeared to work without issue.

Expected behavior

The program should not crash as long as we don't exceed the thread stack size.

Actual behavior

The program throws an exception as soon as a method with a large local array is called.

Regression?

Yes, this appears to be a .NET 6 specific issue.

Known Workarounds

In my case, as this is a scratch buffer, I could use alloca instead.

Configuration

.NET 6 RC2
Windows 10, x64
VS2022

Haven't tried any other configurations.

Other information

No response

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsideration

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions