예제 #1
0
    def handleWhileLoop(self,
                        evalExpression,
                        code,
                        currentScope,
                        free,
                        methodHandles,
                        returnHandle=False,
                        returnedHandle=False):
        if returnedHandle == False:
            print "Error! No Returned Handle for While Loop!"
        scopecopy = dict(currentScope)

        toFree = []
        booleanCheckVar = self.queryBoolean(free)
        originalexp = str(evalExpression)
        evalExpression = nonsensehandling.exactParameters(evalExpression)
        isReturnStatement = False
        #  evaluateWithReturnPointer(self,line, rtnptr , cScopeVariables, freed, methodHandles)
        prelimCheckCode = self.evaluateWithReturnPointer(
            evalExpression, booleanCheckVar, currentScope, free, methodHandles)
        ifstatement = "if(%s && !%s)" % (booleanCheckVar, returnedHandle)
        nextstuff = "do;"
        clevel = 1 if '{' in originalexp else 0
        toInvokeOn = []
        while (len(code) > 0 and clevel >= 0):
            popped = code.pop(0)

            if '{' in popped:
                clevel += 1
            elif '}' in popped:
                clevel -= 1
            if clevel != 0:
                toInvokeOn.append(popped)
            else:
                break
        beefWhile, potentialReturn = self.invoke(toInvokeOn,
                                                 currentScope,
                                                 free,
                                                 methodHandles,
                                                 returnHandle=returnHandle,
                                                 returnedHandle=returnedHandle)
        isReturnStatement |= potentialReturn
        repeatCheckCode = self.evaluateWithReturnPointer(
            evalExpression, booleanCheckVar, currentScope, free, methodHandles)

        lastStuff = "while(%s && !%s);" % (booleanCheckVar, returnedHandle)

        self.deIntersectFreeMemory(scopecopy, currentScope, free)

        # dont free that memory otherwise we wil have problemos bc counter / flag corruption

        return prelimCheckCode + [ifstatement, nextstuff
                                  ] + beefWhile + repeatCheckCode + [
                                      lastStuff, 'endif;'
                                  ], code, isReturnStatement
예제 #2
0
    def handleForLoop(self,
                      evalExpression,
                      code,
                      currentScope,
                      free,
                      methodHandles,
                      returnHandle=False,
                      returnedHandle=False):
        # eval expression is in the form for(onestatement;checkcase;iterate){
        ''' extremely beta rn '''
        scopecopy = dict(currentScope)
        toFree = []
        toWrite = []
        orig = str(evalExpression)
        booleanCheckVar = self.queryBoolean(free)
        evalExpression = nonsensehandling.exactParameters(evalExpression)
        isReturnStatement = False

        line = ''
        expression = '1'
        iter = ''

        try:
            line, expression, iter = evalExpression.split(';')
        except:
            self.announceError(
                'You do not have exactly 3 statements in your for expression\n%s'
                % (evalExpression))
        # establish it
        left, right = line.split("=")
        left = left.replace(" ", "")
        iterval = self.queryVariable(
            free) if not left in currentScope else currentScope[left]
        currentScope[left] = iterval
        prelimcode = self.evaluateWithReturnPointer(right, iterval,
                                                    currentScope, free,
                                                    methodHandles)

        # implement the whole statement itself.\

        prelimCheckCode = self.evaluateWithReturnPointer(
            expression, booleanCheckVar, currentScope, free, methodHandles)
        ifstatement = "if(%s && !%s)" % (booleanCheckVar, returnedHandle)
        nextstuff = "do;"
        clevel = 1 if '{' in orig else 0
        toInvokeOn = []
        while (len(code) > 0 and clevel >= 0):
            popped = code.pop(0)
            if '{' in popped:

                clevel += 1
            elif '}' in popped:
                clevel -= 1
            if clevel != 0:
                toInvokeOn.append(popped)
            else:
                break
        beefWhile, potentialReturn = self.invoke(toInvokeOn,
                                                 currentScope,
                                                 free,
                                                 methodHandles,
                                                 returnHandle=returnHandle,
                                                 returnedHandle=returnedHandle)
        isReturnStatement |= potentialReturn
        #ignore the return bc it litearly will make 0 impact.
        left, right = iter.split("=")
        left = left.replace(" ", "")

        iterval = self.announceError(
            "Cannot Create a new variable in incrementor portion\nof for loop.\n%s"
            % (evalExpression)
        ) if not left in currentScope else currentScope[left]
        currentScope[left] = iterval
        incrementorcode = self.evaluateWithReturnPointer(
            right, iterval, currentScope, free, methodHandles)
        repeatCheckCode = self.evaluateWithReturnPointer(
            expression, booleanCheckVar, currentScope, free, methodHandles)

        self.deIntersectFreeMemory(scopecopy, currentScope, free)

        lastStuff = "while(%s && !%s);" % (booleanCheckVar, returnedHandle)
        return prelimcode + prelimCheckCode + [
            ifstatement, nextstuff
        ] + beefWhile + incrementorcode + repeatCheckCode + [
            lastStuff, 'endif;'
        ], code, isReturnStatement
예제 #3
0
    def handleIfStatement(self,
                          evalExpression,
                          code,
                          currentScope,
                          free,
                          methodHandles,
                          returnHandle=False,
                          returnedHandle=False):
        scopecopy = dict(currentScope)
        toFree = []
        toWrite = []
        original = evalExpression
        booleanCheckVar = self.queryBoolean(free)
        evalExpression = nonsensehandling.exactParameters(evalExpression)
        isReturnStatement = False
        prelimCheckCode = self.evaluateWithReturnPointer(
            evalExpression, booleanCheckVar, currentScope, free, methodHandles)

        clevel = 1 if '{' in original else 0
        toInvokeOnIf = []
        while (len(code) > 0 and clevel >= 0):
            popped = code.pop(0)

            if '{' in popped:
                clevel += 1
            elif '}' in popped:
                clevel -= 1
            #print popped,clevel
            if clevel > 0:
                toInvokeOnIf.append(popped)
            else:
                break
        ifBlock, potentialReturn = self.invoke(toInvokeOnIf,
                                               currentScope,
                                               free,
                                               methodHandles,
                                               returnHandle=returnHandle,
                                               returnedHandle=returnedHandle)
        isReturnStatement |= potentialReturn
        if len(code) == 0 or not 'else' in code[0]:
            return prelimCheckCode + [
                'if(%s && !%s)' % (booleanCheckVar, returnedHandle)
            ] + ifBlock + ['endif;'], code, isReturnStatement

        clevel = 1 if '{' in code.pop(0) else 0
        toInvokeOnElse = []
        while (len(code) > 0 and clevel >= 0):
            popped = code.pop(0)
            if '{' in popped:
                clevel += 1
            elif '}' in popped:
                clevel -= 1
            if clevel != 0:
                toInvokeOnElse.append(popped)
            else:
                break
        elseBlock, potentialReturn = self.invoke(toInvokeOnElse,
                                                 currentScope,
                                                 free,
                                                 methodHandles,
                                                 returnHandle=returnHandle,
                                                 returnedHandle=returnedHandle)
        isReturnStatement |= potentialReturn
        #print "if statement", potentialReturn
        self.deIntersectFreeMemory(scopecopy, currentScope, free)

        return prelimCheckCode + [
            'if(%s && !%s)' % (booleanCheckVar, returnedHandle)
        ] + ifBlock + ['else'] + elseBlock + ['endif;'
                                              ], code, isReturnStatement
예제 #4
0
    def __init__(self, inputCode, flags=[], dRetF=lambda x: None):
        # code stuff
        self.lines = inputCode
        self.functions = {}
        self.value = 0
        #print self.lines
        self.report = dRetF
        self.collectiveVariables = {}  # variables from other libraries.
        self.isImported = set([])
        while len(self.lines) > 0:
            nextLine = nonsensehandling.rmvGarbage(self.lines.pop(0))
            #print nextLine
            if len(nextLine) == 0:
                continue
            elif nextLine[0] >= 'A' and nextLine[0] <= 'Z':
                #global variable
                collectiveVariables[nextLine.replace(' ',
                                                     '')] = AVAILIBLE.pop(0)
            elif nextLine[:5] == "using":
                # need to import a library
                # in the form using (libname,local/online,version) ex: 'using(hypixelcraft,local,*)'
                para = nonsensehandling.exactParameters(nextLine).split(",")
                target_textfile = LOCALLIBRARIES
                if para[2] == "*":
                    target_textfile = target_textfile + para[0] + "-latest.txt"
                else:
                    target_textfile = target_textfile + para[
                        0] + "-v%s.txt" % (str(para[2]))
                print "[*]Looking for ", target_textfile
                with open(target_textfile, "r") as fileHandle:
                    CODE = fileHandle.read().replace('\r', '').replace(
                        '\t', '').split("\n")
                    CODE = map(nonsensehandling.cleanFront, CODE)
                    fileHandle.close()
                tempeditor = ProgramEditor(CODE)
                for qPro in tempeditor.functions:
                    if True:
                        print "Importing Function: %s/%s" % (para[0], qPro)
                        self.functions[qPro] = tempeditor.functions[qPro]
                        self.isImported.add(qPro)
                for cVar in tempeditor.collectiveVariables:
                    print "Importing Variable: %s/%s" % (para[0], qPro)
                    self.collectiveVariables[
                        cVar] = tempeditor.collectiveVariables[cVar]

            elif nextLine[:4] == 'func' or nextLine[:3] == 'def':
                functionProtoType = nonsensehandling.removeWord(nextLine)
                if ("{" in functionProtoType):
                    functionProtoType = functionProtoType[:functionProtoType.
                                                          find(
                                                              '{'
                                                          )]  # snip it there.
                if (self.lines == []):
                    print "got an empty defintion??"
                    return  # they forgot like alot xd
                functionBody = []
                counter = 1 if '{' in nextLine else 0
                if '{' in self.lines[0] and counter == 0:
                    counter = 1
                    self.lines[0] = self.lines[0][self.lines[0].find('{') + 1:]
                    if len(self.lines[0].replace(' ', '')) == 0:
                        self.lines.pop(0)

                while (len(self.lines) > 0):
                    nextLine = nonsensehandling.rmvGarbage(self.lines.pop(0))
                    #print "inf",nextLine,counter
                    if '{' in nextLine:
                        counter += 1
                    elif '}' in nextLine:
                        counter -= 1
                    if counter > 0:
                        functionBody.append(
                            nonsensehandling.cleanComments(nextLine))
                    if counter == 0:
                        break
                if (counter != 0):  # Failed to close the function
                    print "Failed to close a function.  Crashing"
                    return

                resultingFunction = LooseFunction(functionProtoType,
                                                  functionBody,
                                                  self,
                                                  debugStreamFunction=dRetF)
                self.functions[resultingFunction.getName()] = resultingFunction
                self.value = min(resultingFunction.lint(), self.value)
예제 #5
0
    def evaluateWithReturnPointer(self, line, rtnptr, cScopeVariables, freed,
                                  methodHandles):  # marped

        line = nonsensehandling.cleanFront(line)
        self.report({
            'name': 'eval-rptr',
            'variables': cScopeVariables,
            'freedSize': len(freed),
            'numF': len(methodHandles.keys())
        })
        #print "\"%s\""%(line)
        #print "Interpretting line with return pointer: %s, variables: %s free variables: %s"%(rtnptr,cScopeVariables,freed)
        # returns a handle
        # k(a - q(b)) + c
        # litearly just translate this thing.
        tokens = [""]
        queue = list(line)
        cLevel = 0
        while len(queue) > 0:
            nextC = queue.pop(0)
            if nextC in "*-+/%" and cLevel == 0:
                tokens.append(nextC)
                tokens.append("")
            elif (nextC in ['<', '>', '=']) and cLevel == 0:
                if queue[0] == '=':
                    tokens.append(nextC + '=')
                    queue.pop(0)
                else:
                    tokens.append(nextC)
                tokens.append('')
            else:
                if nextC == 'a' and queue[:3] == ['n', 'd', ' '
                                                  ] and cLevel == 0:
                    tokens.append('and')
                    tokens.append('')
                    queue = queue[3:]
                elif nextC == 'o' and queue[:2] == ['r', ' '] and cLevel == 0:
                    tokens.append('or')
                    tokens.append('')
                    queue = queue[2:]
                elif nextC == '&' and queue[:1] == ['&'] and cLevel == 0:
                    tokens.append('&&')
                    tokens.append('')
                    queue = queue[1:]
                elif nextC == '|' and queue[:1] == ['|'] and cLevel == 0:
                    tokens.append('||')
                    tokens.append('')
                    queue = queue[1:]
                elif nextC == '!' and queue[:1] == ['='] and cLevel == 0:
                    tokens.append('!=')
                    tokens.append('')
                    queue = queue[1:]
                else:
                    if nextC == '(':
                        cLevel += 1
                    elif nextC == ')':
                        cLevel -= 1
                    tokens[-1] = tokens[-1] + nextC

        #print "[>]Need to Evaluate", tokens
        for i in range(0, len(tokens)):

            tokens[i] = tokens[i].replace("\t", "")
            while ('  ' in tokens[i]):
                tokens[i] = tokens[i].replace('  ', ' ')
        while tokens[-1] == '':
            tokens.pop()
        toReliquish = []  # pointers to untrash when done
        codebefore = []
        aggregate = []
        for token in tokens:
            if token in "*-+/%":
                aggregate.append(token)
                continue
            if token in ["<", ">", "<=", ">=", "==", "&&", "||", "!="]:
                aggregate.append(token)
                continue
            if token == "and":
                aggregate.append("&&")
                continue
            if token == "or":
                aggregate.append('||')
                continue
            #print token,line
            if '(' in token:
                newpointer = ""

                todo = map(
                    nonsensehandling.rmvGarbage,
                    self.extractOuterParameters(
                        nonsensehandling.exactParameters(token)))

                parameters = []

                optional_pointers = []

                isMandatory = True
                target_opt = ""
                for todo_part in todo:
                    isMandatory = True
                    invokative = todo_part.find('(')
                    declarative = todo_part.find('=')

                    if len(todo_part) == 0:
                        continue
                    elif todo_part[
                            0] == '&' and not nonsensehandling.intersects(
                                "*+-/%", todo_part[1:]
                            ):  # we've got a pointer on the loose.
                        if not todo_part[1:] in cScopeVariables:
                            self.announceError(
                                "[-]invalid base for pointer : " +
                                str(todo_part[1:]))
                        else:
                            newpointer = cScopeVariables[todo_part[1:]]
                    elif (invokative != -1 and '='
                          in todo_part[:invokative]) or (invokative == -1
                                                         and declarative >= 0):
                        # optional parameter loading . . .
                        isMandatory = False
                        target_opt = todo_part[:declarative].replace(" ", "")

                        if len(freed) == 0:
                            #print "[!]oops! we need another pointer.(function input pointer)"
                            newpointer = self.generateCoolName()
                        else:
                            newpointer = freed.pop(0)
                        evaluationcode = self.evaluateWithReturnPointer(
                            todo_part[declarative + 1:], newpointer,
                            cScopeVariables, freed, methodHandles)
                        codebefore.extend(evaluationcode)
                    else:
                        if len(freed) == 0:
                            newpointer = self.generateCoolName()
                        else:
                            newpointer = freed.pop(0)

                        toReliquish.append(newpointer)
                        v = self.evaluateWithReturnPointer(
                            todo_part, newpointer, cScopeVariables, freed,
                            methodHandles)
                        codebefore.extend(v)

                    if isMandatory:
                        parameters.append(newpointer)
                    else:
                        optional_pointers.append([target_opt, newpointer])

                vpointer = ""
                if len(tokens) == 1:
                    vpointer = rtnptr  # checkmate
                elif len(freed) == 0:
                    vpointer = self.generateCoolName()
                    toReliquish.append(vpointer)
                else:
                    vpointer = freed.pop(0)
                    toReliquish.append(vpointer)

                targetinvoke = nonsensehandling.getFunctionName(token)
                self.report({
                    'name': 'eval-tokencheck',
                    'params': list(parameters),
                    'target-hash': hash(targetinvoke.replace(' ', ''))
                })

                #codebefore.append("compupte "+targetinvoke+"(%s)"%(','.join(parameters))+ " to contribute to "+ rtnptr+" via "+vpointer )
                if targetinvoke.replace(' ', '') != '':
                    targetinvoke = nonsensehandling.cleanFront(
                        targetinvoke) + "|" + str(len(parameters))
                    if not targetinvoke in methodHandles:
                        self.announceError('[-]Unable to find func: ' +
                                           targetinvoke)

                    executioncode = methodHandles[targetinvoke].methodinvoke(
                        parameters,
                        freed,
                        methodHandles,
                        returnHandle=vpointer,
                        optionalArgs=optional_pointers)
                    codebefore.extend(executioncode)
                    aggregate.append(vpointer)
                else:
                    aggregate.append(parameters[0])

            elif '&' == token.replace(' ', "")[0]:
                tfrz = token.replace(' ', "")
                if not tfrz[1:] in cScopeVariables:
                    self.announceError("[-]invalid base for pointer : " +
                                       str(tfrz[1:]))
                else:
                    aggregate.append(cScopeVariables[tfrz[1:]])
            elif token.replace(' ', "") in cScopeVariables:
                #print "[*]Got a pre-exist reference to: %s"%(token)
                aggregate.append(cScopeVariables[token.replace(' ', "")])
            else:
                try:
                    aggregate.append(str(int(token.replace(' ', ""))))
                except:
                    self.announceError(
                        "[-]error, no reference to: `%s`\n Line: `%s`\nCurrent Variables: %s"
                        % (token, line, cScopeVariables))

        if (len(aggregate) == 0
                or (rtnptr != None and rtnptr != aggregate[-1])):
            aggregate = [rtnptr + " ="
                         ] + aggregate  #+ ["-- evaluating %s"%(line)]
            codebefore.append(' '.join(aggregate))
        freed.extend(toReliquish)
        return codebefore
예제 #6
0
    def evaluateWithReturnPointer(self, line, rtnptr, cScopeVariables, freed,
                                  methodHandles):  # marped
        #print "Interpretting line with return pointer: %s, variables: %s free variables: %s"%(rtnptr,cScopeVariables,freed)
        # returns a handle
        # k(a - q(b)) + c
        # litearly just translate this thing.
        tokens = [""]
        queue = list(line)
        cLevel = 0
        while len(queue) > 0:
            nextC = queue.pop(0)
            if nextC in "*-+/%" and cLevel == 0:
                tokens.append(nextC)
                tokens.append("")
            elif (nextC in ['<', '>', '=']) and cLevel == 0:
                if queue[0] == '=':
                    tokens.append(nextC + '=')
                    queue.pop(0)
                else:
                    tokens.append(nextC)
                tokens.append('')
            else:
                if nextC == 'a' and queue[:3] == ['n', 'd', ' ']:
                    tokens.append('and')
                    tokens.append('')
                    queue = queue[3:]
                elif nextC == 'o' and queue[:2] == ['r', ' ']:
                    tokens.append('or')
                    tokens.append('')
                    queue = queue[2:]
                elif nextC == '&' and queue[:1] == ['&']:
                    tokens.append('&&')
                    tokens.append('')
                    queue = queue[1:]
                elif nextC == '|' and queue[:1] == ['|']:
                    tokens.append('||')
                    tokens.append('')
                    queue = queue[1:]
                else:
                    if nextC == '(':
                        cLevel += 1
                    elif nextC == ')':
                        cLevel -= 1
                    tokens[-1] = tokens[-1] + nextC

        #print "[>]Need to Evaluate", tokens
        tokens = map(lambda x: x.replace(" ", "").replace("\t", ""), tokens)
        toReliquish = []  # pointers to untrash when done
        codebefore = []
        aggregate = []
        for token in tokens:
            if token in "*-+/%":
                aggregate.append(token)
                continue
            if token in ["<", ">", "<=", ">=", "==", "&&", "||"]:
                aggregate.append(token)
                continue
            if token == "and":
                aggregate.append("&&")
                continue
            if token == "or":
                aggregate.append('||')
                continue
            if '(' in token:
                newpointer = ""

                todo = self.extractOuterParameters(
                    nonsensehandling.exactParameters(token))
                #print "params",todo
                parameters = []
                for todo_part in todo:
                    if todo_part[
                            0] == '&':  # we've got a pointer on the loose.
                        if not todo_part[1:] in cScopeVariables:
                            self.announceError(
                                "[-]invalid base for pointer : ", todopart[1:])
                        else:
                            newpointer = cScopeVariables[todo_part[1:]]
                    else:
                        if len(freed) == 0:
                            #print "[!]oops! we need another pointer.(function input pointer)"
                            newpointer = self.generateCoolName()
                        else:
                            newpointer = freed.pop(0)
                        #print "[*]obtained a pointer for method call ", nonsensehandling.getFunctionName(token), newpointer
                        toReliquish.append(newpointer)
                        v = self.evaluateWithReturnPointer(
                            todo_part, newpointer, cScopeVariables, freed,
                            methodHandles)
                        codebefore.extend(v)
                    parameters.append(newpointer)

                vpointer = ""
                if len(tokens) == 1:
                    vpointer = rtnptr  # checkmate
                elif len(freed) == 0:
                    #print "[!]oops! we need another pointer.(function value pointer)"
                    vpointer = self.generateCoolName()
                    toReliquish.append(vpointer)
                else:
                    vpointer = freed.pop(0)
                    toReliquish.append(vpointer)

                targetinvoke = nonsensehandling.getFunctionName(token)
                #codebefore.append("compupte "+targetinvoke+"(%s)"%(','.join(parameters))+ " to contribute to "+ rtnptr+" via "+vpointer )
                if not targetinvoke in methodHandles:
                    self.announceError('[-]Unable to find func: ' +
                                       targetinvoke)

                executioncode = methodHandles[targetinvoke].methodinvoke(
                    parameters, freed, methodHandles, returnHandle=vpointer)
                codebefore.extend(executioncode)
                aggregate.append(vpointer)
            elif token in cScopeVariables:
                #print "[*]Got a pre-exist reference to: %s"%(token)
                aggregate.append(cScopeVariables[token])
            else:
                try:
                    aggregate.append(str(int(token)))
                except:
                    self.announceError(
                        "[-]error, no reference to: `%s`\n Line: `%s`\nCurrent Variables: %s"
                        % (token, line, cScopeVariables))

        if (rtnptr != None and rtnptr != aggregate[-1]):
            aggregate = [rtnptr + " ="
                         ] + aggregate  #+ ["-- evaluating %s"%(line)]

            codebefore.append(' '.join(aggregate))
        freed.extend(toReliquish)
        return codebefore