def is_dmtcp_in_path():
def start_coordinator(n_port):
def kill_coordinator(n_port):
def get_num_checkpoints():
def get_num_peers():
def is_running():
def kill_peers():
def remove_stale_ptrace_files():
def create_master_branch(s_name):
def create_branch(s_name):
def switch_branch(s_name):
def branch_exists(s_name):
def checkpoint():
def restart(n_index):
def get_dmtcp_tmpdir_path(s_name):
def relocate_dmtcp_tmpdir(s_name):
def load_dmtcp_tmpdir(s_name):
def remove_checkpoint_files_of_index(n_index):
def remove_checkpoints_except_index(n_index):
def rename_index_to_base(n_index):
def reset_checkpoint_indexing():
def resume(s_fred_tmpdir, s_resume_dir):
def manager_teardown(): GS_FREDHIJACK_NAME = "fredhijack.so"
GS_FREDHIJACK_PATH = ""
    GS_FREDHIJACK_PATH = s_path
def reset_real_inferior_pid(n_gdb_pid):
def get_real_inferior_pid():
def set_virtual_inferior_pid(n_pid):
def get_virtual_inferior_pid():
def _read_real_inferior_pid(n_gdb_pid):
def kill_inferior():
def is_fredhijack_found():
def get_fredhijack_path():
def set_fredhijack_path(s_path):
def _execute_fred_command(s_cmd, s_arg=None):
def destroy():
def set_fred_breakpoint(n_index):
def wait_on_fred_breakpoint():
def send_fred_continue():
def get_current_thread():
def get_current_entry_index():
def get_total_entries():
def get_total_threads():
def current_fred_state():
    def __init__(self):
    def total_entries(self):
    def total_threads(self):
    def current_entry(self):
    def current_thread(self):
    def set_total_entries(self, n_entries):
    def set_total_threads(self, n_threads):
    def set_current_entry(self, n_entry):
    def set_current_thread(self, n_clone_id):
class FredState: GB_FRED_DEMO = False
GB_FRED_DEMO_FROM_USER = False
GS_FRED_DEMO_HIDE = ['info files\n', 'info breakpoints\n', 'where\n']
GS_FRED_DEMO_UNHIDE_PREFIX = ['next', 'step']
GN_MAX_PROMPT_LENGTH = 32
GN_PROMPT_WAIT_TIMEOUT = 20.0
GN_PYTHON_BUG_LOCK_TIMEOUT = 9999999
    GB_FRED_DEMO_FROM_USER = False # reset back to default, which is False
    GB_FRED_DEMO_FROM_USER = True
class ThreadedOutput(threading.Thread):
    def run(self):
def _start_output_thread():
def _reset_last_printed():
def _synchronously_drain_child_output():
def _send_child_input(input):
def _get_child_output():
def wait_for_prompt():
def _start_output_capture(wait_for_prompt, b_drain_first):
def _wait_for_captured_output(b_wait_for_prompt, b_timeout,
                              b_multi_page, b_hide_reset):
def get_child_response(s_input, b_timeout=False, hide=True,
                       b_wait_for_prompt=False, b_multi_page=True,
                       b_drain_first=False):
def _set_max_needs_input_length():
def _match_needs_user_input(s_str):
def _fred_completer(text, state):
def _spawn_child(argv):
def kill_child():
def signal_child(signum):
def child_is_alive():
def get_child_pid():
def get_command():
def send_command_nonblocking(command):
def send_command(command):
def reexec(argv):
def setup(l_argv, b_spawn_child=True):
def teardown(): GS_FRED_MASTER_BRANCH_NAME = "MASTER"
GS_NO_SYMBOL_ERROR = "FRED-NO-SYMBOL"
class ReversibleDebugger(debugger.Debugger):
        class TimeoutException(Exception):
class FredCommand():
class Branch():
class Checkpoint():
    def __init__(self, personality):
    def destroy(self):
    def create_master_branch(self):
    def do_branch(self, s_name):
    def switch_to_branch(self, s_name):
    def setup_from_resume(self):
    def do_checkpoint(self):
    def remove_checkpoint(self, n_index):
    def reset_on_restart(self):
    def do_restart(self, n_index=-1, b_clear_history=False):
    def do_restart_previous(self):
    def print_branches(self):
    def history(self):
    def log_command(self, s_command):
    def log_fred_command(self, cmd):
    def execute_fred_command(self, cmd, b_update=True):
    def do_next(self, n=1):
    def do_next_no_deadlock(self, n=1):
    def do_step(self, n=1):
    def do_step_no_deadlock(self, n=1):
    def append_step_over_libc(self, l_history):
    def do_continue(self, b_wait_for_prompt=True):
    def do_breakpoint(self, expr):
    def do_print(self, expr, b_drain_first=False):
    def do_switch_to_thread(self, n_tid):
    def set_log_breakpoint(self, n_log_index):
    def do_log_continue(self):
    def _copy_fred_commands(self, l_cmds):
    def current_checkpoint(self):
    def copy_current_checkpoint_history(self):
    def _coalesce_history(self, l_history):
    def replay_history(self, l_history=[], n=-1):
        def timeout_handler(signum, frame):
    def replay_history_helper(self, l_history=[], n=-1):
    def first_n_commands(self, l_history, n):
    def trim_n_cmds(self, l_history, n):
    def test_expression(self, s_expr, s_expr_val):
    def evaluate_expression(self, s_expr):
    def report_timing_statistics(self):
    def __init__(self, name, args=""):
    def __repr__(self):
    def copy(self):
    def native_repr(self):
    def set_native(self, s_repr):
    def set_ignore(self):
    def set_count_cmd(self, b_allowed):
    def is_unknown(self):
    def is_next(self):
    def is_step(self):
    def is_continue(self):
    def is_breakpoint(self):
    def is_log_breakpoint(self):
    def is_log_continue(self):
    def is_switch_thread(self):
    def count(self):
    def set_count(self, n):
    def __init__(self, s_name):
    def do_checkpoint(self):
    def remove_checkpoint(self, n_index):
    def do_restart(self, n_index, b_clear_history, reset_fnc):
    def add_checkpoint(self, ckpt):
    def get_checkpoint(self, n_index):
    def get_last_checkpoint(self):
    def get_all_checkpoints(self):
    def get_current_checkpoint(self):
    def set_current_checkpoint(self, ckpt):
    def get_num_checkpoints(self):
    def get_name(self):
    def all_history(self):
    def __init__(self, n_index=-1):
    def __repr__(self):
    def clear_history(self):
    def get_history(self):
    def set_history(self, l_history):
    def get_index(self):
    def set_index(self, n_index):
    def log_command(self, cmd):
    def number_non_ignore_cmds(self):
    def last_command(self):
    def last_command_non_ignore(self):
    def trim_non_ignore(self, n):
def fred_next_cmd():
def fred_step_cmd():
def fred_continue_cmd():
def fred_breakpoint_cmd():
def fred_where_cmd():
def fred_info_breakpoints_cmd():
def fred_print_cmd():
def fred_unknown_cmd():
def fred_log_breakpoint_cmd():
def fred_log_continue_cmd():
def fred_switch_thread_cmd(): GS_FILE_PATH_RE = "[/a-zA-Z0-9_\-\.]+"
GB_DEBUG = False
GB_ENABLE_TIMINGS = True
class PromptTimeoutException(Exception):
def last_n(s, source, n):
def fred_info(message):
def fred_error(message):
def fred_warning(message):
def fred_fatal(message):
def fred_debug(msg):
def fred_assert(b_expr, msg="Assertion failed."):
def fred_timer_start(s_timer_name):
def fred_timer_stop(s_timer_name):
def getRE(str, idx=0):
def getREWork(str):
def to_int(str, n_default=0):
def open_file(s_filename):
def fred_teardown():
def fred_quit(exit_code):
def set_env_var_if_unset(s_name, s_val):
def execute_shell_command_and_wait(l_cmd):
def execute_shell_command(l_cmd):
def execute_background_shell_command(l_cmd): def reverse_watch(dbg, s_expr):
    """Perform 'reverse-watch' command on expression.
    'dbg' is the instance of ReversibleDebugger on which to operate."""
    s_expr_val = dbg.evaluate_expression(s_expr)
    fredutil.fred_debug("RW: Starting with expr value '%s'" % s_expr_val)
    # Find starting checkpoint using binary search:
    binary_search._binary_search_checkpoints(dbg, s_expr, s_expr_val)

    # STILL TESTING:  When "else" branch works well, it will become permanent,
    #  and the remaining branch of "if" can be removed.
    if False:
        dbg.current_checkpoint().set_history(
            binary_search._binary_search_history(dbg,
              dbg.copy_current_checkpoint_history(),
              0, s_expr, s_expr_val))
    else:
        if dbg.branch.get_num_checkpoints() == 0:
            fredutil.fred_error("No checkpoints found for reverse-watch.")
            return
        l_history_copy = dbg.copy_current_checkpoint_history()
        try:
	    dbg.current_checkpoint().set_history(
                binary_search.NEW_binary_search_since_last_checkpoint(dbg, l_history_copy,
                                                               0, s_expr, s_expr_val))
        except binary_search.BinarySearchTooFarAtStartError:
	    fredutil.fred_debug("BinarySearchTooFarAtStartError handled")
            fredutil.fred_info(
	        'reverse-watch failed; expr "%s"\n  is same at start and end.'
		% s_expr )
    dbg.update_state()
    fredutil.fred_debug("Reverse watch finished.") def reverse_next(dbg, n=1):
    """Perform n 'reverse-next' commands."""
    if dbg.branch.get_num_checkpoints() == 0:
        fredutil.fred_error("No checkpoints found for reverse-next.")
        return
    while n > 0:
        n -= 1
        dbg.update_state()
        orig_state = dbg.state().copy()
        l_history = dbg.copy_current_checkpoint_history()
        while True:
            # Trimming ignore commands. TODO: This could delete commands
            # with side effects like "p var++".
            while len(l_history)>0 and \
                    not l_history[-1].is_step() and \
                    not l_history[-1].is_next() and \
                    not l_history[-1].is_continue():
                del l_history[-1]
            if len(l_history) == 0:
                break
            if l_history[-1].is_step():
                dbg.trim_n_cmds(l_history, 1)
                break
            elif l_history[-1].is_next():
                level = dbg.state().level()
                if not dbg.program_is_running():
                    level = -99
                dbg.trim_n_cmds(l_history, 1)
                dbg.do_restart(b_clear_history = True)
                dbg.replay_history(l_history)
                if dbg.state().level() == level:
                    break
                elif dbg.state().level() == level+1:
                    # The last 'n' returned from fnc; go to before fnc call
                    dbg.current_checkpoint().set_history(l_history)
                    reverse_finish.reverse_finish(dbg)
                    l_history = dbg.current_checkpoint().get_history()
                    break
                else:
                    # The last 'n' entered fnc or exited program
                    fredutil.fred_assert(dbg.state().level() == level-1 or
                                         level == -99)

            fredutil.fred_assert(l_history[-1].is_continue() or
                                 (l_history[-1].is_next() and dbg.at_breakpoint())
                                 or level == -99)
            if True:  # if is_continue() or (is_next() and at_breakpoint())
                # if it was l_history[-1].is_next() and hit a breakpoint,
                # then it acts like 'c'.  Already undid last command for 'n'
                if l_history[-1].is_continue():
                    del l_history[-1]
                    dbg.do_restart(b_clear_history = True)
                    dbg.replay_history(l_history)
                dbg.append_step_over_libc(l_history)
                # FIXME:  This is inefficient.  In gdb, we should be
                #   doing 'n 2', 'n 4', 'n 8', etc., and be depending
                #   on gdb stopping at breakpoint.  But gdb doesn't always
                #   stop at breakpoint (e.g. at beginning of 'for' loop)
                while dbg.program_is_running() and \
                        not dbg.at_breakpoint():
                    l_history += \
                        [dbg._p.get_personality_cmd(freddebugger.fred_next_cmd())]
                    dbg.replay_history([l_history[-1]])
    # Gene - Am I using the next four lines correctly?
    dbg.current_checkpoint().set_history(l_history)
    dbg.do_restart()
    dbg.replay_history(l_history)
    dbg.update_state()
    fredutil.fred_debug("Reverse next finished.") def reverse_step(dbg, n=1):
    """Perform n 'reverse-step' commands."""
    while n > 0:
        n -= 1
        dbg.update_state()
        orig_state = dbg.state().copy()
        if dbg.branch.get_num_checkpoints() == 0:
            fredutil.fred_error("No checkpoints found for reverse-step.")
            return
        l_history = dbg.copy_current_checkpoint_history()
        while len(l_history)>0 and \
                not l_history[-1].is_step() and \
                not l_history[-1].is_next() and \
                not l_history[-1].is_continue():
            del l_history[-1]
        if len(l_history) == 0:
            break
        if l_history[-1].is_continue():
            fredutil.fred_debug("Last command continue. Expanding")
            # Since we last executed 'continue', we must be at a breakpoint.
            # Use that to expand the last 'continue' command until we
            #   reach the breakpoint.
            # FIXME:  This is inefficient.  In gdb, we should be
            #   doing 'n 2', 'n 4', 'n 8', etc., and be depending
            #   on gdb stopping at breakpoint.  But gdb doesn't always
            #   stop at breakpoint (e.g. at beginning of 'for' loop)
            del l_history[-1]
            dbg.do_restart(b_clear_history = True)
            dbg.replay_history(l_history)
            dbg.append_step_over_libc(l_history)
            while dbg.program_is_running() and not dbg.at_breakpoint():
                l_history += [dbg._p.get_personality_cmd(freddebugger.fred_next_cmd())]
                dbg.replay_history([l_history[-1]])
        fredutil.fred_debug("Done next doubling; starting search.")
        while l_history[-1].is_next():
            level = dbg.state().level()
            fredutil.fred_debug("Expanding next, level is %d" % level)
            # expand_next replaces last 'n' by ['s', 'n', ..., 's']
            #   while returning to current loc. Or returns [..., 'n/bkpt'].
            # After exiting this while loop, will delete 's' before returning.
            # dbg.state().level() can never increase under repeated 'n'
            # BUG:  Actually, 'n' can hit a breakpoint deeper in stack.
            testIfTooFar = lambda: dbg.state().level() <= level or \
                dbg.at_breakpoint()
            (l_history, n_min) = \
                binary_search.NEW_binary_search_expand_next(dbg, l_history,
                                                            testIfTooFar)
            # If not is_step(), it's because we hit at_breakpoint(): 'n/bkpt'.
            # First, search for correct expansion between n_min and currnt loc
            # If it fails, then will have 'n' at end.  Loop around to strip it
            if not l_history[-1].is_step():
                l_history = binary_search.NEW_binary_search_history(dbg,
                                                                    l_history,
                                                                    n_min,
                                                                    testIfTooFar)
        fredutil.fred_debug("Done reverse step.")
        fredutil.fred_assert(l_history[-1].is_step())
        del l_history[-1]
    # Gene - Am I using the next four lines correctly?
    dbg.current_checkpoint().set_history(l_history)
    dbg.do_restart()
    dbg.replay_history()
    dbg.update_state()
    fredutil.fred_debug("Reverse step finished.") def reverse_finish(dbg, n=1):
    """Perform n 'reverse-finish' commands."""
    if dbg.branch.get_num_checkpoints() == 0:
        fredutil.fred_error("No checkpoints found for reverse-finish.")
        return
    while n > 0:
        n -= 1
        dbg.update_state()
        orig_state = dbg.state().copy()
        l_history = dbg.copy_current_checkpoint_history()
        level = dbg.state().level()
	if level == 1:
            fredutil.fred_error(
             "reverse_finish: already at top level, can't go to higher level.")
        while dbg.state().level() >= level:
            # Trimming ignore commands. TODO: This could delete commands
            # with side effects like "p var++".
            while len(l_history)>0 and \
                    not l_history[-1].is_step() and \
                    not l_history[-1].is_next() and \
                    not l_history[-1].is_continue():
                del l_history[-1]
            if len(l_history) == 0:
                fredutil.fred_warning("Reverse-finish:" +
                                       "  can't reverse past last checkpoint")
            if l_history[-1].is_continue():
                # expand 'c' and continue to other cases
                fredutil.fred_error("This case not yet implemented.")
                # but see comment about BUG in binary_search_expand_continue
                testIfTooFar = lambda: dbg.at_breakpoint()
                (l_history, n_min) = \
                    binary_search.NEW_binary_search_expand_continue(dbg, l_history,
                                                                    testIfTooFar)
                # l_history ==
                #     l_history[0:n_min] + (len(l_history)-n_min)*['n']
                if len(l_history) - n_min > 1:
                    l_history = binary_search.NEW_binary_search_history(dbg, l_history,
                                                                        n_min, testIfTooFar)
                # execution stopped with n_min; l_history went one further
                continue
            elif l_history[-1].is_next() and dbg.at_breakpoint():
                # 'n' can hit a breakpoint deeper in stack.
                dbg.trim_n_cmds(l_history, 1)
                dbg.do_restart()
                dbg.replay_history(l_history)
                # This can be made more efficient.
                while dbg.state().level() < level-1:
                    dbg.append_step_over_libc(l_history)
                fredutil.fred_assert(dbg.state().level() == level-1)
            elif l_history[-1].is_next():
                # Search for time in past when level was one higher.
                # This can be optimized for fewer ckpt/restarts.
                while dbg.state().level() >= level and \
                        not dbg.at_breakpoint() and len(l_history)>0 and \
                        (l_history[-1].is_next() or l_history[-1].is_step()):
                    dbg.trim_n_cmds(l_history, 1)
                    dbg.do_restart(b_clear_history = True)
                    dbg.replay_history(l_history)
                fredutil.fred_assert(dbg.state().level() >= level-1)
            elif l_history[-1].is_step():
                dbg.trim_n_cmds(l_history, 1)
                dbg.do_restart(b_clear_history = True)
                dbg.replay_history(l_history)
                dbg.update_state()
    fredutil.fred_assert(dbg.state().level() == level-1 or
                         len(l_history) == 0)
    # Gene - Am I using the next four lines correctly?
    dbg.current_checkpoint().set_history(l_history)
    dbg.do_restart()
    dbg.replay_history()
    dbg.update_state()
    fredutil.fred_debug("Reverse finish finished.") def reverse_continue(dbg):
    """Perform 'reverse-continue' command. """
    dbg.update_state()
    orig_state = dbg.state().copy()
    n_to_restart = dbg.current_checkpoint().get_index()
    n_breakpoints_found = 0
    b_finished = False
    while True:
        if b_finished:
            break
        dbg.do_restart(n_to_restart)
        # Count the number of breakpoints encountered
        for cmd in dbg.current_checkpoint().get_history():
            dbg.execute_fred_command(cmd)
            if dbg.at_breakpoint():
                n_breakpoints_found += 1
        # If we were at a breakpoint, when rc was issued, we want to exclude
        # it when we re-execute.
        if n_breakpoints_found > 1 and dbg.at_breakpoint() or \
                n_breakpoints_found > 0 and not dbg.at_breakpoint():
            if dbg.at_breakpoint():
                n_breakpoints_found -= 1
            n_recount = 0
            dbg.do_restart(n_to_restart)
            for i in range(0,len(dbg.current_checkpoint().get_history())):
                cmd = dbg.current_checkpoint().get_history()[i]
                dbg.execute_fred_command(cmd)
                if dbg.at_breakpoint():
                    n_recount += 1
                if n_recount == n_breakpoints_found:
                    dbg.current_checkpoint().set_history(
                        dbg.current_checkpoint().get_history()[:i+1])
                    b_finished = True
                    break
        else:
            n_to_restart -= 1
            if n_to_restart < 0:
                fredutil.fred_error("Reverse-continue failed.")
                break
    dbg.update_state()
    fredutil.fred_debug("Reverse continue finished.") def undo(dbg, n=1):
    """Undo the last n commands."""
    b_restart = True
    if dbg.branch.get_num_checkpoints() == 0:
        fredutil.fred_error("No checkpoints found for undo.")
        return
    fredutil.fred_debug("Undoing %d command(s)." % n)
    while n > dbg.current_checkpoint().number_non_ignore_cmds():
        b_restart = False
        n -= dbg.current_checkpoint().number_non_ignore_cmds()
        # Back up to previous checkpoint
        if dbg.current_checkpoint().get_index() == 0:
            fredutil.fred_error("No undo possible (empty command history "
                                "and no previous checkpoints).")
            return
        else:
            dbg.do_restart_previous()
    if b_restart:
        dbg.do_restart()
    # Trim history by n non-ignore commands
    dbg.current_checkpoint().trim_non_ignore(n)
    dbg.replay_history()
    fredutil.fred_debug("Done undoing %d command(s)." % n)
from optparse import OptionParser
from fred import dmtcpmanager
from fred import fredmanager
from fred import fredio
from fred import freddebugger
from fred import fredutil
from fred.algorithms import reverse_watch
from fred.algorithms import reverse_next
from fred.algorithms import reverse_step
from fred.algorithms import reverse_finish
from fred.algorithms import reverse_continue
from fred.algorithms import undo
        from fred.personality.personalityGdb import PersonalityGdb
        from fred.personality.personalityPython import PersonalityPython
        from fred.personality.personalityPerl import PersonalityPerl
        from fred.personality.personalityMatlab import PersonalityMatlab
import pdb
import os
import shutil
import signal
import sys
                      help="Show all output from child processes.")
    parser.add_option("--fred-demo", dest="fred_demo", default=False,
                      action="store_true",
                      help="Enable FReD demo mode.")
    parser.add_option("--resume", dest="resume_dir",
                      help="Resume session from directory DIR containing "
                      "FReD support files: checkpoint images, "
                      "synchronization logs, etc.", metavar="DIR")
    (options, l_args) = parser.parse_args()
    # 'l_args' is the 'gdb ARGS ./a.out' list
    if len(l_args) == 0 and options.resume_dir == None:
        parser.print_help()
        fredutil.fred_quit(1)
    if options.source_script != None:
        # Source script executed from main_io_loop().
        g_source_script = options.source_script
    fredio.GB_FRED_DEMO = options.fred_demo
    gb_show_child_output = options.show_child_output
    if options.resume_dir != None:
        # Resume session from given directory.
        gs_resume_dir_path = options.resume_dir
    setup_environment_variables(str(options.dmtcp_port), options.debug)
    return l_args

def setup_debugger(s_debugger_name):
    """Initialize global ReversibleDebugger instance g_debugger."""
    global g_debugger, gs_resume_dir_path
    if s_debugger_name == "gdb":
        fredutil.fred_debug("Using gdb personality.")
        g_debugger = freddebugger.ReversibleDebugger(PersonalityGdb())
        del PersonalityGdb
    elif s_debugger_name == "python":
        fredutil.fred_debug("Using python personality.")
        g_debugger = freddebugger.ReversibleDebugger(PersonalityPython())
        del PersonalityPython
    elif s_debugger_name == "perl":
        fredutil.fred_debug("Using perl personality.")
        fredutil.set_env_var_if_unset("PERLDB_OPTS", "ornaments=ue,me")
        g_debugger = freddebugger.ReversibleDebugger(PersonalityPerl())
        del PersonalityPerl
    elif s_debugger_name.endswith("MATLAB"):
        fredutil.fred_debug("Using matlab personality.")
        g_debugger = freddebugger.ReversibleDebugger(PersonalityMatlab())
        del PersonalityMatlab
    else:
        fredutil.fred_fatal("Unimplemented debugger '%s'" % s_debugger_name)

def setup_environment_variables(s_dmtcp_port="7779", b_debug=False):
    """Set up the given environment variables.
    If any environment variables are already set, the existing values
    take precedence. This is so the user can set up environment
    variables for DMTCP/FReD in their .bashrc, for example."""
    fredutil.GB_DEBUG = b_debug
    fredutil.set_env_var_if_unset("DMTCP_PORT", s_dmtcp_port)
    fredutil.set_env_var_if_unset("DMTCP_TMPDIR", GS_DMTCP_TMPDIR)
    fredutil.set_env_var_if_unset("DMTCP_CHECKPOINT_DIR", GS_DMTCP_TMPDIR)
    fredutil.set_env_var_if_unset("DMTCP_GZIP", '0')
    fredutil.set_env_var_if_unset("DMTCP_QUIET", '2')

def setup_fredio(l_cmd, b_spawn_child=True):
    """Set up I/O handling."""
    global g_debugger, gb_show_child_output
    fredio.g_find_prompt_function  = g_debugger.get_find_prompt_function()
    fredio.g_print_prompt_function = g_debugger.get_prompt_string_function()
    fredio.gre_prompt              = g_debugger.get_prompt_regex()
    fredio.gls_needs_user_input    = g_debugger.get_ls_needs_input()
    fredio.gb_show_child_output    = gb_show_child_output
    fredio.setup(l_cmd, b_spawn_child)

def interactive_debugger_setup():
    """Perform any debugger setup that requires a debugger prompt."""
    global g_debugger, g_source_script
    if g_debugger.personality_name() == "gdb":
        # Special case for gdb: record name of executable.
        g_debugger._p.set_inferior_name()
        # Ignore SIGUSR2 (DMTCP checkpoint signal)
        g_debugger._p.execute_command("handle SIGUSR2 pass nostop")
    # If the user gave a source script file, execute it now.
    if g_source_script != None:
        source_from_file(g_source_script)

def fred_setup():
    """Perform any setup needed by FReD before entering an I/O loop."""
    global g_debugger, gs_resume_dir_path, GS_FRED_TMPDIR, gb_show_child_output
    # Parse command line args and set up environment.
    l_cmd = parse_program_args()
    # Set up the FReD global debugger
    setup_debugger(l_cmd[0])
    # Set up I/O handling
    # (only spawn if we are not resuming:)
    b_resume = gs_resume_dir_path != None
    if not b_resume:
        cleanup_fred_files()
        setup_fredio(l_cmd, True)
        g_debugger.create_master_branch()
    else:
        setup_fredio(l_cmd, False)
        dmtcpmanager.resume(GS_FRED_TMPDIR, gs_resume_dir_path)
        g_debugger.setup_from_resume()
        # XXX: Right now this is a hack to get the virtualized pid of the
        # inferior. We should make this more robust. Ideally we could have
        # support from DMTCP (via dmtcp_command) to tell us the inferior
        # virtualized pid.
        fredutil.fred_assert(g_debugger.personality_name() == "gdb")
        n_inf_pid = int(g_debugger.evaluate_expression("getpid()"))
        fredmanager.set_virtual_inferior_pid(n_inf_pid)
    g_debugger.set_real_debugger_pid(fredio.get_child_pid())

def fred_setup_as_module(l_cmd, s_dmtcp_port, b_debug, b_show_child_output):
    """Perform setup for FReD when being used as a module, return g_debugger.
    For example, fredtest.py uses FReD as a module."""
    global g_debugger, gb_show_child_output
    cleanup_fred_files()
    setup_environment_variables(s_dmtcp_port, b_debug)
    setup_debugger(l_cmd[0])
    gb_show_child_output = b_show_child_output
    setup_fredio(l_cmd, True)
    # Since modules won't use the main_io_loop, we perform the debugger setup
    # requiring a debugger prompt here.
    g_debugger.set_real_debugger_pid(fredio.get_child_pid())

    fredio.wait_for_prompt()