summaryrefslogtreecommitdiffstats
path: root/Python
diff options
context:
space:
mode:
authorMichael W. Hudson <mwh@python.net>2005-06-20 16:52:57 (GMT)
committerMichael W. Hudson <mwh@python.net>2005-06-20 16:52:57 (GMT)
commit188d4366bed88bbca777c05e7f1a5cb3878ff335 (patch)
treeb77be5cef3108cf44dbf6bcd8e53dc23a77112e7 /Python
parentfb662972e001aa051e5085862cf5eac323e1756f (diff)
downloadcpython-188d4366bed88bbca777c05e7f1a5cb3878ff335.zip
cpython-188d4366bed88bbca777c05e7f1a5cb3878ff335.tar.gz
cpython-188d4366bed88bbca777c05e7f1a5cb3878ff335.tar.bz2
Fix bug:
[ 1163563 ] Sub threads execute in restricted mode basically by fixing bug 1010677 in a non-broken way. Backport candidate.
Diffstat (limited to 'Python')
-rw-r--r--Python/pystate.c68
1 files changed, 53 insertions, 15 deletions
diff --git a/Python/pystate.c b/Python/pystate.c
index e2cf7c5..3ac799c 100644
--- a/Python/pystate.c
+++ b/Python/pystate.c
@@ -36,6 +36,12 @@ static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */
#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
#define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
#define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
+
+/* The single PyInterpreterState used by this process'
+ GILState implementation
+*/
+static PyInterpreterState *autoInterpreterState = NULL;
+static int autoTLSkey = 0;
#else
#define HEAD_INIT() /* Nothing */
#define HEAD_LOCK() /* Nothing */
@@ -47,6 +53,8 @@ static PyInterpreterState *interp_head = NULL;
PyThreadState *_PyThreadState_Current = NULL;
PyThreadFrameGetter _PyThreadState_GetFrame = NULL;
+static void _PyGILState_NoteThreadState(PyThreadState* tstate);
+
PyInterpreterState *
PyInterpreterState_New(void)
@@ -180,6 +188,8 @@ PyThreadState_New(PyInterpreterState *interp)
tstate->c_profileobj = NULL;
tstate->c_traceobj = NULL;
+ _PyGILState_NoteThreadState(tstate);
+
HEAD_LOCK();
tstate->next = interp->tstate_head;
interp->tstate_head = tstate;
@@ -261,6 +271,8 @@ PyThreadState_DeleteCurrent()
"PyThreadState_DeleteCurrent: no current tstate");
_PyThreadState_Current = NULL;
tstate_delete_common(tstate);
+ if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate)
+ PyThread_delete_key_value(autoTLSkey);
PyEval_ReleaseLock();
}
#endif /* WITH_THREAD */
@@ -393,12 +405,6 @@ PyThreadState_IsCurrent(PyThreadState *tstate)
return tstate == _PyThreadState_Current;
}
-/* The single PyInterpreterState used by this process'
- GILState implementation
-*/
-static PyInterpreterState *autoInterpreterState = NULL;
-static int autoTLSkey = 0;
-
/* Internal initialization/finalization functions called by
Py_Initialize/Py_Finalize
*/
@@ -408,12 +414,10 @@ _PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
assert(i && t); /* must init with valid states */
autoTLSkey = PyThread_create_key();
autoInterpreterState = i;
- /* Now stash the thread state for this thread in TLS */
assert(PyThread_get_key_value(autoTLSkey) == NULL);
- if (PyThread_set_key_value(autoTLSkey, (void *)t) < 0)
- Py_FatalError("Couldn't create autoTLSkey mapping");
- assert(t->gilstate_counter == 0); /* must be a new thread state */
- t->gilstate_counter = 1;
+ assert(t->gilstate_counter == 0);
+
+ _PyGILState_NoteThreadState(t);
}
void
@@ -424,6 +428,41 @@ _PyGILState_Fini(void)
autoInterpreterState = NULL;;
}
+/* When a thread state is created for a thread by some mechanism other than
+ PyGILState_Ensure, it's important that the GILState machinery knows about
+ it so it doesn't try to create another thread state for the thread (this is
+ a better fix for SF bug #1010677 than the first one attempted).
+*/
+void
+_PyGILState_NoteThreadState(PyThreadState* tstate)
+{
+ /* If autoTLSkey is 0, this must be the very first threadstate created
+ in Py_Initialize(). Don't do anything for now (we'll be back here
+ when _PyGILState_Init is called). */
+ if (!autoTLSkey)
+ return;
+
+ /* Stick the thread state for this thread in thread local storage.
+
+ The only situation where you can legitimately have more than one
+ thread state for an OS level thread is when there are multiple
+ interpreters, when:
+
+ a) You shouldn't really be using the PyGILState_ APIs anyway,
+ and:
+
+ b) The slightly odd way PyThread_set_key_value works (see
+ comments by its implementation) means that the first thread
+ state created for that given OS level thread will "win",
+ which seems reasonable behaviour.
+ */
+ if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
+ Py_FatalError("Couldn't create autoTLSkey mapping");
+
+ /* PyGILState_Release must not try to delete this thread state. */
+ tstate->gilstate_counter = 1;
+}
+
/* The public functions */
PyThreadState *
PyGILState_GetThisThreadState(void)
@@ -450,8 +489,9 @@ PyGILState_Ensure(void)
tcur = PyThreadState_New(autoInterpreterState);
if (tcur == NULL)
Py_FatalError("Couldn't create thread-state for new thread");
- if (PyThread_set_key_value(autoTLSkey, (void *)tcur) < 0)
- Py_FatalError("Couldn't create autoTLSkey mapping");
+ /* This is our thread state! We'll need to delete it in the
+ matching call to PyGILState_Release(). */
+ tcur->gilstate_counter = 0;
current = 0; /* new thread state is never current */
}
else
@@ -498,8 +538,6 @@ PyGILState_Release(PyGILState_STATE oldstate)
* habit of coming back).
*/
PyThreadState_DeleteCurrent();
- /* Delete this thread from our TLS. */
- PyThread_delete_key_value(autoTLSkey);
}
/* Release the lock if necessary */
else if (oldstate == PyGILState_UNLOCKED)
d='n312' href='#n312'>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
"""SCons.Script.SConscript

This module defines the Python API provided to SConscript and SConstruct 
files.

"""

#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

import SCons
import SCons.Action
import SCons.Builder
import SCons.Defaults
import SCons.Environment
import SCons.Errors
import SCons.Node
import SCons.Node.Alias
import SCons.Node.FS
import SCons.Node.Python
import SCons.Platform
import SCons.SConf
import SCons.Script
import SCons.Util
import SCons.Options

import os
import os.path
import re
import string
import sys
import traceback
import types

def do_nothing(text): pass
HelpFunction = do_nothing

arguments = {}
launch_dir = os.path.abspath(os.curdir)

# global exports set by Export():
global_exports = {}

# chdir flag
sconscript_chdir = 1

def SConscriptChdir(flag):
    global sconscript_chdir
    sconscript_chdir = flag

def _scons_add_args(alist):
    global arguments
    for arg in alist:
        a, b = string.split(arg, '=', 2)
        arguments[a] = b

def get_calling_namespaces():
    """Return the locals and globals for the function that called
    into this module in the current callstack."""
    try: 1/0
    except: frame = sys.exc_info()[2].tb_frame
    
    while frame.f_globals.get("__name__") == __name__: frame = frame.f_back

    return frame.f_locals, frame.f_globals

    
def compute_exports(exports):
    """Compute a dictionary of exports given one of the parameters
    to the Export() function or the exports argument to SConscript()."""

    exports = SCons.Util.Split(exports)
    loc, glob = get_calling_namespaces()

    retval = {}
    try:
        for export in exports:
            if SCons.Util.is_Dict(export):
                retval.update(export)
            else:
                try:
                    retval[export] = loc[export]
                except KeyError:
                    retval[export] = glob[export]
    except KeyError, x:
        raise SCons.Errors.UserError, "Export of non-existant variable '%s'"%x

    return retval
    

class Frame:
    """A frame on the SConstruct/SConscript call stack"""
    def __init__(self, exports, sconscript):
        self.globals = BuildDefaultGlobals()
        self.retval = None 
        self.prev_dir = SCons.Node.FS.default_fs.getcwd()
        self.exports = compute_exports(exports)  # exports from the calling SConscript
        # make sure the sconscript attr is a Node.
        if isinstance(sconscript, SCons.Node.Node):
            self.sconscript = sconscript
        else:
            self.sconscript = SCons.Node.FS.default_fs.File(str(sconscript))
        
# the SConstruct/SConscript call stack:
stack = []

# For documentation on the methods in this file, see the scons man-page

def Return(*vars):
    retval = []
    try:
        for var in vars:
            for v in string.split(var):
                retval.append(stack[-1].globals[v])
    except KeyError, x:
        raise SCons.Errors.UserError, "Return of non-existant variable '%s'"%x
        
    if len(retval) == 1:
        stack[-1].retval = retval[0]
    else:
        stack[-1].retval = tuple(retval)

# This function is responsible for converting the parameters passed to
# SConscript() calls into a list of files and export variables.  If the
# parameters are invalid, throws SCons.Errors.UserError. Returns a tuple
# (l, e) where l is a list of SConscript filenames and e is a list of
# exports.

def GetSConscriptFilenames(ls, kw):
    exports = []

    if len(ls) == 0:
        try:
            dirs = kw["dirs"]
        except KeyError:
            raise SCons.Errors.UserError, \
                  "Invalid SConscript usage - no parameters"

        if not SCons.Util.is_List(dirs):
            dirs = [ dirs ]
        dirs = map(str, dirs)

        name = kw.get('name', 'SConscript')

        files = map(lambda n, name = name: os.path.join(n, name), dirs)

    elif len(ls) == 1:

        files = ls[0]

    elif len(ls) == 2:

        files   = ls[0]
        exports = SCons.Util.Split(ls[1])

    else:

        raise SCons.Errors.UserError, \
              "Invalid SConscript() usage - too many arguments"

    if not SCons.Util.is_List(files):
        files = [ files ]

    if kw.get('exports'):
        exports.extend(SCons.Util.Split(kw['exports']))

    build_dir = kw.get('build_dir')
    if build_dir:
        if len(files) != 1:
            raise SCons.Errors.UserError, \
                "Invalid SConscript() usage - can only specify one SConscript with a build_dir"
        duplicate = kw.get('duplicate', 1)
        src_dir = kw.get('src_dir')
        if not src_dir:
            src_dir, fname = os.path.split(str(files[0]))
        else:
            if not isinstance(src_dir, SCons.Node.Node):
                src_dir = SCons.Node.FS.default_fs.Dir(src_dir)
            fn = files[0]
            if not isinstance(fn, SCons.Node.Node):
                fn = SCons.Node.FS.default_fs.File(fn)
            if fn.is_under(src_dir):
                # Get path relative to the source directory.
                fname = fn.get_path(src_dir)
            else:
                # Fast way to only get the terminal path component of a Node.
                fname = fn.get_path(fn.dir)
        SCons.Node.FS.default_fs.BuildDir(build_dir, src_dir, duplicate)
        files = [os.path.join(str(build_dir), fname)]

    return (files, exports)

def _SConscript(fs, *ls, **kw):
    files, exports = GetSConscriptFilenames(ls, kw)

    top = fs.Top
    sd = fs.SConstruct_dir.rdir()

    # evaluate each SConscript file
    results = []
    for fn in files:
        stack.append(Frame(exports,fn))
        old_sys_path = sys.path
        try:
            if fn == "-":
                exec sys.stdin in stack[-1].globals
            else:
                if isinstance(fn, SCons.Node.Node):
                    f = fn
                else:
                    f = fs.File(str(fn))
                _file_ = None

                # Change directory to the top of the source
                # tree to make sure the os's cwd and the cwd of
                # fs match so we can open the SConscript.
                fs.chdir(top, change_os_dir=1)
                if f.rexists():
                    _file_ = open(f.rstr(), "r")
                elif f.has_src_builder():
                    # The SConscript file apparently exists in a source
                    # code management system.  Build it, but then clear
                    # the builder so that it doesn't get built *again*
                    # during the actual build phase.
                    f.build()
                    f.builder_set(None)
                    s = str(f)
                    if os.path.exists(s):
                        _file_ = open(s, "r")
                if _file_:
                    # Chdir to the SConscript directory.  Use a path
                    # name relative to the SConstruct file so that if
                    # we're using the -f option, we're essentially
                    # creating a parallel SConscript directory structure
                    # in our local directory tree.
                    #
                    # XXX This is broken for multiple-repository cases
                    # where the SConstruct and SConscript files might be
                    # in different Repositories.  For now, cross that
                    # bridge when someone comes to it.
                    ldir = fs.Dir(f.dir.get_path(sd))
                    try:
                        fs.chdir(ldir, change_os_dir=sconscript_chdir)
                    except OSError:
                        # There was no local directory, so we should be
                        # able to chdir to the Repository directory.
                        # Note that we do this directly, not through
                        # fs.chdir(), because we still need to
                        # interpret the stuff within the SConscript file
                        # relative to where we are logically.
                        fs.chdir(ldir, change_os_dir=0)
                        os.chdir(f.rfile().dir.get_abspath())

                    # Append the SConscript directory to the beginning
                    # of sys.path so Python modules in the SConscript
                    # directory can be easily imported.
                    sys.path = [ f.dir.get_abspath() ] + sys.path

                    # This is the magic line that actually reads up and
                    # executes the stuff in the SConscript file.  We
                    # look for the "exec _file_ " from the beginning
                    # of this line to find the right stack frame (the
                    # next one) describing the SConscript file and line
                    # number that creates a node.
                    exec _file_ in stack[-1].globals
                else:
                    sys.stderr.write("Ignoring missing SConscript '%s'\n" %
                                     f.path)
                
        finally:
            sys.path = old_sys_path
            frame = stack.pop()
            try:
                fs.chdir(frame.prev_dir, change_os_dir=sconscript_chdir)
            except OSError:
                # There was no local directory, so chdir to the
                # Repository directory.  Like above, we do this
                # directly.
                fs.chdir(frame.prev_dir, change_os_dir=0)
                os.chdir(frame.prev_dir.rdir().get_abspath())

            results.append(frame.retval)

    # if we only have one script, don't return a tuple
    if len(results) == 1:
        return results[0]
    else:
        return tuple(results)

def is_our_exec_statement(line):
    return not line is None and line[:12] == "exec _file_ "

def SConscript_exception(file=sys.stderr):
    """Print an exception stack trace just for the SConscript file(s).
    This will show users who have Python errors where the problem is,
    without cluttering the output with all of the internal calls leading
    up to where we exec the SConscript."""
    stack = traceback.extract_tb(sys.exc_traceback)
    last_text = ""
    i = 0
    for frame in stack:
        if is_our_exec_statement(last_text):
            break
        i = i + 1
        last_text = frame[3]
    type = str(sys.exc_type)
    if type[:11] == "exceptions.":
        type = type[11:]
    file.write('%s: %s:\n' % (type, sys.exc_value))
    for fname, line, func, text in stack[i:]:
        file.write('  File "%s", line %d:\n' % (fname, line))
        file.write('    %s\n' % text)

def annotate(node):
    """Annotate a node with the stack frame describing the
    SConscript file and line number that created it."""
    stack = traceback.extract_stack()
    last_text = ""
    for frame in stack:
        # If the script text of the previous frame begins with the
        # magic "exec _file_ " string, then this frame describes the
        # SConscript file and line number that caused this node to be
        # created.  Record the tuple and carry on.
        if is_our_exec_statement(last_text):
            node.creator = frame
            return
        last_text = frame[3]

# The following line would cause each Node to be annotated using the
# above function.  Unfortunately, this is a *huge* performance hit, so
# leave this disabled until we find a more efficient mechanism.
#SCons.Node.Annotate = annotate

class SConsEnvironment(SCons.Environment.Base):
    """An Environment subclass that contains all of the methods that
    are particular to the wrapper SCons interface and which aren't
    (or shouldn't be) part of the build engine itself.
    """

    #
    # Private functions of an SConsEnvironment.
    #

    def _check_version(self, major, minor, version_string):
        """Return 0 if 'major' and 'minor' are greater than the version
        in 'version_string', and 1 otherwise."""
        try:
            v_major, v_minor, v_micro, release, serial = sys.version_info
        except AttributeError:
            version = string.split(string.split(version_string, ' ')[0], '.')
            v_major = int(version[0])
            v_minor = int(re.match('\d+', version[1]).group())
        if major > v_major or (major == v_major and minor > v_minor):
            return 0
        else:
            return 1

    #
    # Public functions of an SConsEnvironment.  These get
    # entry points in the global name space so they can be called
    # as global functions.
    #

    def EnsureSConsVersion(self, major, minor):
        """Exit abnormally if the SCons version is not late enough."""
        if not self._check_version(major,minor,SCons.__version__):
            print "SCons %d.%d or greater required, but you have SCons %s" %(major,minor,SCons.__version__)
            sys.exit(2)

    def EnsurePythonVersion(self, major, minor):
        """Exit abnormally if the Python version is not late enough."""
        if not self._check_version(major,minor,sys.version):
            v = string.split(sys.version, " ", 1)[0]
            print "Python %d.%d or greater required, but you have Python %s" %(major,minor,v)
            sys.exit(2)

    def Exit(self, value=0):
        sys.exit(value)

    def Export(self, *vars):
        for var in vars:
            global_exports.update(compute_exports(var))

    def GetLaunchDir(self):
        global launch_dir
        return launch_dir

    def GetOption(self, name):
        name = self.subst(name)
        return SCons.Script.ssoptions.get(name)

    def Help(self, text):
        text = self.subst(text, raw=1)
        HelpFunction(text)

    def Import(self, *vars):
        try:
            for var in vars:
                var = SCons.Util.Split(var)
                for v in var:
                    if v == '*':
                        stack[-1].globals.update(global_exports)
                        stack[-1].globals.update(stack[-1].exports)
                    else:
                        if stack[-1].exports.has_key(v):
                            stack[-1].globals[v] = stack[-1].exports[v]
                        else:
                            stack[-1].globals[v] = global_exports[v]
        except KeyError,x:
            raise SCons.Errors.UserError, "Import of non-existant variable '%s'"%x

    def SConscript(self, *ls, **kw):
        ls = map(lambda l, self=self: self.subst(l), ls)
        subst_kw = {}
        for key, val in kw.items():
            if SCons.Util.is_String(val):
                val = self.subst(val)
            subst_kw[key] = val
        return apply(_SConscript, [self.fs,] + ls, subst_kw)

    def SetOption(self, name, value):
        name = self.subst(name)
        SCons.Script.ssoptions.set(name, value)

#
#
#
SCons.Environment.Environment = SConsEnvironment

def SetBuildSignatureType(type):
    SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning,
                        "The SetBuildSignatureType() function has been deprecated;\n" +\
                        "\tuse the TargetSignatures() function instead.")
    SCons.Defaults.DefaultEnvironment().TargetSignatures(type)

def SetContentSignatureType(type):
    SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning,
                        "The SetContentSignatureType() function has been deprecated;\n" +\
                        "\tuse the SourceSignatures() function instead.")
    SCons.Defaults.DefaultEnvironment().SourceSignatures(type)

class Options(SCons.Options.Options):
    def __init__(self, files=None, args=arguments):
        SCons.Options.Options.__init__(self, files, args)

def GetJobs():
    SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning,
                        "The GetJobs() function has been deprecated;\n" +\
                        "\tuse GetOption('num_jobs') instead.")

    return GetOption('num_jobs')
 
def SetJobs(num):
    SCons.Warnings.warn(SCons.Warnings.DeprecatedWarning,
                        "The SetJobs() function has been deprecated;\n" +\
                        "\tuse SetOption('num_jobs', num) instead.")
    SetOption('num_jobs', num)


def Alias(name):
    alias = SCons.Node.Alias.default_ans.lookup(name)
    if alias is None:
        alias = SCons.Node.Alias.default_ans.Alias(name)
    return alias

#
_DefaultEnvironmentProxy = None

def get_DefaultEnvironmentProxy():
    global _DefaultEnvironmentProxy
    if not _DefaultEnvironmentProxy:
        class EnvironmentProxy(SCons.Environment.Environment):
            """A proxy subclass for an environment instance that overrides
            the subst() and subst_list() methods so they don't actually
            actually perform construction variable substitution.  This is
            specifically intended to be the shim layer in between global
            function calls (which don't want want construction variable
            substitution) and the DefaultEnvironment() (which would
            substitute variables if left to its own devices)."""
            def __init__(self, subject):
                self.__dict__['__subject'] = subject
            def __getattr__(self, name):
                return getattr(self.__dict__['__subject'], name)
            def __setattr__(self, name, value):
                return setattr(self.__dict__['__subject'], name, value)
            def subst(self, string, raw=0, target=None, source=None):
                return string
            def subst_list(self, string, raw=0, target=None, source=None):
                return string
        default_env = SCons.Defaults.DefaultEnvironment()
        _DefaultEnvironmentProxy = EnvironmentProxy(default_env)
    return _DefaultEnvironmentProxy

def BuildDefaultGlobals():
    """
    Create a dictionary containing all the default globals for 
    SConstruct and SConscript files.
    """

    globals = {}
    globals['Action']            = SCons.Action.Action
    globals['Alias']             = Alias
    globals['ARGUMENTS']         = arguments
    globals['Builder']           = SCons.Builder.Builder
    globals['Configure']         = SCons.SConf.SConf
    globals['CScan']             = SCons.Defaults.CScan
    globals['DefaultEnvironment'] = SCons.Defaults.DefaultEnvironment
    globals['Environment']       = SCons.Environment.Environment
    globals['GetCommandHandler'] = SCons.Action.GetCommandHandler
    globals['Literal']           = SCons.Util.Literal
    globals['Options']           = Options
    globals['ParseConfig']       = SCons.Util.ParseConfig
    globals['Platform']          = SCons.Platform.Platform
    globals['Return']            = Return
    globals['SConscriptChdir']   = SConscriptChdir
    globals['Scanner']           = SCons.Scanner.Base
    globals['SetCommandHandler'] = SCons.Action.SetCommandHandler
    globals['Split']             = SCons.Util.Split
    globals['Tool']              = SCons.Tool.Tool
    globals['Value']             = SCons.Node.Python.Value
    globals['WhereIs']           = SCons.Util.WhereIs

    # Deprecated functions, leave this here for now.
    globals['GetJobs']           = GetJobs
    globals['SetBuildSignatureType'] = SetBuildSignatureType
    globals['SetContentSignatureType'] = SetContentSignatureType
    globals['SetJobs']           = SetJobs

    class DefaultEnvironmentCall:
        """A class that implements "global function" calls of
        Environment methods by fetching the specified method from the
        DefaultEnvironment's class.  Note that this uses an intermediate
        proxy class instead of calling the DefaultEnvironment method
        directly so that the proxy can override the subst() method and
        thereby prevent expansion of construction variables (since from
        the user's point of view this was called as a global function,
        with no associated construction environment)."""
        def __init__(self, method_name):
            self.method_name = method_name
        def __call__(self, *args, **kw):
            proxy = get_DefaultEnvironmentProxy()
            method = getattr(proxy.__class__, self.method_name)
            return apply(method, (proxy,) + args, kw)

    EnvironmentMethods = [
        'AddPostAction',
        'AddPreAction',
        'AlwaysBuild',
        'BuildDir',
        'CacheDir',
        'Clean',
        'Command',
        'Default',
        'Depends',
        'Dir',
        'File',
        'FindFile',
        'GetBuildPath',
        'Ignore',
        'Install',
        'InstallAs',
        'Local',
        'Precious',
        'Repository',
        'SConsignFile',
        'SideEffect',
        'SourceCode',
        'SourceSignatures',
        'TargetSignatures',
    ]

    SConsEnvironmentMethods = [
        'EnsurePythonVersion',
        'EnsureSConsVersion',
        'Exit',
        'Export',
        'GetLaunchDir',
        'GetOption',
        'Help',
        'Import',
        'SConscript',
        'SetOption',
    ]

    for name in EnvironmentMethods + SConsEnvironmentMethods:
        globals[name] = DefaultEnvironmentCall(name)

    return globals