summaryrefslogtreecommitdiff
path: root/Runtime/Mono/MonoUtility.cpp
blob: 1e0a4e0f8ab2a9b1319a39334e3c102122260ce0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
#include "UnityPrefix.h"
#include "MonoIncludes.h"
#include "Runtime/Utilities/File.h"
#include "Runtime/BaseClasses/RefCounted.h"
#include "Runtime/BaseClasses/GameObject.h"
#include "Runtime/Utilities/Utility.h"
#include "Runtime/Utilities/PathNameUtility.h"
#include "Runtime/Scripting/ScriptingUtility.h"
#include "Runtime/Scripting/Scripting.h"

#if UNITY_EDITOR
static UNITY_TLS_VALUE(void*) gStackLimit;

static void* GetStackLimit()
{
#if UNITY_WIN
    MEMORY_BASIC_INFORMATION mbi;
    VirtualQuery(&mbi, &mbi, sizeof(mbi));

    return mbi.AllocationBase;
#elif UNITY_OSX
	pthread_t self = pthread_self();
	void* addr = pthread_get_stackaddr_np(self);
	size_t size = pthread_get_stacksize_np(self);
	return (void*)((char*)addr - (char*)size);
#elif UNITY_LINUX
	pthread_attr_t attr;
	size_t stacksize = 0;
	void *stackaddr = NULL;
	pthread_t self = pthread_self ();
	int ret = pthread_getattr_np (self, &attr);

	if (ret != 0)
	{
		printf_console ("pthread_getattr_np ret=%d\n", ret);
		return 0;
	}

	ret = pthread_attr_getstack (&attr, &stackaddr, &stacksize);

	if (ret != 0)
	{
		printf_console ("pthread_attr_getstack ret=%d\n", ret);
		return 0;
	}

	return (void*)((char*)stackaddr - (char*)stacksize);
#else
#error Platform does not have stack checking implemented.
#endif
}

#define REQUIRED_SCRIPTING_STACK_SIZE (16*1024)


// Functions to check whether we have REQUIRED_SCRIPTING_STACK_SIZE (64K) of stack space available
// before calling into native code. This ensures a StackOverflowException will *not* occur in mono runtime
// or engine code.
bool IsStackLargeEnough ()
{
	// Note, we assume stack grows DOWN
	void* stackLimit = gStackLimit;
	if (stackLimit == NULL)
		gStackLimit = stackLimit = GetStackLimit();

	if (((char*)&stackLimit-(char*)stackLimit) < REQUIRED_SCRIPTING_STACK_SIZE)
		return false;
	else
		return true;
}

void AssertStackLargeEnough ()
{	
	if (!IsStackLargeEnough ())
	{
		Scripting::RaiseManagedException ("System", "StackOverflowException", "");
	}
}

#endif

std::string ErrorMessageForUnsupportedEnumField(MonoType* enumType, MonoType* classType, const char * fieldName)
{
	char* enumTypeName = mono_type_get_name (enumType);
	char* classTypeName = mono_type_get_name (classType);

	std::string message = Format("Unsupported enum type '%s' used for field '%s' in class '%s'", 
		enumTypeName,
		fieldName,
		classTypeName);

	g_free(enumTypeName);
	g_free(classTypeName);

	return message;
}

#if MONO_QUALITY_ERRORS
MonoObject* MonoObjectNULL (ScriptingClassPtr klass, ScriptingStringPtr error)
{
	AssertMsg (klass, "NULL scripting class!");
	if (NULL == klass)
		return NULL;

	if (mono_class_is_subclass_of (klass, GetScriptingManager ().GetCommonClasses ().monoBehaviour, 0))
		return NULL;
	if (mono_class_is_subclass_of (klass, GetScriptingManager ().GetCommonClasses ().scriptableObject, 0))
		return NULL;

	if (!mono_class_is_subclass_of (klass, GetScriptingManager ().GetCommonClasses ().unityEngineObject, 0))
		return NULL;

	if (mono_unity_class_is_abstract (klass) || mono_unity_class_is_interface (klass))
		return NULL;

	ScriptingObjectPtr scriptingobject = mono_object_new (mono_domain_get (), klass);
	if (scriptingobject == NULL)
		return NULL;

	ScriptingObjectOfType<Object> object (scriptingobject);
	object.SetInstanceID (0);

	if (error != NULL)
		object.SetError (error);

	return scriptingobject;
}

MonoObject* MonoObjectNULL (int classID, MonoString* error)
{
	AssertIf (classID == -1);
	if (classID == ClassID (MonoBehaviour))
		return NULL;

	ScriptingObjectPtr scriptingobject = Scripting::InstantiateScriptingWrapperForClassID(classID);
	if (scriptingobject == NULL)
		return NULL;

	ScriptingObjectOfType<Object> object(scriptingobject);
	object.SetInstanceID(0);
	
	if (error != NULL)
		object.SetError(error);

	return scriptingobject;
}

MonoString* MissingComponentString (GameObject& go, const char* klassName)
{
		return MonoStringFormat(
							"MissingComponentException:There is no '%s' attached to the \"%s\" game object, but a script is trying to access it.\n"
							"You probably need to add a %s to the game object \"%s\". Or your script needs to check if the component is attached before using it.",
							klassName, go.GetName(), klassName, go.GetName());
}

MonoString* MissingComponentString (GameObject& go, int classID)
{
	const string& className = Object::ClassIDToString(classID);
	return MissingComponentString(go,className.c_str());
}

MonoString* MissingComponentString (GameObject& go, ScriptingTypePtr klass)
{
	return MissingComponentString(go,scripting_class_get_name(klass));
}

#endif

int mono_array_length (MonoArray* array)
{
	char* raw = sizeof(uintptr_t)*3 + (char*)array;
	return *reinterpret_cast<uintptr_t*> (raw);
}

int mono_array_length_safe (MonoArray* array)
{
	if (array)
	{
		char* raw = sizeof(uintptr_t)*3 + (char*)array;
		return *reinterpret_cast<uintptr_t*> (raw);
	}
	else
	{
		return 0;
	}
}

ScriptingClassPtr GetBuiltinScriptingClass(const char* name,bool optional)
{
	return GetMonoManager().GetBuiltinMonoClass(name,optional);
}


#if USE_MONO_AOT && !(UNITY_XENON || UNITY_PS3)

// Flag defined in mono, when AOT libraries are built with -ficall option
// But that is not available in mono/consoles
extern "C" int mono_ficall_flag;

void* ResolveMonoMethodPointer(MonoDomain* domain, MonoMethod* method)
{
	return mono_ficall_flag && method ?  mono_aot_get_method(domain, method) : NULL;	
}
#else
void* ResolveMonoMethodPointer(MonoDomain* domain, MonoMethod* method)
{
	return NULL;
}
#endif

void mono_runtime_object_init_exception (MonoObject *thiss, MonoException** exception)
{
	MonoClass *klass = mono_object_get_class (thiss);

	MonoMethod *method;
	void* iter = NULL;
	while ((method = mono_class_get_methods (klass, &iter))) {
		MonoMethodSignature *signature = mono_method_signature (method);
		if (!signature) {
			ErrorString (Format ("Error looking up signature for method %s.%s", mono_class_get_name (klass), mono_method_get_name (method)));
			continue;
		}
		int paramCount = mono_signature_get_param_count (signature);
		if (!strcmp (".ctor", mono_method_get_name (method)) && signature && paramCount == 0)
			break;
	}

	if (method)
	{
		AssertIf (mono_class_is_valuetype (mono_method_get_class (method)));
		mono_runtime_invoke_profiled (method, thiss, NULL, exception);
	}
	else
	{
		*exception = NULL;	
	}
}

void mono_runtime_object_init_log_exception (MonoObject *thiss)
{
	if (!thiss)
		return;
	MonoException* exc = NULL;
	mono_runtime_object_init_exception(thiss, &exc);
	if (exc)
		::Scripting::LogException(exc, 0);
}

/*
mono_enumerator_next (MonoObject* enumerable, gconstpointer pointer)
{

}*/

bool IsUtf16InAsciiRange( gunichar2 const* str, int length )
{
	gunichar2 const* strEnd = str + length;
	while( str != strEnd )
	{ //length-- ) {
		if( (*str & ~((gunichar2)0x7f)) != 0 )
			return false;
		++str;
	}
	return true;
}

bool FastTestAndConvertUtf16ToAscii( char* destination, gunichar2 const* str, int length )
{
	gunichar2 const* strEnd = str + length;
	while( str != strEnd ) { //length-- ) {
		if( (*str & ~((gunichar2)0x7f)) != 0 )
			return false;
		*destination = (char)*str;
		++destination;
		++str;
	}
	return true;
}

// converts symbols in the range 0x00-0x7f from unicode16 to ascii (excluding the terminating 0 character)
void fastUtf16ToAscii( char* destination, gunichar2 const* str, int length )
{
	gunichar2 const* strEnd = str + length;
	while( str != strEnd ) {
		*destination = (char)*str;
		++destination;
		++str;
	}
}

#if UNITY_WIN || UNITY_XENON
std::wstring MonoStringToWideCpp (MonoString* monoString)
{
	if (monoString)
	{
		wchar_t* buf = (wchar_t*)mono_string_to_utf16(monoString);
		std::wstring temp (buf);
		g_free (buf);
		return temp;
	}
	else
		return std::wstring ();
}
#endif

std::string MonoStringToCpp (MonoString* monoString)
{
	if (!monoString)
		return string ();
	
	char buff[256];
	if(monoString->length <= 256 && FastTestAndConvertUtf16ToAscii (buff,mono_string_chars(monoString), mono_string_length(monoString)) )
		return string((char const*)buff,mono_string_length (monoString));
		
	char* buf = mono_string_to_utf8 (monoString);
	string temp (buf);
	g_free (buf);
	return temp;
}

MonoArray *mono_array_new_2d (int size0, int size1, MonoClass *klass) {
	guint32 sizes[] = {size0, size1};
	MonoClass* ac = mono_array_class_get (klass, 2);

	return mono_array_new_full(mono_domain_get (), ac, sizes, NULL);
}

MonoArray *mono_array_new_3d (int size0, int size1, int size2, MonoClass *klass) {
	guint32 sizes[] = {size0, size1, size2};
	MonoClass* ac = mono_array_class_get (klass, 3);

	return mono_array_new_full(mono_domain_get (), ac, sizes, NULL);
}

std::string MonoStringToCppChecked (MonoObject* monoString)
{
	if (monoString && mono_type_get_type(mono_class_get_type(mono_object_get_class(monoString))) == MONO_TYPE_STRING)
	{
		char* buf = mono_string_to_utf8 ((MonoString*)monoString);
		string temp (buf);
		g_free (buf);
		return temp;
	}
	else
		return string ();
}

inline bool ExtractLineAndPath (const string& exception, string::size_type& pathBegin, int& line, string& path)
{
	// Extract line and path from exception ...
	// Format is: in [0x00031] (at /Users/.../filename.cs:51)
	
	pathBegin = exception.find ("(at ", pathBegin);
	
	if (pathBegin != string::npos)
	{
		pathBegin += 4;

		// On Windows, there's a ':' right at the beginning as part of drive
		#if UNITY_WIN && UNITY_EDITOR
		std::string::size_type pathEnd = exception.find (':', exception.size() > pathBegin+2 ? pathBegin+2 : pathBegin);
		#else
		std::string::size_type pathEnd = exception.find (':', pathBegin);
		#endif
		if (pathEnd != string::npos)
		{
			path.assign (exception.begin () + pathBegin, exception.begin () + pathEnd);
			line = atoi (exception.c_str () + pathEnd + 1);
			pathBegin = pathEnd;
			ConvertSeparatorsToUnity(path);
			return true;
		}	
	}
	return false;
}

inline bool IsScriptAssetPath (const string& path)
{
	const string& projectDir = File::GetCurrentDirectory ();
	// C# returns absolute path names
	if (path.find (projectDir) == 0)
		return true;
	// Boo returns relative path names
	if (!IsAbsoluteFilePath(path) )
		return true;
	return false;
}

bool ExceptionToLineAndPath (const string& stackTrace, int& line, string& path)
{
	// Extract line and path from exception...
	// We want the topmost exception function trace that is in the project folder. 
	// If there is nothing in the project folder we return the topmost.
	// Format is: in [0x00031] (at /Users/.../filename.cs:51)
	string::size_type searchStart = 0;
	
	if (ExtractLineAndPath (stackTrace, searchStart, line, path) && !IsScriptAssetPath (path))
	{
		string tempPath;
		int tempLine;
		while (ExtractLineAndPath (stackTrace, searchStart, tempLine, tempPath))
		{
			if (!IsAbsoluteFilePath(tempPath))
			{
				path = tempPath;
				line = tempLine;
				break;
			}
		}
		return true;
	}
	else
		return false;
}


string SimpleGetExceptionString(MonoException* exception)
{
	MonoClass* klass = mono_object_get_class((MonoObject*)exception);
	if (!klass)
		return "";
	
	MonoMethod* toString = mono_class_get_method_from_name(mono_get_exception_class(), "ToString", 0);
	if (!toString)
		return "";

	MonoString* exceptionString = (MonoString*)mono_runtime_invoke_profiled(toString, (MonoObject*)exception, NULL, NULL);
	if (!exceptionString)
		return "";

	return mono_string_to_utf8(exceptionString);
}

MonoString* MonoStringNew (const std::string& in)
{
	return MonoStringNew (in.c_str ());
}

MonoString* MonoStringNew (const char* in)
{
	Assert (in != NULL);
	MonoString* mono = mono_string_new_wrapper (in);
	if (mono != NULL)
		return mono;
	else
	{
		// This can happen when conversion fails eg. converting utf8 to ascii or something i guess.
		mono = mono_string_new_wrapper ("");
		Assert (mono != NULL);
		return mono;
	}
}

MonoString* MonoStringNewUTF16 (const wchar_t* in)
{
	Assert (in != NULL);
	MonoString* mono = mono_string_from_utf16 ( (const gunichar2*)in );
	if (mono != NULL)
		return mono;
	else
	{
		// See MonoStringNew
		mono = mono_string_new_wrapper ("");
		Assert (mono != NULL);
		return mono;
	}
}

MonoString* MonoStringNewLength (const char* in, int length)
{
	Assert (in != NULL);
	Assert (length >= 0);
	MonoDomain* domain = mono_domain_get ();
	Assert (domain != NULL);
	MonoString* mono = mono_string_new_len (domain, in, length);
	if (mono != NULL)
		return mono;
	else
	{
		// This can happen when conversion fails eg. converting utf8 to ascii or something i guess.
		mono = mono_string_new_wrapper ("");
		Assert (mono != NULL);
		return mono;
	}
}

bool MonoSetObjectField(MonoObject* target, const char* fieldname, MonoObject* value)
{
	MonoClass* klass = mono_object_get_class(target);
	MonoClassField* field = mono_class_get_field_from_name(klass,fieldname);
	if (!field) return false;
	mono_field_set_value(target,field,value);
	return true;
}

bool MonoObjectToBool (MonoObject* value)
{
	if (value && mono_type_get_type (mono_class_get_type (mono_object_get_class (value))) == MONO_TYPE_BOOLEAN)
		return ExtractMonoObjectData<char> (value);
	else
		return false;
}

int MonoObjectToInt (MonoObject* value)
{
	if (value && mono_type_get_type (mono_class_get_type (mono_object_get_class (value))) == MONO_TYPE_I4)
		return ExtractMonoObjectData<int> (value);
	else
		return -1;
}

MonoAssembly* mono_load_assembly_from_any_monopath(const char* assemblyname)
{
	MonoDomain* domain = mono_domain_get();
	std::vector<string>& monoPaths = MonoPathContainer::GetMonoPaths();
	for (int i=0; i!=monoPaths.size(); i++)
	{
		MonoAssembly* ass = mono_domain_assembly_open(domain, AppendPathName(monoPaths[i],assemblyname).c_str());
		if (ass) return ass;
	}
	return NULL;
}

MonoMethod* mono_unity_find_method(const char* assemblyname, const char* ns, const char* klass, const char* methodname)
{
//todo: be less stupid about always trying to load an assembly that will be already loaded 99% of the time
	MonoAssembly* ass = mono_load_assembly_from_any_monopath(assemblyname);
	if (!ass) return NULL;
	MonoImage* img = mono_assembly_get_image(ass);
	if (!img) return NULL;
	MonoMethod* method = FindStaticMonoMethod(img,klass,ns,methodname);
	if (!method) return NULL;
	return method;
}

MonoMethod* mono_reflection_method_get_method (MonoObject* ass)
{
	return ExtractMonoObjectData<MonoMethod*>(ass);
}

MonoString* MonoStringFormat (const char* format, ...)
{
	using namespace std;
	va_list vl;
	va_start( vl, format );
	char buffer[1024 * 5];
	vsnprintf (buffer, 1024 * 5, format, vl);
	va_end (vl);
	return mono_string_new_wrapper(buffer);
}

void StringMonoArrayToVector (MonoArray* arr, std::vector<UnityStr>& container)
{
	container.resize(mono_array_length_safe(arr));
	for (int i=0;i<container.size();i++)
	{
		container[i] = MonoStringToCpp(GetMonoArrayElement<MonoString*> (arr, i));
	}
}

void StringMonoArrayToVector (MonoArray* arr, std::vector<std::string>& container)
{
	container.resize(mono_array_length_safe(arr));
	for (int i=0;i<container.size();i++)
	{
		container[i] = MonoStringToCpp(GetMonoArrayElement<MonoString*> (arr, i));
	}
}


void SetReferenceDataOnScriptingWrapper(MonoObject* wrapper, const UnityEngineObjectMemoryLayout& data)
{
	UnityEngineObjectMemoryLayout* wrapperdata = reinterpret_cast<UnityEngineObjectMemoryLayout*> (((char*)wrapper) + kMonoObjectOffset);
	memcpy(wrapperdata,&data,sizeof(UnityEngineObjectMemoryLayout));
}

MonoObject* mono_class_get_object (MonoClass* klass)
{
	if (klass == NULL)
		return NULL;
	
	MonoType* type = mono_class_get_type(klass);
	if (type)
		return mono_type_get_object (mono_domain_get(), type);
	else
		return NULL;
}

MonoClass* mono_type_get_class_or_element_class (MonoType* type)
{
#if MONO_2_12
	MonoClass* klass = mono_class_from_mono_type (type);
	if (mono_class_get_rank (klass) > 0)
	{
		klass = mono_class_get_element_class (klass);
	}

	return klass;
#else
	return mono_type_get_class (type);
#endif
}

int mono_array_length_safe_wrapper(MonoArray* array)
{
	return mono_array_length_safe(array);
}

#if MONO_QUALITY_ERRORS
MonoString* UnassignedReferenceString (MonoObject* instance, int classID, MonoClassField* field, int instanceID)
{
	MonoClass* klass = NULL;
	if (instance == NULL)
		return NULL;
	// Transfer sometimes provides us with non-object derived instances so we simply ignore those
	klass = mono_object_get_class(instance);
	if (!mono_class_is_subclass_of(klass, GetMonoManager().GetCommonClasses().unityEngineObject, false))
		return NULL;
	
	const char* fieldName = mono_field_get_name(field);
	const char* klassName = mono_class_get_name(mono_object_get_class(instance));
	
	if (instanceID == 0)
	{
		return MonoStringFormat(
								"UnassignedReferenceException:The variable %s of '%s' has not been assigned.\n"
								"You probably need to assign the %s variable of the %s script in the inspector.",
								fieldName, klassName, fieldName, klassName);
	}
	else
	{
		return MonoStringFormat(
								"MissingReferenceException:The variable %s of '%s' doesn't exist anymore.\n"
								"You probably need to reassign the %s variable of the '%s' script in the inspector.",
								fieldName, klassName, fieldName, klassName);
	}
}
#endif

MonoClassField* GetMonoArrayFieldFromList (int type, MonoType* monoType, MonoClassField* field)
{
	if (type != MONO_TYPE_GENERICINST)
		return NULL;
	
	MonoClass* elementClass = mono_class_from_mono_type(monoType);
	
	// Check that we have a Generic List class
	const char* className = mono_class_get_name(elementClass);
	if (strcmp(className, "List`1") != 0 || mono_class_get_image(elementClass) != mono_get_corlib())
		return NULL;
	
	MonoClassField *arrayField;
	void* iter_list = NULL;
	
	// List<> first element is something called Default Capacity
	// Second is the actual array
	// But, Mono 2.12 reordered the fields
#if !MONO_2_12
	mono_class_get_fields (elementClass, &iter_list);
#endif
	arrayField = mono_class_get_fields (elementClass, &iter_list);
	
#if !UNITY_RELEASE
	AssertIf(strcmp(mono_field_get_name(arrayField), "_items") != 0);
	AssertIf(mono_field_get_offset(arrayField) != kMonoObjectOffset);
	
	MonoClassField* sizeField = mono_class_get_fields (elementClass, &iter_list);
	AssertIf(strcmp(mono_field_get_name(sizeField), "_size") != 0);
	AssertIf(mono_field_get_offset(sizeField) != kMonoObjectOffset + sizeof(intptr_t));
#endif
	
	return arrayField;
}

static int currentDomainId = 0;

int MonoDomainGetUniqueId()
{
	return currentDomainId;
}

void MonoDomainIncrementUniqueId()
{
	currentDomainId++;
}