Пример #1
0
 def org(self, origin):
     from java.math import BigInteger
     if type(origin) is int:
         self.builder.setOrigin(origin)
     elif type(origin) is dict:
         delta = origin.get('delta')
         if type(delta) is not int:
             raise TypeError("delta must be int")
         self.builder.setRelativeOrigin(BigInteger(str(delta)))
     else:
         raise TypeError("origin must be int or dict")
Пример #2
0
def readWKB(wkb):
    """
  Constructs a geometry from Well Known Binary.

  >>> 
  """
    if isinstance(wkb, (str, unicode)):
        from java.math import BigInteger
        wkb = BigInteger(wkb, 16).toByteArray()

    return _wkbreader.read(wkb)
Пример #3
0
    def define_space(self, attrs):
        from java.math import BigInteger
        id = attrs.get('id')
        text = attrs.get('text')
        fillWith = attrs.get('fill_with')

        self.configurer.defineSpace(id, text, BigInteger(str(fillWith)))

        def p(self, length):
            self.builder.addSpace(length)

        template_builder.define_method_for(DataManager, id, 'space', p)
Пример #4
0
def create_preparator(is_comparator, attrs, contents=lambda: []):
    from java.math import BigInteger
    target = attrs.get('target')

    builder = globals.template.template.beginPreparator(target, is_comparator)
    builder.setWhere(globals.template.get_caller_location())

    name = attrs.get('name')

    if name is not None:
        builder.setName(name)

    mask = attrs.get('mask')
    if mask is not None:
        if isinstance(mask, basestring):
            builder.setMaskValue(mask)
        elif isintance(mask, list):
            builder.setMaskCollection(mask)
        else:
            raise TypeError("Illegal mask type")

    arguments = attrs.get('arguments')
    if arguments is not None:
        if not isinstance(arguments, dict):
            raise TypeError("arguments is not dict")

        for name, value in arguments.iteritems():
            if isinstance(value, int):
                builder.addArgumentValue(name, BigInteger(str(value)))
            elif isinstance(value, RangeClass):
                builder.addArgumentRange(name, BigInteger(str(value.min)),
                                         BigInteger(str(value.max)))
            elif isinstance(value, list):
                builder.addArgumentCollection(name, value)
            else:
                raise TypeError("Illegal value of argument")

    contents()
    globals.template.template.endPreparator()
def set_arguments_from_array(builder, args):
    for value in args:
        if isinstance(args, list):
            set_arguments_from_array(builder, value)
        else:
            if isinstance(value, template.WrappedObject):
                value = value.java_object()
            if isinstance(value, basestring):
                value = value
            if isinstance(value, int):
                builder.addArgument(BigInteger(str(value)))
            else:
                if not isinstance(value, dict):
                    builder.addArgument(value)
Пример #6
0
def convert_big_integer(value):
    """
    Convert the big integer value to long.
    :param value: big integer string or number value
    :return: converted to long
    """
    _method_name = 'convert_big_integer'
    converted_type = alias_constants.LONG
    converted = None
    if value is not None:
        try:
            converted = BigInteger(value).longValue()
        except NumberFormatException, nfe:
            _logger.fine('WLSDPLY-06774', value, type(value), nfe.getMessage(),
                         class_name=_class_name, method_name=_method_name)
Пример #7
0
def get_pinsn_at(address, thumb=False):
    """
    attempt to dissemble adr, return PseudoInstruction or None
    for pre-analysis without affecting program

    """
    # NOTE in modules used from interpreter window, using the currentProgram
    # variable fails on tab switches (currentProgram is set at import time)
    cp = getCurrentProgram()
    mbi = MemoryBufferImpl(cp.getMemory(), address)
    # API changed in 9.2
    if ghidra.framework.ApplicationVersion(
            getGhidraVersion()) >= ghidra.framework.ApplicationVersion('9.2'):
        pci = ProcessorContextImpl(cp.getLanguage())
    else:
        pci = ProcessorContextImpl(cp.getProgramContext().getRegisters())

    treg = pci.getRegister('TMode')

    # don't try to set thumb reg if firmware not loaded as t
    if treg:
        if thumb:
            pci.setValue(pci.getRegister('TMode'), BigInteger("1"))
        else:
            pci.setValue(pci.getRegister('TMode'), BigInteger("0"))
    elif thumb:
        warn("ignoring Thumb set on non-t processor")

    try:
        ip = cp.getLanguage().parse(mbi, pci, False)
        pi = PseudoInstruction(address, ip, mbi, pci)
        return pi
    except (ghidra.program.model.lang.UnknownInstructionException,
            ghidra.program.model.lang.InsufficientBytesException,
            ghidra.program.model.address.AddressOverflowException):
        return None
Пример #8
0
def print_format(kind, format, *args):
    import ru.ispras.microtesk.test.template.Value as Value
    from java.math import BigInteger

    builder = globals.template.template.newOutput(kind, format)

    for arg in args:
        if isinstance(arg, long) or isinstance(arg, basestring) or isinstance(
                arg, Value):
            builder.addArgument(arg)
        elif isinstance(arg, Location):
            builder.addArgument(arg.name, BigInteger(str(arg.index)))
        else:
            raise TypeError("Illegal format argument class")

    return globals.template.template.addOutput(builder.build())
Пример #9
0
 def parse(self, javaCert):
     '''
         Perform trasformation from java.security.X509Certificate to ssl_cert.X509Certificate
         @types: java.security.X509Certificate -> ssl_cert.X509Certificate
     '''
     typeCert = javaCert.getType()
     if typeCert == CertificateTypes.X509:
         objParser = DnParser()
         subject = javaCert.getSubjectDN().getName()
         issuedBy = javaCert.getIssuerDN().getName()
         subjectDn = objParser.parse(subject)
         issuedByDn = objParser.parse(issuedBy)
         version = javaCert.getVersion()
         create = javaCert.getNotBefore()
         expires = javaCert.getNotAfter()
         serialNumber = self.__bytesToHex(
             BigInteger(str(javaCert.getSerialNumber())).toByteArray())
         return X509Certificate(
             create, expires, LDAPDistinguishedObject(subjectDn, subject),
             LDAPDistinguishedObject(issuedByDn, issuedBy), serialNumber,
             javaCert.getSigAlgName(), typeCert, version)
     return None
Пример #10
0
 def check_big_compress_buffer(self, size, compress_func):
     _1M = 1024 * 1024
     if not is_jython:
         # Generate 10MB worth of random, and expand it by repeating it.
         # The assumption is that zlib's memory is not big enough to exploit
         # such spread out redundancy.
         fmt = "%%0%dx" % (2 * _1M)
         data = ''.join([
             binascii.a2b_hex(fmt % random.getrandbits(8 * _1M))
             for i in range(10)
         ])
         data = data * (size // len(data) + 1)
     else:
         #
         # The original version of this test passes fine on cpython,
         # but appears to hang on jython, because of the time taken to
         # format a very large integer as a hexadecimal string.
         # See this issue for details
         # http://bugs.jython.org/issue2013
         # Since testing string formatting is not the purpose of the test
         # it is necessary to generate the random test data in a different
         # way on jython. (There may be a better way than what I have
         # implemented here)
         #
         from java.math import BigInteger
         from java.util import Random
         num_bits = 8 * _1M  # causes "java.lang.OutOfMemoryError: Java heap space"
         num_bits = _1M
         data = ''.join([
             str(BigInteger((num_bits), Random()).toByteArray())
             for i in range(10)
         ])
     try:
         compress_func(data)
     finally:
         # Release memory
         data = None
Пример #11
0
# irrevocable, worldwide license in the Software to reproduce,
# distribute copies to the public, prepare derivative works, and perform
# publicly and display publicly, and to permit other to do so.
#
__author__ = 'bmah'

#
# Get switch and ports (node and node connectors) inventory on MD-SAL
#
from java.math import BigInteger
from net.es.netshell.odlmdsal.impl import OdlMdsalImpl
from org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819 import FlowCapableNode
from org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819 import FlowCapableNodeConnector

omi = OdlMdsalImpl.getInstance()

ss = omi.getNetworkDevices()
for s in ss:
    fcn = s.getAugmentation(FlowCapableNode)
    if fcn:
        spl = s.getId().getValue().split(":")
        print "dpid " + str(int(spl[1])) + " (" + BigInteger(spl[1]).toString(
            16) + ") : " + fcn.getManufacturer() + " / " + fcn.getHardware(
            ) + " @ " + fcn.getIpAddress().getIpv4Address().getValue()
        conns = omi.getNodeConnectors(s)
        for conn in conns:
            fcnc = conn.getAugmentation(FlowCapableNodeConnector)
            if fcnc:
                print "  " + conn.getId().getValue() + " => " + fcnc.getName(
                ) + " (port " + str(fcnc.getPortNumber().getUint32()) + ")"
Пример #12
0
def bi(val):
    return BigInteger("%s"%val)
Пример #13
0
#
# Extremely specific to one particular configuration of the ESnet testbed,
# but is useful for illustrating how to perform OpenFlow operations
#
from java.math import BigInteger
from net.es.netshell.odlmdsal.impl import OdlMdsalImpl
from net.es.netshell.odlcorsa.impl import OdlCorsaImpl

from org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924 import MacAddress

omi = OdlMdsalImpl.getInstance()
oci = OdlCorsaImpl.getInstance()

# Get the switches in the ODL world
swDENV = omi.getNetworkDeviceByDpid(
    BigInteger("02010064656e7601", 16).longValue())
swAOFA = omi.getNetworkDeviceByDpid(
    BigInteger("020100616f666101", 16).longValue())

# Get interesting node connectors
portDENV23 = omi.getNodeConnector(swDENV, "23")
portDENV24 = omi.getNodeConnector(swDENV, "24")
portAOFA23 = omi.getNodeConnector(swAOFA, "23")
portAOFA24 = omi.getNodeConnector(swAOFA, "24")

# Get the MAC addresses of the DTN data plane interfaces
macLBL = MacAddress("00:60:DD:44:2B:2C")
macBNL = MacAddress("00:60:DD:44:2B:18")
macANL = MacAddress("00:60:DD:44:2B:14")
macBroadcast = MacAddress("FF:FF:FF:FF:FF:FF")
Пример #14
0
def toInt(a):
    return BigInteger("%i" % a).intValue()
Пример #15
0
    def __findGeoLocationsInFile(self, file, abstractFile):

        tempBytes = bytearray([0] * 2) # will temporarily hold bytes to be converted into the correct data types

        try:
            inputStream = FileInputStream(file)

            inputStream.read(tempBytes) # version

            tempBytes = bytearray([0] * 2)
            inputStream.read(tempBytes) # number of location entries

            iterations = BigInteger(tempBytes).intValue()

            for i in range(iterations): # loop through every entry
                tempBytes = bytearray([0] * 2)
                inputStream.read(tempBytes)

                tempBytes = bytearray([0])
                inputStream.read(tempBytes)

                while BigInteger(tempBytes).intValue() != 0: # pass through non important values until the start of accuracy(around 7-10 bytes)
                    if 0 > inputStream.read(tempBytes):
                        break # we've passed the end of the file, so stop

                tempBytes = bytearray([0] * 3)
                inputStream.read(tempBytes)
                if BigInteger(tempBytes).intValue() <= 0: # This refers to a location that could not be calculated
                    tempBytes = bytearray([0] * 28) # read rest of the row's bytes
                    inputStream.read(tempBytes)
                    continue
                accuracy = "" + BigInteger(tempBytes).intValue()

                tempBytes = bytearray([0] * 4)
                inputStream.read(tempBytes)
                confidence = "" + BigInteger(tempBytes).intValue()

                tempBytes = bytearray([0] * 8)
                inputStream.read(tempBytes)
                latitude = CacheLocationAnalyzer.toDouble(bytes)

                tempBytes = bytearray([0] * 8)
                inputStream.read(tempBytes)
                longitude = CacheLocationAnalyzer.toDouble(bytes)

                tempBytes = bytearray([0] * 8)
                inputStream.read(tempBytes)
                timestamp = BigInteger(tempBytes).longValue() / 1000

                attributes = ArrayList()
                artifact = abstractFile.newArtifact(BlackboardArtifact.ARTIFACT_TYPE.TSK_GPS_TRACKPOINT)
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LATITUDE, AndroidAnalyzer.MODULE_NAME, latitude))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_GEO_LONGITUDE, AndroidAnalyzer.MODULE_NAME, longitude))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_DATETIME, AndroidModuleFactorymodule.Name, timestamp))
                attributes.add(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_PROG_NAME, AndroidAnalyzer.MODULE_NAME,
                    file.getName() + "Location History"))

                artifact.addAttributes(attributes)
                #Not storing these for now.
                #    artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_VALUE.getTypeID(), AndroidModuleFactorymodule.moduleName, accuracy))
                #    artifact.addAttribute(BlackboardAttribute(BlackboardAttribute.ATTRIBUTE_TYPE.TSK_COMMENT.getTypeID(), AndroidModuleFactorymodule.moduleName, confidence))
                try:
                    # index the artifact for keyword search
                    blackboard = Case.getCurrentCase().getServices().getBlackboard()
                    blackboard.indexArtifact(artifact)
                except Blackboard.BlackboardException as ex:
                    self._logger.log(Level.SEVERE, "Unable to index blackboard artifact " + artifact.getArtifactID(), ex)
                    self._logger.log(Level.SEVERE, traceback.format_exc())
                    MessageNotifyUtil.Notify.error("Failed to index GPS trackpoint artifact for keyword search.", artifact.getDisplayName())

        except Exception as ex:
            self._logger.log(Level.SEVERE, "Error parsing Cached GPS locations to blackboard", ex)
            self._logger.log(Level.SEVERE, traceback.format_exc())
Пример #16
0
from java.lang import Long, Integer, Short, Character, Byte, Boolean, Double, Float, String
from java.math import BigInteger

values = [
    0, 0L, 0.0, 'c', "string", (), o, c, foo, subfoo, subfoo2, n, Object,
    Class, Foo, SubFoo, C, SubFoo2, N, Integer,
    Long(0),
    Integer(0),
    Short(0),
    Character('c'),
    Byte(0),
    Boolean(0),
    Double(0),
    Float(0),
    String("js"),
    BigInteger("0")
]


def pp(v):
    inst = d.get(v, None)
    if inst is not None:
        return inst
    if hasattr(v, '__name__'):
        return v.__name__
    if isinstance(v, (String, Number, Character, Boolean)):
        n = v.__class__.__name__
        return "%s[%s]" % (n[n.rfind('.') + 1:], v)
    return repr(v)

Пример #17
0
def parseNextIntLittleEndian(ra, count):
  # ra: a RandomAccessFile at the correct place to read the next sequence of bytes
  bytes = zeros(count + 1, 'b')
  ra.read(bytes, 0, count) # ending zero will be the leading zero when reversed
  return BigInteger(reversed(bytes)).longValue() # long to avoid bit overflows
Пример #18
0
def run(sim, ns):

    sim.run(BigInteger(ns).multiply(BigInteger("1000000")))
Пример #19
0
def toByte(a):
    return BigInteger("%i" % a).byteValue()
Пример #20
0
 def entry_point(org, exception, contents=lambda: []):
     from java.math import BigInteger
     builder.beginEntryPoint(BigInteger(str(org)), exception)
     contents()
     return builder.endEntryPoint()
def parseNextIntLittleEndian(ra, count):
    # ra.read() reads a single byte as an unsigned int
    return BigInteger(reversed([ra.readByte()
                                for _ in xrange(count)])).intValue()
Пример #22
0
# Set up end-to-end flow on testbed, Take 2
# More complicated, using OVS switch going eastbound (but not westbound)
# We do MAC translation across the wide area circuit between hardware switches.

from java.math import BigInteger
from net.es.netshell.odlmdsal.impl import OdlMdsalImpl
from net.es.netshell.odlcorsa.impl import OdlCorsaImpl

from org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924 import MacAddress

omi = OdlMdsalImpl.getInstance()
oci = OdlCorsaImpl.getInstance()

# Get the switches in the ODL world
hwDENV = omi.getNetworkDeviceByDpid(
    BigInteger("02010064656e7601", 16).longValue())
ovsDENV = omi.getNetworkDeviceByDpid(
    BigInteger("01020064656e7601", 16).longValue())
hwAOFA = omi.getNetworkDeviceByDpid(
    BigInteger("020100616f666101", 16).longValue())
ovsAOFA = omi.getNetworkDeviceByDpid(
    BigInteger("010200616f666101", 16).longValue())

# Get interesting node connectors
hwDENV1 = omi.getNodeConnector(hwDENV, "1")
hwDENV2 = omi.getNodeConnector(hwDENV, "2")
hwDENV23 = omi.getNodeConnector(hwDENV, "23")
hwDENV24 = omi.getNodeConnector(hwDENV, "24")
ovsDENVeth10 = omi.getNodeConnector(ovsDENV, "eth10")
ovsDENVeth11 = omi.getNodeConnector(ovsDENV, "eth11")
hwAOFA1 = omi.getNodeConnector(hwAOFA, "1")
Пример #23
0
def parseNextIntBigEndian(ra, count):
    # ra: a RandomAccessFile at the correct place to read the next sequence of bytes
    bytes = zeros(count + 1, 'b')
    ra.read(bytes, 1,
            count)  # a leading zero to avoid parsing as negative numbers
    return BigInteger(bytes).longValue()  # long to avoid bit overflows
Пример #24
0
 def align(self, value):
     from java.math import BigInteger
     value_in_bytes = alignment_in_bytes(value)
     return self.builder.align(BigInteger(str(value)),
                               BigInteger(str(value_in_bytes)))
Пример #25
0
expected = 0
for i in vec:
    assert i == expected, 'testing __iter__ on java.util.Vector'
    expected = expected + 1

expected = 0
for i in iter(vec):
    assert i == expected, 'testing iter(java.util.Vector)'
    expected = expected + 1

print_test('create java objects', 2)

from java.math import BigInteger

assert BigInteger('1234', 10).intValue() == 1234, 'BigInteger(string)'
assert BigInteger([0x11, 0x11,
                   0x11]).intValue() == 0x111111, 'BigInteger(byte[])'
assert BigInteger(
    -1, [0x11, 0x11, 0x11]).intValue() == -0x111111, 'BigInteger(int, byte[])'

print_test('call static methods')
s1 = String.valueOf(['1', '2', '3'])
s2 = String.valueOf('123')
s3 = String.valueOf(123)
s4 = String.valueOf(123l)
s5 = String.valueOf(['0', '1', '2', '3', 'a', 'b'], 1, 3)
assert s1 == s2 == s3 == s4 == s5, 'String.valueOf method with different arguments'

print_test('call instance methods')
s = String('hello')
Пример #26
0
def int2jBigInteger(val):
    if val.bit_length() <= 63:
        return BigInteger.valueOf(val)
    else:
        return BigInteger(str(val))