ocarina_common_tools.py 4.92 KB
Newer Older
1 2
#! /usr/bin/python
'''
3
:mod:`ocarina_common_tools`
4 5 6

.. moduleauthor:: Jerome Hugues, Arnaud Schach

7
Tools used by Python binding to the Ocarina AADL processor
8 9 10 11 12 13 14 15 16 17 18 19
'''

################################################################################

try:
    import sys
    import StringIO
    from contextlib import contextmanager
    import ctypes
    import io
    import os
    import tempfile
20 21
    import platform

22 23 24
except ImportError:
    pass

25 26
################################################################################
def runOcarinaFunction (f, *parameters):
27 28 29 30
    '''Wrapper to run an Ada function provided by Ocarina. It performs all
       the redirections
    '''

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    info = io.BytesIO()
    error = io.BytesIO()
    raisedError = []
    res = ''
    with std_redirector(info,error):
        try:
            res = f (*parameters)
        except:
            raisedError.append(getErrorMessage())
    stderrMsg = sortStderrMessages(error.getvalue().decode('utf-8'))
    if stderrMsg[1]!=[]:
        raisedError.append(stderrMsg[1])
    return [ res , info.getvalue().decode('utf-8'), stderrMsg[0] ,
        raisedError ]

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
################################################################################

def getErrorMessage ():
    '''Get the error message from the raised error
    '''
    keep = False
    msg = ''
    for line in StringIO.StringIO(sys.exc_info()[1]):
        if line.lower().startswith('message:'):
            keep = True
        if line.lower().startswith('call stack traceback locations:'):
            break
        if keep:
            msg = msg + line[9:] + '\n'
    return msg

################################################################################

def sortStderrMessages (messages):
    '''Get the error and warning messages from the stderr

    :param messages: the messages written on stderr
68

69
    return a pair of the form [ warnings , errors ]
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
    msgType = 'error'
    warningMsg = ''
    errorMsg = ''
    warningMsgList = []
    errorMsgList = []
    for line in StringIO.StringIO(messages):
        if line.lower().startswith('error:'):
            if warningMsg.strip()!='':
                warningMsgList.append(warningMsg.strip())
                warningMsg = ''
            if errorMsg.strip()!='':
                errorMsgList.append(errorMsg.strip())
                errorMsg = ''
            msgType = 'error'
            errorMsg = warningMsg + line[7:] + '\n'
        elif line.lower().startswith('warning:'):
            if warningMsg.strip()!='':
                warningMsgList.append(warningMsg.strip())
                warningMsg = ''
            if errorMsg.strip()!='':
                errorMsgList.append(errorMsg.strip())
                errorMsg = ''
            msgType = 'warning'
            warningMsg = warningMsg + line[9:] + '\n'
        else:
            if msgType == 'warning':
                warningMsg = warningMsg + line + '\n'
            elif msgType == 'error':
                errorMsg = errorMsg + line + '\n'
    if warningMsg.strip()!='':
        warningMsgList.append(warningMsg.strip())
    if errorMsg.strip()!='':
        errorMsgList.append(errorMsg.strip())
    return [ warningMsgList , errorMsgList ]

################################################################################

@contextmanager
def std_redirector(stdoutStream, stderrStream):

    libc = ctypes.CDLL(None)
114 115 116 117 118 119 120 121 122 123 124

    # Note: Darwin (OS X) does ont export stdout/stderr as symbols,
    # but exports __stdoutp/__stderrp instead

    if platform.system () == "Darwin":
        c_stdout = ctypes.c_void_p.in_dll(libc, '__stdoutp')
        c_stderr = ctypes.c_void_p.in_dll(libc, '__stderrp')
    else:
        c_stdout = ctypes.c_void_p.in_dll(libc, 'stdout')
        c_stderr = ctypes.c_void_p.in_dll(libc, 'stderr')

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
    original_stdout_fd = sys.stdout.fileno()
    original_stderr_fd = sys.stderr.fileno()

    def _redirect_stdout(to_fd):
        libc.fflush(c_stdout)
        sys.stdout.close()
        os.dup2(to_fd, original_stdout_fd)
        sys.stdout = os.fdopen(original_stdout_fd, 'wb')

    def _redirect_stderr(to_fd):
        libc.fflush(c_stderr)
        sys.stderr.close()
        os.dup2(to_fd, original_stderr_fd)
        sys.stderr = os.fdopen(original_stderr_fd, 'wb')

    saved_stdout_fd = os.dup(original_stdout_fd)
    saved_stderr_fd = os.dup(original_stderr_fd)
    try:
        stdoutfile = tempfile.TemporaryFile(mode='w+b')
        _redirect_stdout(stdoutfile.fileno())
        stderrfile = tempfile.TemporaryFile(mode='w+b')
        _redirect_stderr(stderrfile.fileno())
        yield
        _redirect_stdout(saved_stdout_fd)
        _redirect_stderr(saved_stderr_fd)
150

151 152 153 154 155 156 157 158 159 160 161
        stdoutfile.flush()
        stdoutfile.seek(0, io.SEEK_SET)
        stdoutStream.write(stdoutfile.read())
        stderrfile.flush()
        stderrfile.seek(0, io.SEEK_SET)
        stderrStream.write(stderrfile.read())
    finally:
        stdoutfile.close()
        os.close(saved_stdout_fd)
        stderrfile.close()
        os.close(saved_stderr_fd)