Find current function call in the byte code.
426542
def _find_current_fn_call(co, lasti):
  """"""
  qj._DEBUG_QJ and qj.LOG_FN('co = {}'.format(co))

  if sys.version_info[0] < 3:
    stack = _build_instruction_stack(co, lasti)
  else:
    stack = _build_instruction_stack3(co, lasti)

  source_lines, source_offset = inspect.getsourcelines(co)
  source_lines = [l.strip() for l in source_lines]

  # Apply stack effects backwards until we arrive at the stack entries for a complete function call
  fn_stack = _collect_pops(stack[:-1], stack[-1].stack_depth, [], 0)

  if not fn_stack and stack[-1].stack_depth == 0:
    # The function call took 0 arguments, so return early with a special string.
    return '<empty log>'

  qj._DEBUG_QJ and qj.LOG_FN('collected fn_stack:\n%s\n\n' % '\n'.join(str(se) for se in fn_stack))

  # Prepare to annotate the stack with extra symbols, and filter out MAKE_FUNCTION and MAKE_CLOSURE calls, which are no longer needed.
  annotate_stack = [se for se in fn_stack if not se.opname.startswith('MAKE_')]
  annotate_stack.reverse()
  _annotate_fn_args(annotate_stack, stack[-1].opname, stack[-1].oparg, -1, False)

  qj._DEBUG_QJ and qj.LOG_FN('annotated fn_stack:\n%s\n\n' % '\n'.join(str(se) for se in fn_stack))

  # Find the range of lines to search over.
  min_l = stack[-1].curr_l
  max_l = stack[0].curr_l
  for se in fn_stack:
    min_l = min(min_l, se.curr_l)
    max_l = max(max_l, se.curr_l)

  qj._DEBUG_QJ and qj.LOG_FN('source lines range: %d -> %d (indices: %d, %d)' % (min_l, max_l, min_l - source_offset, max_l - source_offset + 1))
  source_chunk = ' '.join(
      [l for l in source_lines[min_l - source_offset:max_l - source_offset + 1] if l and not l.startswith('#')])

  qj._DEBUG_QJ and qj.LOG_FN('source_chunk: %r' % source_chunk)

  # Build up all of the tokens for the function call.
  tokens = []
  for se in fn_stack:
    opname = se.opname
    for oparg_repr in se.oparg_repr[::-1]:
      # Clean up the tokens
      if not oparg_repr:
        continue
      oparg_repr = re.escape(oparg_repr.replace('\n', '\\n'))
      tokens.append(oparg_repr)

  tokens.reverse()
  qj._DEBUG_QJ and qj.LOG_FN('extracted tokens: {}'.format(tokens))
  if qj._DEBUG_QJ:
    assert tokens

  # Add tokens for the function call we're extracting.
  tokens = ['\\('] + tokens + ['\\)']

  reg = '\b*?.*?\b*?'.join(tokens)
  qj._DEBUG_QJ and qj.LOG_FN(reg)

  # Search for the function call using the full set of tokens.
  # Expand the search with source lines after the current set if we don't find a match.
  shortest_match = None
  match_attempts = 0
  max_match_attempts = 10
  while not shortest_match and match_attempts < max_match_attempts:
    (shortest_match, _, _) = (
        _find_earliest_shortest_match(source_chunk, reg, 0, len(source_chunk), num_attempts=10))
    if not shortest_match:
      match_attempts += 1

      min_l -= 1
      prev_line = ''
      while not prev_line and min_l - source_offset >= 0 and min_l - source_offset < len(source_lines):
        prev_line = source_lines[min_l - source_offset]
        if prev_line.startswith('#'):
          prev_line = ''
        if not prev_line:
          min_l -= 1
      prev_line += ' ' if prev_line else ''
      source_chunk = prev_line + source_chunk

      max_l += 1
      next_line = ''
      while not next_line and max_l - source_offset >= 0 and max_l - source_offset < len(source_lines):
        next_line = source_lines[max_l - source_offset]
        if next_line.startswith('#'):
          next_line = ''
        if not next_line:
          max_l += 1
      next_line = (' ' if next_line else '') + next_line
      source_chunk += next_line

  # Return the string for the function call
  if qj._DEBUG_QJ:
    assert shortest_match
  if shortest_match is not None:
    match = shortest_match.group(0)
    if qj._DEBUG_QJ:
      assert match.startswith('(') and match.endswith(')')
    # Do some parentheses cleanup.
    if match.startswith('('):
      match = match[1:]
    lparens = match.count('(')
    rparens = match.count(')')
    if lparens > rparens:
      match += ')' * (lparens - rparens)
    elif lparens < rparens:
      rparens_to_remove = rparens - lparens
      while len(match) and match[-1] == ')' and rparens_to_remove > 0:
        match = match[:-1]
        rparens_to_remove -= 1
    match = match.strip()
    return match
  else:
    return ''
1172583
def _scan_function_prologues(self, traced_address, function_exits, initial_state):
        

        # Precompile all regexes
        regexes = set()
        for ins_regex in self.project.arch.function_prologs:
            r = re.compile(ins_regex)
            regexes.add(r)

        # TODO: Make sure self._start is aligned

        # Construct the binary blob first

        for start_, bytes_ in self.project.loader.main_object.memory.backers():
            for regex in regexes:
                # Match them!
                for mo in regex.finditer(bytes):
                    position = mo.start() + start_
                    if position % self.project.arch.instruction_alignment == 0:
                        if position not in traced_address:
                            percentage = self._seg_list.occupied_size * 100.0 / (self._valid_memory_region_size)
                            l.info("Scanning %xh, progress %0.04f%%", position, percentage)

                            self._unassured_functions.add(position)

                            self._scan_code(traced_address, function_exits, initial_state, position)
                        else:
                            l.info("Skipping %xh", position)
491493
def visit_Call(self, nodeCall):
        
        super(PatternFinder, self).generic_visit(nodeCall)
        # Capture assignment like 'f = getattr(...)'.
        if hasattr(nodeCall.func, "func"):
            # In this case, the statement should be
            # 'f = getattr(...)()'.
            nodeCall = nodeCall.func
        # Make sure the function's name is 'getattr'.
        if not hasattr(nodeCall.func, "id"):
            return
        if nodeCall.func.id != "getattr":
            return

        # Capture 'f = getattr(foo, "bar_%s" % baz )' or
        # 'f = getattr(foo, "bar_" + baz )'.
        nodeArgument = nodeCall.args[1]
        if not isinstance(nodeArgument, ast.BinOp):
            return
        operation = nodeArgument.op
        if type(operation) not in [ast.Mod, ast.Add]:
            return
        nodePattern = nodeArgument.left
        if not isinstance(nodePattern, ast.Str):
            return
        pattern = nodePattern.s
        if not ((type(operation) == ast.Add and pattern.endswith("_")) or
                (pattern.count("%s") == 1 and pattern.endswith("_%s"))):
            return
        pattern = pattern.replace("%s", "")
        if pattern[:1].isalpha() and not pattern[:1].islower():
            self.patternsClass.add(pattern)
        else:
            self.patternsFunc.add(pattern)
723971
def func_runtime(callback):
    
    now = time.time()
    print('%s - start: %f' % (callback, now))
    callback()
    now = time.time() - now
    print('%s - spent: %f Second' % (callback, now))
601248
def _find_global(self, module, func):
        """"""
        if module == __name__:
            if func == '_unpickle_call_error' or func == 'CallError':
                return _unpickle_call_error
            elif func == '_unpickle_sender':
                return self._unpickle_sender
            elif func == '_unpickle_context':
                return self._unpickle_context
            elif func == 'Blob':
                return Blob
            elif func == 'Secret':
                return Secret
            elif func == 'Kwargs':
                return Kwargs
        elif module == '_codecs' and func == 'encode':
            return self._unpickle_bytes
        elif module == '__builtin__' and func == 'bytes':
            return BytesType
        raise StreamError('cannot unpickle %r/%r', module, func)
1228618
def callable(self) -> Optional[str]:
        """"""
        if self.current_trace_frame_index != -1:
            return self._get_callable_from_trace_tuple(
                self.trace_tuples[self.current_trace_frame_index]
            )[0]
        return None
799817
def bytearray_check(*args, func=None):
    """"""
    func = func or inspect.stack()[2][3]
    for var in args:
        if not isinstance(var, (bytearray, collections.abc.ByteString, collections.abc.MutableSequence)):
            name = type(var).__name__
            raise BytearrayError(
                f'Function {func} expected bytearray, {name} got instead.')
279138
def function_call_action(self, text, loc, fun):
        """"""
        exshared.setpos(loc, text)
        if DEBUG > 0:
            print("FUN_CALL:",fun)
            if DEBUG == 2: self.symtab.display()
            if DEBUG > 2: return
        #check number of arguments
        if len(self.function_arguments) != self.symtab.get_attribute(self.function_call_index):
            raise SemanticException("Wrong number of arguments for function '%s'" % fun.name)
        #arguments should be pushed to stack in reverse order
        self.function_arguments.reverse()
        self.codegen.function_call(self.function_call_index, self.function_arguments)
        self.codegen.restore_used_registers()
        return_type = self.symtab.get_type(self.function_call_index)
        #restore previous function call data
        self.function_call_index = self.function_call_stack.pop()
        self.function_arguments = self.function_arguments_stack.pop()
        register = self.codegen.take_register(return_type)
        #move result to a new free register, to allow the next function call
        self.codegen.move(self.codegen.take_function_register(return_type), register)
        return register
1028266
def current(class_):
		""
		tzi = class_()
		kernel32 = ctypes.windll.kernel32
		getter = kernel32.GetTimeZoneInformation
		getter = getattr(kernel32, 'GetDynamicTimeZoneInformation', getter)
		code = getter(ctypes.byref(tzi))
		return code, tzi
1286644
def get_call_data(
    global_state: GlobalState,
    memory_start: Union[int, BitVec],
    memory_size: Union[int, BitVec],
):
    
    state = global_state.mstate
    transaction_id = "{}_internalcall".format(global_state.current_transaction.id)

    memory_start = cast(
        BitVec,
        (
            symbol_factory.BitVecVal(memory_start, 256)
            if isinstance(memory_start, int)
            else memory_start
        ),
    )
    memory_size = cast(
        BitVec,
        (
            symbol_factory.BitVecVal(memory_size, 256)
            if isinstance(memory_size, int)
            else memory_size
        ),
    )

    uses_entire_calldata = simplify(
        memory_size - global_state.environment.calldata.calldatasize == 0
    )

    if uses_entire_calldata is True:
        return global_state.environment.calldata

    try:
        calldata_from_mem = state.memory[
            util.get_concrete_int(memory_start) : util.get_concrete_int(
                memory_start + memory_size
            )
        ]
        return ConcreteCalldata(transaction_id, calldata_from_mem)
    except TypeError:
        log.debug("Unsupported symbolic calldata offset")
        return SymbolicCalldata(transaction_id)
1318823
def in_function_call(self):
        """"""
        #See if we are calling a function inside a module or other function.
        result = []
        if (self.context.el_section == "body" and
            self.context.el_call in [ "sub", "fun" ]):
            #Do a signature completion for the function/subroutine call.
            result = self.signature()

        if result == []:
            return self.complete()

        return result
609289
def reset_trace():
    
    global call_dict
    global call_stack
    global func_count
    global func_count_max
    global func_time
    global func_time_max
    global call_stack_timer

    call_dict = {}

    # current call stack
    call_stack = ['__main__']

    # counters for each function
    func_count = {}
    func_count_max = 0

    # accumative time per function
    func_time = {}
    func_time_max = 0

    # keeps track of the start time of each call on the stack
    call_stack_timer = []
706132
def get_function_body(self, func_indent):
        """"""
        cursor = self.code_editor.textCursor()
        line_number = cursor.blockNumber() + 1
        number_of_lines = self.code_editor.blockCount()
        body_list = []

        for idx in range(number_of_lines - line_number + 1):
            text = to_text_string(cursor.block().text())
            text_indent = get_indent(text)

            if text.strip() == '':
                pass
            elif len(text_indent) <= len(func_indent):
                break

            body_list.append(text)

            cursor.movePosition(QTextCursor.NextBlock)

        return '\n'.join(body_list)
230678
function getCaller3Info() {
    if (this === undefined) {
        // Cannot access caller info in 'strict' mode.
        return;
    }
    var obj = {};
    var saveLimit = Error.stackTraceLimit;
    var savePrepare = Error.prepareStackTrace;
    Error.stackTraceLimit = 3;

    Error.prepareStackTrace = function (_, stack) {
        var caller = stack[2];
        if (sourceMapSupport) {
            caller = sourceMapSupport.wrapCallSite(caller);
        }
        obj.file = caller.getFileName();
        obj.line = caller.getLineNumber();
        var func = caller.getFunctionName();
        if (func)
            obj.func = func;
    };
    Error.captureStackTrace(this, getCaller3Info);
    // call prepareStackTrace
    this.stack

    Error.stackTraceLimit = saveLimit;
    Error.prepareStackTrace = savePrepare;
    return obj;
  }
794088
def get_f_ty_callback(self):
        
        cb = self._callback_factory(self.exprs)
        lb = self.lower_bounds
        ub = self.upper_bounds
        if lb is not None or ub is not None:
            def _bounds_wrapper(t, y, p=(), be=None):
                if lb is not None:
                    if np.any(y < lb - 10*self._current_integration_kwargs['atol']):
                        raise RecoverableError
                    y = np.array(y)
                    y[y < lb] = lb[y < lb]
                if ub is not None:
                    if np.any(y > ub + 10*self._current_integration_kwargs['atol']):
                        raise RecoverableError
                    y = np.array(y)
                    y[y > ub] = ub[y > ub]
                return cb(t, y, p, be)
            return _bounds_wrapper
        else:
            return cb
1028953
def function_trace(function_name):
    
    if newrelic:
        nr_transaction = newrelic.agent.current_transaction()
        with newrelic.agent.FunctionTrace(nr_transaction, function_name):
            yield
    else:
        yield
131684
def get_func(func, aliasing, implementations):
    
    try:
        func_str = aliasing[func]
    except KeyError:
        if callable(func):
            return func
    else:
        if func_str in implementations:
            return func_str
        if func_str.startswith('nan') and \
                func_str[3:] in funcs_no_separate_nan:
            raise ValueError("%s does not have a nan-version".format(func_str[3:]))
        else:
            raise NotImplementedError("No such function available")
    raise ValueError("func %s is neither a valid function string nor a "
                     "callable object".format(func))