From: Nutchanon Wetchasit <Nutchanon.Wetchasit@gmail.com>
Subject: Use _global as "this" for ExternalInterface callback that lacks it.
Bug: https://savannah.gnu.org/bugs/?37223

This fixes special cases of bug #37223 where instance object of
the callback is set to null or undefined at registration time.
See <https://savannah.gnu.org/bugs/?37223>

diff --git a/libcore/movie_root.cpp b/libcore/movie_root.cpp
index 55e45c5..cb63f7d 100644
--- a/libcore/movie_root.cpp
+++ b/libcore/movie_root.cpp
@@ -1942,6 +1942,12 @@ movie_root::callExternalCallback(const std::string &name,
         }
         else instance = instance_iterator->second;
 
+        // Use _global object as "this" instance if the callback is originally
+        // registered with null or undefined one.
+        if (instance == NULL) {
+            instance = &getGlobal(*method);
+        }
+
         // Populate function call arguments
         for (std::vector<as_value>::const_iterator args_iterator
                  = fnargs.begin();
diff --git a/testsuite/misc-mtasc.all/extcomm.as b/testsuite/misc-mtasc.all/extcomm.as
index dcf7862..df80226 100644
--- a/testsuite/misc-mtasc.all/extcomm.as
+++ b/testsuite/misc-mtasc.all/extcomm.as
@@ -89,12 +89,13 @@ class ExternalCommTest
 				{
 					// `this` should be an "undefined" object like one in
 					// a function called via `function.call(null)`
-					xcheck_equals(typeof(this), "object");
+					check_equals(typeof(this), "object");
 					check(this == undefined);
 					check(this == null);
 					check(this !== undefined);
-					xcheck(this !== null);
-					xcheck_equals("" + this, "undefined");
+					check(this !== null);
+					check_equals("" + this, "undefined");
+					check(this === _global);
 				}
 			)
 		);
@@ -104,12 +105,13 @@ class ExternalCommTest
 				{
 					// `this` should be an "undefined" object like one in
 					// a function called via `function.call(undefined)`
-					xcheck_equals(typeof(this), "object");
+					check_equals(typeof(this), "object");
 					check(this == undefined);
 					check(this == null);
 					check(this !== undefined);
-					xcheck(this !== null);
-					xcheck_equals("" + this, "undefined");
+					check(this !== null);
+					check_equals("" + this, "undefined");
+					check(this === _global);
 				}
 			)
 		);
diff --git a/testsuite/misc-mtasc.all/extcommtests-runner.sh b/testsuite/misc-mtasc.all/extcommtests-runner.sh
index 80cd550..2ac31a4 100644
--- a/testsuite/misc-mtasc.all/extcommtests-runner.sh
+++ b/testsuite/misc-mtasc.all/extcommtests-runner.sh
@@ -281,7 +281,7 @@ XFAILED=\`expr "\$XFAILED" + "\$PLAYERXFAILED"\`
 TESTED=\`expr "\$TESTED" + "\$PLAYERPASSED" + "\$PLAYERXPASSED" + "\$PLAYERFAILED" + "\$PLAYERXFAILED"\`
 
 # Check for total number of test run
-check_totals "87" "There should be 87 tests run"
+check_totals "89" "There should be 89 tests run"
 
 # Remove temporary files
 rm "\$LOGFILE"
