code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/env python
import sys, random, string
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
from androguard.core.bytecodes import dvm
TEST = "./examples/dalvik/test/bin/classes.dex"
TEST_OUTPUT = "./examples/dalvik/test/bin/classes_output.dex"
j = dvm.DalvikVMFormat( open(TEST).read() )
# Modify the name of each field
#for field in j.get_fields() :
# field.set_name( random.choice( string.letters ) + ''.join([ random.choice(string.letters + string.digits) for i in range(10 - 1) ] ) )
# Modify the name of each method (minus the constructor (<init>) and a extern called method (go))
#for method in j.get_methods() :
# if method.get_name() != "go" and method.get_name() != "<init>" :
# method.set_name( random.choice( string.letters ) + ''.join([ random.choice(string.letters + string.digits) for i in range(10 - 1) ] ) )
# SAVE CLASS
fd = open( TEST_OUTPUT, "w" )
fd.write( j.save() )
fd.close()
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL + "./")
from androguard.core.androgen import Androguard, OBFU_Names, OBFU_NAMES_FIELDS, OBFU_NAMES_METHODS
TEST = [ './examples/java/test/orig/Test1.class', './examples/java/test/orig_main/Test.class' ]
TEST_OUTPUT = [ './examples/java/test/new/Test1.class', './examples/java/test/new_main/Test.class' ]
a = Androguard( TEST )
OBFU_Names( a, "Test1", "value", ".", OBFU_NAMES_FIELDS )
OBFU_Names( a, "Test1", ".", ".", OBFU_NAMES_METHODS )
i = 0
while i < len(TEST) :
_a = a.get("file", TEST[i])
fd = open( TEST_OUTPUT[i], "w" )
fd.write( _a.save() )
fd.close()
i = i + 1
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL + "./core/vm")
sys.path.append(PATH_INSTALL + "./core/predicates")
from il_reil import VM_REIL, REIL_REGISTER, REIL_LITERAL, REIL_OFFSET, REIL_SUB, REIL_STRING
x = "HELLO WORLD"
var_j = REIL_REGISTER( "j", 4, 0 )
lit_1 = REIL_LITERAL( 50, 4 )
l = [ REIL_SUB( var_j, lit_1, var_j ) ]
v = VM_REIL()
v.execute( l )
v.show()
v.execute( REIL_STRING( x, 0x100 ) )
v.show()
#v.execute( ALGO )
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL + "/core")
sys.path.append(PATH_INSTALL + "/core/bytecodes")
import jvm
TEST = "./examples/java/test/orig/Test1.class"
j = jvm.JVMFormat( open(TEST).read() )
# SHOW CLASS (verbose)
j.show()
# SHOW FIELDS
for i in j.get_fields() :
print i.get_access(), i.get_name(), i.get_descriptor()
print
# SHOW METHODS
for i in j.get_methods() :
print i.get_access(), i.get_name(), i.get_descriptor()
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL + "./")
from androgen import Androguard
CONF1 = "./examples/java/Demo1/androguard_1.xml"
BASE_TEST = "./examples/java/Demo1/orig/"
BASE_TEST_OUTPUT = "./examples/java/Demo1/new/"
BASE_MAIN_TEST = "./examples/java/Demo1/orig_main/"
BASE_MAIN_TEST_OUTPUT = "./examples/java/Demo1/new_main/"
FILES = [
("BaseCipher.class", 0),
("DES.class", 0),
("DES$Context.class", 0),
("IBlockCipher.class", 0),
("IBlockCipherSpi.class", 0),
("Properties$1.class", 0),
("Properties.class", 0),
("Registry.class", 0),
("Util.class", 0),
("WeakKeyException.class", 0),
("Demo1Main.class", 1)
]
TEST = []
TEST_OUTPUT = []
for i in FILES :
if i[1] == 0 :
TEST.append( BASE_TEST + i[0] )
TEST_OUTPUT.append( BASE_TEST_OUTPUT + i[0] )
else :
TEST.append( BASE_MAIN_TEST + i[0] )
TEST_OUTPUT.append( BASE_MAIN_TEST_OUTPUT + i[0] )
a = Androguard( TEST )
a.do( CONF1 )
i = 0
while i < len(TEST) :
_a = a.get("file", TEST[i])
fd = open( TEST_OUTPUT[i], "w" )
fd.write( _a.save() )
fd.close()
i = i + 1
| Python |
#!/usr/bin/env python
import random, string
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL + "./")
from androguard.core.androgen import AndroguardS
TEST = './examples/java/test/orig/Test1.class'
TEST_OUTPUT = './examples/java/test/new/Test1.class'
TEST2 = './examples/java/Hello.class'
_a = AndroguardS( TEST )
_b = AndroguardS( TEST2 )
_a.show()
#nb = 0
#for field in _a.gets( "fields" ) :
# field.set_name( random.choice( string.letters ) + ''.join([ random.choice(string.letters + string.digits) for i in range(10 - 1) ] ) )
# nb += 1
#for string in _a.gets( "strings" ) :
# print string
#for method in _a.get("method", "rc4") :
# if method.with_descriptor( "([B)[B" ) :
# code = method.get_code()
# code.show()
# code.remplace_at( 19, [ "sipush", 254 ] )
# code.insert_at( 21, [ "sipush", 254 ] )
# code.insert_at( 22, [ "iand" ] )
# code.remove_at( 19 )
# code.remove_at( 19 )
# code.show()
# code.remove_at( 19 )
# code.insert_at( 19, [ "sipush", 254 ] )
_a.insert_string( "BLAAAA" )
#_a.insert_craft_method( "toto", [ "ACC_PUBLIC", "[B", "[B" ], [ [ "aconst_null" ], [ "areturn" ] ] ) #( "sipush", 254 ) ] )
#_a.insert_direct_method( "toto2", _b.get("method", "test3")[0] )
_a.insert_direct_method( "toto2", _b.get("method", "test5")[0] )
for method in _a.get("method", "test_base") :
if method.with_descriptor( "(I)I" ) :
code = method.get_code()
code.removes_at( [ 13, 14 ] )
code.insert_at( 13, [ "aload_0" ] )
method_toto2 = _a.get("method", "toto2")[0]
code.insert_at( 14, [ "invokevirtual", "Test1", "toto2", method_toto2.get_descriptor() ] )
method.show()
#for method in _a.get("method", "test1") :
# code = method.get_code()
# code.remove_at( 0 )
# code.insert_at( 0, [ "aload_0" ] )
# method_toto2 = _a.get("method", "toto2")[0]
# code.insert_at( 1, [ "invokevirtual", "toto2", method_toto2.get_descriptor() ] )
# method.show()
fd = open( TEST_OUTPUT, "w" )
fd.write( _a.save() )
fd.close()
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append( PATH_INSTALL )
from androguard.core.bytecodes import dvm, apk
TEST = "./examples/android/TC/bin/TC-debug.apk"
a = apk.APK( TEST )
a.show()
j = dvm.DalvikVMFormat( a.get_dex() )
# SHOW CLASS (verbose)
#j.show()
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL + "/core")
sys.path.append(PATH_INSTALL + "/core/bytecodes")
sys.path.append(PATH_INSTALL + "/core/analysis")
import jvm, analysis
TEST = "./examples/java/test/orig/Test1.class"
j = jvm.JVMFormat( open(TEST).read() )
x = analysis.VMAnalysis( j )
# SHOW CLASS (verbose and pretty)
#j.pretty_show( x )
# SHOW METHODS
for i in j.get_methods() :
print i
i.pretty_show( x )
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
from androguard.core.bytecodes import apk
from xml.dom import minidom
ap = apk.AXMLPrinter( open("examples/axml/AndroidManifest2.xml", "r").read() )
print minidom.parseString( ap.getBuff() ).toxml()
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
from androguard.core.androgen import AndroguardS
from androguard.core.analysis import analysis
#TEST = 'examples/java/test/orig/Test1.class'
TEST = 'examples/android/TestsAndroguard/bin/classes.dex'
a = AndroguardS( TEST )
x = analysis.VMAnalysis( a.get_vm() )
for method in a.get_methods() :
print method.get_class_name(), method.get_name(), method.get_descriptor()
code = method.get_code()
bc = code.get_bc()
idx = 0
for i in bc.get() :
print "\t", "%x" % idx, i.get_name(), i.get_output()
idx += i.get_length()
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL + "/core")
sys.path.append(PATH_INSTALL + "/core/bytecodes")
sys.path.append(PATH_INSTALL + "/core/assembly/")
sys.path.append(PATH_INSTALL + "/core/assembly/libassembly")
import assembly
assembly.ASM()
#import arm
#arm.ARM()
#a = apk.APK( TEST )
#a.show()
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
from androguard.core.bytecodes import dvm
TEST = "./examples/dalvik/test/bin/classes.dex"
j = dvm.DalvikVMFormat( open(TEST).read() )
# SHOW CLASS (verbose)
j.show()
# SHOW FIELDS
for i in j.get_fields() :
print i.get_access(), i.get_name(), i.get_descriptor()
print
# SHOW METHODS
for i in j.get_methods() :
print i.get_access(), i.get_name(), i.get_descriptor()
| Python |
#!/usr/bin/env python
import sys
PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)
from androguard.core.bytecodes import dvm
from androguard.core.analysis import analysis
from androguard.decompiler import decompiler
TEST = "examples/android/TestsAndroguard/bin/classes.dex"
j = dvm.DalvikVMFormat( open(TEST).read() )
jx = analysis.VMAnalysis( j )
#d = decompiler.DecompilerDex2Jad( j )
#d = decompiler.DecompilerDed( j )
d = decompiler.DecompilerDAD( j, jx )
j.set_decompiler( d )
# SHOW METHODS
for i in j.get_methods() :
if i.get_name() == "onCreate" :
print i.get_class_name(), i.get_name()
i.source()
# if i.get_name() == "testWhileTrue" :
# i.source()
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys
from optparse import OptionParser
from xml.dom import minidom
import codecs
from androguard.core import androconf
from androguard.core.bytecodes import apk
option_0 = { 'name' : ('-i', '--input'), 'help' : 'filename input (APK or android\'s binary xml)', 'nargs' : 1 }
option_1 = { 'name' : ('-o', '--output'), 'help' : 'filename output of the xml', 'nargs' : 1 }
option_2 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2]
def main(options, arguments) :
if options.input != None :
buff = ""
ret_type = androconf.is_android( options.input )
if ret_type == "APK" :
a = apk.APK( options.input )
buff = a.xml[ "AndroidManifest.xml" ].toprettyxml()
a.get_activities()
elif ".xml" in options.input :
ap = apk.AXMLPrinter( open(options.input, "rb").read() )
buff = minidom.parseString( ap.getBuff() ).toprettyxml()
else :
print "Unknown file type"
return
if options.output != None :
fd = codecs.open(options.output, "w", "utf-8")
fd.write( buff )
fd.close()
else :
print buff
elif options.version != None :
print "Androaxml version %s" % androconf.ANDROGUARD_VERSION
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys, re, os
from optparse import OptionParser
from androguard.core.bytecodes import apk
sys.path.append("./elsim/")
from elsim.elsign import dalvik_elsign
sys.path.append("./mercury/client")
from merc.lib.common import Session
option_0 = { 'name' : ('-l', '--list'), 'help' : 'list all packages', 'nargs' : 1 }
option_1 = { 'name' : ('-i', '--input'), 'help' : 'get specific packages (a filter)', 'nargs' : 1 }
option_2 = { 'name' : ('-r', '--remotehost'), 'help' : 'specify ip of emulator/device', 'nargs' : 1 }
option_3 = { 'name' : ('-p', '--port'), 'help' : 'specify the port', 'nargs' : 1 }
option_4 = { 'name' : ('-o', '--output'), 'help' : 'output directory to write packages', 'nargs' : 1 }
option_5 = { 'name' : ('-b', '--database'), 'help' : 'database : use this database', 'nargs' : 1 }
option_6 = { 'name' : ('-c', '--config'), 'help' : 'use this configuration', 'nargs' : 1 }
option_7 = { 'name' : ('-v', '--verbose'), 'help' : 'display debug information', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_4, option_5, option_6, option_7]
def display(ret, debug) :
print "---->", ret[0],
def main(options, arguments) :
sessionip = "127.0.0.1"
sessionport = 31415
if options.remotehost :
sessionip = options.remotehost
if options.port :
sessionport = int(options.port)
newsession = Session(sessionip, sessionport, "bind")
# Check if connection can be established
if newsession.executeCommand("core", "ping", None).data == "pong":
if options.list :
request = {'filter': options.list, 'permissions': None }
apks_info = newsession.executeCommand("packages", "info", {}).getPaddedErrorOrData()
print apks_info
elif options.input and options.output :
s = None
if options.database != None or options.config != None :
s = dalvik_elsign.MSignature( options.database, options.config, options.verbose != None, ps = dalvik_elsign.PublicSignature)
request = {'filter': options.input, 'permissions': None }
apks_info = newsession.executeCommand("packages", "info", request).getPaddedErrorOrData()
print apks_info
for i in apks_info.split("\n") :
if re.match("APK path:", i) != None :
name_app = i.split(":")[1][1:]
print name_app,
response = newsession.downloadFile(name_app, options.output)
print response.data, response.error,
if s != None :
a = apk.APK( options.output + "/" + os.path.basename(name_app) )
if a.is_valid_APK() :
display( s.check_apk( a ), options.verbose )
print
else:
print "\n**Network Error** Could not connect to " + sessionip + ":" + str(sessionport) + "\n"
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys, os
from optparse import OptionParser
from androguard.core import androconf
from androguard.core.bytecodes import apk
sys.path.append("./elsim/")
from elsim.elsign import dalvik_elsign
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use this filename', 'nargs' : 1 }
option_1 = { 'name' : ('-d', '--directory'), 'help' : 'directory : use this directory', 'nargs' : 1 }
option_2 = { 'name' : ('-b', '--database'), 'help' : 'database : use this database', 'nargs' : 1 }
option_3 = { 'name' : ('-c', '--config'), 'help' : 'use this configuration', 'nargs' : 1 }
option_4 = { 'name' : ('-v', '--verbose'), 'help' : 'display debug information', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_4]
def display(ret, debug) :
print "---->", ret[0]
sys.stdout.flush()
def main(options, arguments) :
if options.database == None or options.config == None :
return
s = dalvik_elsign.MSignature( options.database, options.config, options.verbose != None, ps = dalvik_elsign.PublicSignature)
if options.input != None :
ret_type = androconf.is_android( options.input )
print os.path.basename(options.input), ":",
sys.stdout.flush()
if ret_type == "APK" :
try :
a = apk.APK( options.input )
if a.is_valid_APK() :
display( s.check_apk( a ), options.verbose )
else :
print "INVALID"
except Exception, e :
print "ERROR", e
elif ret_type == "DEX" :
display( s.check_dex( open(options.input, "rb").read() ), options.verbose )
elif options.directory != None :
for root, dirs, files in os.walk( options.directory, followlinks=True ) :
if files != [] :
for f in files :
real_filename = root
if real_filename[-1] != "/" :
real_filename += "/"
real_filename += f
ret_type = androconf.is_android( real_filename )
if ret_type == "APK" :
print os.path.basename( real_filename ), ":",
sys.stdout.flush()
try :
a = apk.APK( real_filename )
if a.is_valid_APK() :
display( s.check_apk( a ), options.verbose )
else :
print "INVALID APK"
except Exception, e :
print "ERROR", e
elif ret_type == "DEX" :
try :
print os.path.basename( real_filename ), ":",
sys.stdout.flush()
display( s.check_dex( open(real_filename, "rb").read() ), options.verbose )
except Exception, e :
print "ERROR", e
elif options.version != None :
print "Androsign version %s" % androconf.ANDROGUARD_VERSION
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
from xml.sax.saxutils import escape
import sys, os
from optparse import OptionParser
from androguard.core.androgen import Androguard
from androguard.core.analysis import analysis
option_0 = { 'name' : ('-i', '--input'), 'help' : 'filename input', 'nargs' : 1 }
option_1 = { 'name' : ('-o', '--output'), 'help' : 'filename output of the xgmml', 'nargs' : 1 }
option_2 = { 'name' : ('-f', '--functions'), 'help' : 'include function calls', 'action' : 'count' }
option_3 = { 'name' : ('-e', '--externals'), 'help' : 'include extern function calls', 'action' : 'count' }
option_4 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_4]
METHODS_ID = {}
EXTERNAL_METHODS_ID = {}
NODES_ID = {}
EDGES_ID = {}
NODE_GRAPHIC = {
"classic" : {
"h" : 20.0,
"w" : 20.0,
"type" : "ELLIPSE",
"width" : 1,
"fill" : "#e1e1e1",
"outline" : "#000000",
},
"extern" : {
"h" : 20.0,
"w" : 20.0,
"type" : "ELLIPSE",
"width" : 1,
"fill" : "#ff8c00",
"outline" : "#000000",
}
}
EDGE_GRAPHIC = {
"cfg" : {
"width" : 2,
"fill" : "#0000e1",
},
"fcg" : {
"width" : 3,
"fill" : "#9acd32",
},
"efcg" : {
"width" : 3,
"fill" : "#808000",
}
}
def get_node_name(method, bb) :
return "%s-%s-%s" % ( method.get_class_name(), escape(bb.name), escape(method.get_descriptor()) )
def export_xgmml_cfg(g, fd) :
method = g.get_method()
name = method.get_name()
class_name = method.get_class_name()
descriptor = method.get_descriptor()
if method.get_code() != None :
size_ins = method.get_code().get_length()
for i in g.basic_blocks.get() :
fd.write("<node id=\"%d\" label=\"%s\">\n" % (len(NODES_ID), get_node_name(method, i)))
fd.write("<att type=\"string\" name=\"classname\" value=\"%s\"/>\n" % (escape(class_name)))
fd.write("<att type=\"string\" name=\"name\" value=\"%s\"/>\n" % (escape(name)))
fd.write("<att type=\"string\" name=\"descriptor\" value=\"%s\"/>\n" % (escape(descriptor)))
fd.write("<att type=\"integer\" name=\"offset\" value=\"%d\"/>\n" % (i.start))
cl = NODE_GRAPHIC["classic"]
width = cl["width"]
fill = cl["fill"]
# No child ...
if i.childs == [] :
fill = "#87ceeb"
if i.start == 0 :
fd.write("<att type=\"string\" name=\"node.label\" value=\"%s\\n%s\"/>\n" % (escape(name), i.get_ins()[-1].get_name()))
width = 3
fill = "#ff0000"
METHODS_ID[ class_name + name + descriptor ] = len(NODES_ID)
else :
fd.write("<att type=\"string\" name=\"node.label\" value=\"0x%x\\n%s\"/>\n" % (i.start, i.get_ins()[-1].get_name()))
size = 0
for tmp_ins in i.get_ins() :
size += (tmp_ins.get_length() / 2)
h = ((size / float(size_ins)) * 20) + cl["h"]
fd.write("<graphics type=\"%s\" h=\"%.1f\" w=\"%.1f\" width=\"%d\" fill=\"%s\" outline=\"%s\">\n" % ( cl["type"], h, h, width, fill, cl["outline"]))
fd.write("</graphics>\n")
fd.write("</node>\n")
NODES_ID[ class_name + i.name + descriptor ] = len(NODES_ID)
for i in g.basic_blocks.get() :
for j in i.childs :
if j[-1] != None :
label = "%s (cfg) %s" % (get_node_name(method, i), get_node_name(method, j[-1]))
id = len(NODES_ID) + len(EDGES_ID)
fd.write( "<edge id=\"%d\" label=\"%s\" source=\"%d\" target=\"%d\">\n" % (id, label, NODES_ID[ class_name + i.name + descriptor ], NODES_ID[ class_name + j[-1].name + descriptor ]) )
cl = EDGE_GRAPHIC["cfg"]
fd.write("<graphics width=\"%d\" fill=\"%s\">\n" % (cl["width"], cl["fill"]) )
fd.write("</graphics>\n")
fd.write("</edge>\n")
EDGES_ID[ label ] = id
def export_xgmml_fcg(a, x, fd) :
classes = a.get_classes_names()
# Methods flow graph
for m, _ in x.tainted_packages.get_packages() :
paths = m.get_methods()
for j in paths :
if j.get_method().get_class_name() in classes and m.get_info() in classes :
if j.get_access_flag() == analysis.TAINTED_PACKAGE_CALL :
t = m.get_info() + j.get_name() + j.get_descriptor()
if t not in METHODS_ID :
continue
bb1 = x.hmethods[ j.get_method() ].basic_blocks.get_basic_block( j.get_idx() )
node1 = get_node_name(j.get_method(), bb1) + "@0x%x" % j.get_idx()
node2 = "%s-%s-%s" % (m.get_info(), escape(j.get_name()), escape(j.get_descriptor()))
label = "%s (fcg) %s" % (node1, node2)
if label in EDGES_ID :
continue
id = len(NODES_ID) + len(EDGES_ID)
fd.write( "<edge id=\"%d\" label=\"%s\" source=\"%d\" target=\"%d\">\n" % (id,
label,
NODES_ID[ j.get_method().get_class_name() + bb1.name + j.get_method().get_descriptor() ],
METHODS_ID[ m.get_info() + j.get_name() + j.get_descriptor() ]) )
cl = EDGE_GRAPHIC["fcg"]
fd.write("<graphics width=\"%d\" fill=\"%s\">\n" % (cl["width"], cl["fill"]) )
fd.write("</graphics>\n")
fd.write("</edge>\n")
EDGES_ID[ label ] = id
def export_xgmml_efcg(a, x, fd) :
classes = a.get_classes_names()
# Methods flow graph
for m, _ in x.tainted_packages.get_packages() :
paths = m.get_methods()
for j in paths :
if j.get_method().get_class_name() in classes and m.get_info() not in classes :
if j.get_access_flag() == analysis.TAINTED_PACKAGE_CALL :
t = m.get_info() + j.get_name() + j.get_descriptor()
if t not in EXTERNAL_METHODS_ID :
fd.write("<node id=\"%d\" label=\"%s\">\n" % (len(NODES_ID), escape(t)))
fd.write("<att type=\"string\" name=\"classname\" value=\"%s\"/>\n" % (escape(m.get_info())))
fd.write("<att type=\"string\" name=\"name\" value=\"%s\"/>\n" % (escape(j.get_name())))
fd.write("<att type=\"string\" name=\"descriptor\" value=\"%s\"/>\n" % (escape(j.get_descriptor())))
cl = NODE_GRAPHIC["extern"]
fd.write("<att type=\"string\" name=\"node.label\" value=\"%s\\n%s\\n%s\"/>\n" % (escape(m.get_info()), escape(j.get_name()), escape(j.get_descriptor())))
fd.write("<graphics type=\"%s\" h=\"%.1f\" w=\"%.1f\" width=\"%d\" fill=\"%s\" outline=\"%s\">\n" % ( cl["type"], cl["h"], cl["h"], cl["width"], cl["fill"], cl["outline"]))
fd.write("</graphics>\n")
fd.write("</node>\n")
NODES_ID[ t ] = len(NODES_ID)
EXTERNAL_METHODS_ID[ t ] = NODES_ID[ t ]
bb1 = x.hmethods[ j.get_method() ].basic_blocks.get_basic_block( j.get_idx() )
node1 = get_node_name(j.get_method(), bb1) + "@0x%x" % j.get_idx()
node2 = "%s-%s-%s" % (m.get_info(), escape(j.get_name()), escape(j.get_descriptor()))
label = "%s (efcg) %s" % (node1, node2)
if label in EDGES_ID :
continue
id = len(NODES_ID) + len(EDGES_ID)
fd.write( "<edge id=\"%d\" label=\"%s\" source=\"%d\" target=\"%d\">\n" % (id,
label,
NODES_ID[ j.get_method().get_class_name() + bb1.name + j.get_method().get_descriptor() ],
EXTERNAL_METHODS_ID[ m.get_info() + j.get_name() + j.get_descriptor() ]) )
cl = EDGE_GRAPHIC["efcg"]
fd.write("<graphics width=\"%d\" fill=\"%s\">\n" % (cl["width"], cl["fill"]) )
fd.write("</graphics>\n")
fd.write("</edge>\n")
EDGES_ID[ label ] = id
def export_apps_to_xgmml( input, output, fcg, efcg ) :
a = Androguard( [ input ] )
fd = open(output, "w")
fd.write("<?xml version='1.0'?>\n")
fd.write("<graph label=\"Androguard XGMML %s\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns1=\"http://www.w3.org/1999/xlink\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns=\"http://www.cs.rpi.edu/XGMML\" directed=\"1\">\n" % (os.path.basename(input)))
for vm in a.get_vms() :
x = analysis.VMAnalysis( vm )
# CFG
for method in vm.get_methods() :
g = x.hmethods[ method ]
export_xgmml_cfg(g, fd)
if fcg :
export_xgmml_fcg(vm, x, fd)
if efcg :
export_xgmml_efcg(vm, x, fd)
fd.write("</graph>")
fd.close()
def main(options, arguments) :
if options.input != None and options.output != None :
export_apps_to_xgmml( options.input, options.output, options.functions, options.externals )
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys
from optparse import OptionParser
from androguard.core.bytecodes import apk, dvm
from androguard.core.analysis import analysis
from androguard.core import androconf
sys.path.append("./elsim")
from elsim import elsim
from elsim.elsim_dalvik import ProxyDalvik, FILTERS_DALVIK_SIM, ProxyDalvikMethod, FILTERS_DALVIK_BB
from elsim.elsim_dalvik import ProxyDalvikBasicBlock, FILTERS_DALVIK_DIFF_BB
from elsim.elsim_dalvik import DiffDalvikMethod
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use these filenames', 'nargs' : 2 }
option_1 = { 'name' : ('-t', '--threshold'), 'help' : 'define the threshold', 'nargs' : 1 }
option_2 = { 'name' : ('-c', '--compressor'), 'help' : 'define the compressor', 'nargs' : 1 }
option_3 = { 'name' : ('-d', '--display'), 'help' : 'display the file in human readable format', 'action' : 'count' }
#option_4 = { 'name' : ('-e', '--exclude'), 'help' : 'exclude specific blocks (0 : orig, 1 : diff, 2 : new)', 'nargs' : 1 }
option_5 = { 'name' : ('-e', '--exclude'), 'help' : 'exclude specific class name (python regexp)', 'nargs' : 1 }
option_6 = { 'name' : ('-s', '--size'), 'help' : 'exclude specific method below the specific size', 'nargs' : 1 }
option_7 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_5, option_6, option_7]
def main(options, arguments) :
details = False
if options.display != None :
details = True
if options.input != None :
ret_type = androconf.is_android( options.input[0] )
if ret_type == "APK" :
a = apk.APK( options.input[0] )
d1 = dvm.DalvikVMFormat( a.get_dex() )
elif ret_type == "DEX" :
d1 = dvm.DalvikVMFormat( open(options.input[0], "rb").read() )
dx1 = analysis.VMAnalysis( d1 )
ret_type = androconf.is_android( options.input[1] )
if ret_type == "APK" :
a = apk.APK( options.input[1] )
d2 = dvm.DalvikVMFormat( a.get_dex() )
elif ret_type == "DEX" :
d2 = dvm.DalvikVMFormat( open(options.input[1], "rb").read() )
dx2 = analysis.VMAnalysis( d2 )
print d1, dx1, d2, dx2
sys.stdout.flush()
threshold = None
if options.threshold != None :
threshold = float(options.threshold)
FS = FILTERS_DALVIK_SIM
FS[elsim.FILTER_SKIPPED_METH].set_regexp( options.exclude )
FS[elsim.FILTER_SKIPPED_METH].set_size( options.size )
el = elsim.Elsim( ProxyDalvik(d1, dx1), ProxyDalvik(d2, dx2), FS, threshold, options.compressor )
el.show()
e1 = elsim.split_elements( el, el.get_similar_elements() )
for i in e1 :
j = e1[ i ]
elb = elsim.Elsim( ProxyDalvikMethod(i), ProxyDalvikMethod(j), FILTERS_DALVIK_BB, threshold, options.compressor )
#elb.show()
eld = elsim.Eldiff( ProxyDalvikBasicBlock(elb), FILTERS_DALVIK_DIFF_BB )
#eld.show()
ddm = DiffDalvikMethod( i, j, elb, eld )
ddm.show()
print "NEW METHODS"
enew = el.get_new_elements()
for i in enew :
el.show_element( i, False )
print "DELETED METHODS"
edel = el.get_deleted_elements()
for i in edel :
el.show_element( i )
elif options.version != None :
print "Androdiff version %s" % androconf.ANDROGUARD_VERSION
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys
from androguard.core import androconf
sys.path.append("./elsim/")
from elsim.elsign import dalvik_elsign
from optparse import OptionParser
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use this filename', 'nargs' : 1 }
option_1 = { 'name' : ('-r', '--remove'), 'help' : 'remote the signature', 'nargs' : 1 }
option_2 = { 'name' : ('-o', '--output'), 'help' : 'output database', 'nargs' : 1 }
option_3 = { 'name' : ('-l', '--list'), 'help' : 'list signatures in database', 'nargs' : 1 }
option_4 = { 'name' : ('-c', '--check'), 'help' : 'check signatures in database', 'nargs' : 1 }
option_5 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_4, option_5]
def main(options, arguments) :
s = dalvik_elsign.CSignature(pcs=dalvik_elsign.PublicCSignature)
if options.input != None :
ret = s.add_file( open( options.input, "rb" ).read() )
if ret != None and options.output != None :
s.add_indb( ret, options.output )
elif options.list != None :
s.list_indb( options.list )
elif options.remove != None :
s.remove_indb( options.remove, options.output )
elif options.check != None :
s.check_db( options.check )
elif options.version != None :
print "Androcsign version %s" % androconf.ANDROGUARD_VERSION
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys, os
from optparse import OptionParser
from androguard.core import androconf
from androguard.core.bytecodes import apk
from androguard.core.bytecodes import dvm
from androguard.core.analysis import analysis
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use this filename (APK)', 'nargs' : 1 }
option_1 = { 'name' : ('-d', '--directory'), 'help' : 'directory : use this directory', 'nargs' : 1 }
option_2 = { 'name' : ('-t', '--tag'), 'help' : 'display tags', 'action' : 'count' }
option_3 = { 'name' : ('-v', '--version'), 'help' : 'version', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3]
def display_dvm_info(apk) :
vm = dvm.DalvikVMFormat( apk.get_dex() )
vmx = analysis.VMAnalysis( vm )
print "Native code:", analysis.is_native_code(vmx)
print "Dynamic code:", analysis.is_dyn_code(vmx)
print "Reflection code:", analysis.is_reflection_code(vmx)
print analysis.TAG_ANDROID
vmx.create_tags()
for i in vmx.get_methods() :
if not i.tags.empty() :
print i.method.get_class_name(), i.method.get_name(), i.tags
def main(options, arguments) :
if options.input != None :
ret_type = androconf.is_android( options.input )
print os.path.basename(options.input), ":"
if ret_type == "APK" :
try :
a = apk.APK( options.input )
if a.is_valid_APK() :
a.show()
display_dvm_info( a )
else :
print "INVALID"
except Exception, e :
print "ERROR", e
elif options.directory != None :
for root, dirs, files in os.walk( options.directory, followlinks=True ) :
if files != [] :
for f in files :
real_filename = root
if real_filename[-1] != "/" :
real_filename += "/"
real_filename += f
ret_type = androconf.is_android( real_filename )
if ret_type == "APK" :
print os.path.basename( real_filename ), ":"
try :
a = apk.APK( real_filename )
if a.is_valid_APK() :
a.show()
display_dvm_info( a )
else :
print "INVALID APK"
raise("ooos")
except Exception, e :
print "ERROR", e
raise("ooos")
elif options.version != None :
print "Androapkinfo version %s" % androconf.ANDROGUARD_VERSION
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys, os
from optparse import OptionParser
from androguard.core.bytecodes import apk, dvm
from androguard.core.data import data
from androguard.core.analysis import analysis, ganalysis
from androguard.core import androconf
option_0 = { 'name' : ('-i', '--input'), 'help' : 'filename input (dex, apk)', 'nargs' : 1 }
option_1 = { 'name' : ('-o', '--output'), 'help' : 'directory output', 'nargs' : 1 }
options = [option_0, option_1]
def create_directory( class_name, output ) :
output_name = output
if output_name[-1] != "/" :
output_name = output_name + "/"
try :
os.makedirs( output_name + class_name )
except OSError :
pass
def create_directories( vm, output ) :
for class_name in vm.get_classes_names() :
z = os.path.split( class_name )[0]
create_directory( z[1:], output )
def main(options, arguments) :
if options.input != None and options.output != None :
ret_type = androconf.is_android( options.input )
vm = None
a = None
if ret_type == "APK" :
a = apk.APK( options.input )
if a.is_valid_APK() :
vm = dvm.DalvikVMFormat( a.get_dex() )
else :
print "INVALID APK"
elif ret_type == "DEX" :
try :
vm = dvm.DalvikVMFormat( open(options.input, "rb").read() )
except Exception, e :
print "INVALID DEX", e
vmx = analysis.VMAnalysis( vm )
gvmx = ganalysis.GVMAnalysis( vmx, a )
create_directories( vm, options.output )
# dv.export_to_gml( options.output )
dd = data.Data(vm, vmx, gvmx, a)
buff = dd.export_apk_to_gml()
androconf.save_to_disk( buff, options.output + "/" + "apk.graphml" )
buff = dd.export_methodcalls_to_gml()
androconf.save_to_disk( buff, options.output + "/" + "methodcalls.graphml" )
buff = dd.export_dex_to_gml()
for i in buff :
androconf.save_to_disk( buff[i], options.output + "/" + i + ".graphml" )
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys, os
from optparse import OptionParser
from androguard.core.androgen import Androguard
from androguard.core import androconf
from androguard.core.analysis import analysis
from androguard.core.bytecode import method2dot, method2format
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use this filename', 'nargs' : 1 }
option_1 = { 'name' : ('-o', '--output'), 'help' : 'base directory to output all files', 'nargs' : 1 }
option_2 = { 'name' : ('-d', '--dot'), 'help' : 'write the method in dot format', 'action' : 'count' }
option_3 = { 'name' : ('-f', '--format'), 'help' : 'write the method in specific format (png, ...)', 'nargs' : 1 }
option_4 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_4]
def valid_class_name( class_name ):
if class_name[-1] == ";" :
return class_name[1:-1]
return class_name
def create_directory( class_name, output ) :
output_name = output
if output_name[-1] != "/" :
output_name = output_name + "/"
try :
os.makedirs( output_name + class_name )
except OSError :
pass
def create_directories( a, output ) :
for vm in a.get_vms() :
for class_name in vm.get_classes_names() :
create_directory( valid_class_name( class_name ), output )
def export_apps_to_format( a, output, dot=None, _format=None ) :
output_name = output
if output_name[-1] != "/" :
output_name = output_name + "/"
for vm in a.get_vms() :
x = analysis.VMAnalysis( vm )
for method in vm.get_methods() :
filename = output_name + valid_class_name( method.get_class_name() )
if filename[-1] != "/" :
filename = filename + "/"
descriptor = method.get_descriptor()
descriptor = descriptor.replace(";", "")
descriptor = descriptor.replace(" ", "")
descriptor = descriptor.replace("(", "-")
descriptor = descriptor.replace(")", "-")
descriptor = descriptor.replace("/", "_")
filename = filename + method.get_name() + descriptor
buff = method2dot( x.get_method( method ) )
if dot :
fd = open( filename + ".dot", "w")
fd.write( buff )
fd.close()
if _format :
method2format( filename + "." + _format, _format, raw = buff )
def main(options, arguments) :
if options.input != None and options.output != None :
a = Androguard( [ options.input ] )
if options.dot != None or options.format != None :
create_directories( a, options.output )
export_apps_to_format( a, options.output, options.dot, options.format )
else :
print "Please, specify a format or dot option"
elif options.version != None :
print "Androdd version %s" % androconf.ANDROGUARD_VERSION
else :
print "Please, specify an input file and an output directory"
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This script is useful for taking the output of memdump() and
# converting it back into binary output. This can be useful, for
# example, when one wants to push that data into other tools like
# objdump or hexdump.
#
# (C) Copyright 2010 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys
import struct
def unhex(str):
return int(str, 16)
def parseMem(filehdl):
mem = []
for line in filehdl:
parts = line.split(':')
if len(parts) < 2:
continue
try:
vaddr = unhex(parts[0])
parts = parts[1].split()
mem.extend([unhex(v) for v in parts])
except ValueError:
continue
return mem
def printUsage():
sys.stderr.write("Usage:\n %s <file | ->\n"
% (sys.argv[0],))
sys.exit(1)
def main():
if len(sys.argv) != 2:
printUsage()
filename = sys.argv[1]
if filename == '-':
filehdl = sys.stdin
else:
filehdl = open(filename, 'r')
mem = parseMem(filehdl)
for i in mem:
sys.stdout.write(struct.pack("<I", i))
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
# Fill in checksum/size of an option rom, and pad it to proper length.
#
# Copyright (C) 2009 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys
def alignpos(pos, alignbytes):
mask = alignbytes - 1
return (pos + mask) & ~mask
def checksum(data):
ords = map(ord, data)
return sum(ords)
def main():
inname = sys.argv[1]
outname = sys.argv[2]
# Read data in
f = open(inname, 'rb')
data = f.read()
count = len(data)
# Pad to a 512 byte boundary
data += "\0" * (alignpos(count, 512) - count)
count = len(data)
# Check if a pci header is present
pcidata = ord(data[24:25]) + (ord(data[25:26]) << 8)
if pcidata != 0:
data = data[:pcidata + 16] + chr(count/512) + chr(0) + data[pcidata + 18:]
# Fill in size field; clear checksum field
data = data[:2] + chr(count/512) + data[3:6] + "\0" + data[7:]
# Checksum rom
newsum = (256 - checksum(data)) & 0xff
data = data[:6] + chr(newsum) + data[7:]
# Write new rom
f = open(outname, 'wb')
f.write(data)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
# Copyright (C) 2011 Red Hat, Inc., Michael S. Tsirkin <mst@redhat.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# Read a preprocessed ASL listing and put each ACPI_EXTRACT
# directive in a comment, to make iasl skip it.
# We also put each directive on a new line, the machinery
# in tools/acpi_extract.py requires this.
import re;
import sys;
import fileinput;
def die(diag):
sys.stderr.write("Error: %s\n" % (diag))
sys.exit(1)
# Note: () around pattern make split return matched string as part of list
psplit = re.compile(r''' (
\b # At word boundary
ACPI_EXTRACT_\w+ # directive
\s+ # some whitespace
\w+ # array name
)''', re.VERBOSE);
lineno = 0
for line in fileinput.input():
# line number and debug string to output in case of errors
lineno = lineno + 1
debug = "input line %d: %s" % (lineno, line.rstrip())
s = psplit.split(line);
# The way split works, each odd item is the matching ACPI_EXTRACT directive.
# Put each in a comment, and on a line by itself.
for i in range(len(s)):
if (i % 2):
sys.stdout.write("\n/* %s */\n" % s[i])
else:
sys.stdout.write(s[i])
| Python |
#!/usr/bin/env python
# Script to check a bios image and report info on it.
#
# Copyright (C) 2008 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys
import layoutrom
def main():
# Get args
objinfo, rawfile, outfile = sys.argv[1:]
# Read in symbols
objinfofile = open(objinfo, 'rb')
symbols = layoutrom.parseObjDump(objinfofile, 'in')[1]
# Read in raw file
f = open(rawfile, 'rb')
rawdata = f.read()
f.close()
datasize = len(rawdata)
finalsize = 64*1024
if datasize > 64*1024:
finalsize = 128*1024
if datasize > 128*1024:
finalsize = 256*1024
# Sanity checks
start = symbols['code32flat_start'].offset
end = symbols['code32flat_end'].offset
expend = layoutrom.BUILD_BIOS_ADDR + layoutrom.BUILD_BIOS_SIZE
if end != expend:
print "Error! Code does not end at 0x%x (got 0x%x)" % (
expend, end)
sys.exit(1)
if datasize > finalsize:
print "Error! Code is too big (0x%x vs 0x%x)" % (
datasize, finalsize)
sys.exit(1)
expdatasize = end - start
if datasize != expdatasize:
print "Error! Unknown extra data (0x%x vs 0x%x)" % (
datasize, expdatasize)
sys.exit(1)
# Print statistics
runtimesize = datasize
if '_reloc_abs_start' in symbols:
runtimesize = end - symbols['code32init_end'].offset
print "Total size: %d Fixed: %d Free: %d (used %.1f%% of %dKiB rom)" % (
datasize, runtimesize, finalsize - datasize
, (datasize / float(finalsize)) * 100.0
, finalsize / 1024)
# Write final file
f = open(outfile, 'wb')
f.write(("\0" * (finalsize - datasize)) + rawdata)
f.close()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
# Script that can read from a serial device and show timestamps.
#
# Copyright (C) 2009 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# Usage:
# tools/readserial.py /dev/ttyUSB0 115200
import sys
import time
import select
import optparse
# Reset time counter after this much idle time.
RESTARTINTERVAL = 60
# Number of bits in a transmitted byte - 8N1 is 1 start bit + 8 data
# bits + 1 stop bit.
BITSPERBYTE = 10
def calibrateserialwrite(outfile, byteadjust):
# Build 4000 bytes of dummy data.
data = "0123456789" * 4 + "012345678" + "\n"
data = data * 80
while 1:
st = time.time()
outfile.write(data)
outfile.flush()
et = time.time()
sys.stdout.write(
"Wrote %d - %.1fus per char (theory states %.1fus)\n" % (
len(data), (et-st) / len(data) * 1000000, byteadjust * 1000000))
sys.stdout.flush()
time.sleep(3)
def calibrateserialread(infile, byteadjust):
starttime = lasttime = 0
totalchars = 0
while 1:
select.select([infile], [], [])
d = infile.read(4096)
curtime = time.time()
if curtime - lasttime > 1.0:
if starttime and totalchars:
sys.stdout.write(
"Calibrating on %d bytes - %.1fus per char"
" (theory states %.1fus)\n" % (
totalchars,
float(lasttime - starttime) * 1000000 / totalchars,
byteadjust * 1000000))
totalchars = 0
starttime = curtime
else:
totalchars += len(d)
lasttime = curtime
def readserial(infile, logfile, byteadjust):
lasttime = 0
while 1:
# Read data
try:
res = select.select([infile, sys.stdin], [], [])
except KeyboardInterrupt:
sys.stdout.write("\n")
break
if sys.stdin in res[0]:
# Got keyboard input - force reset on next serial input
sys.stdin.read(1)
lasttime = 0
if len(res[0]) == 1:
continue
d = infile.read(4096)
if not d:
break
datatime = time.time()
datatime -= len(d) * byteadjust
# Reset start time if no data for some time
if datatime - lasttime > RESTARTINTERVAL:
starttime = datatime
charcount = 0
isnewline = 1
msg = "\n\n======= %s (adjust=%.1fus)\n" % (
time.asctime(time.localtime(datatime)), byteadjust * 1000000)
sys.stdout.write(msg)
logfile.write(msg)
lasttime = datatime
# Translate unprintable chars; add timestamps
out = ""
for c in d:
if isnewline:
delta = datatime - starttime - (charcount * byteadjust)
out += "%06.3f: " % delta
isnewline = 0
oc = ord(c)
charcount += 1
datatime += byteadjust
if oc == 0x0d:
continue
if oc == 0x00:
out += "<00>\n"
isnewline = 1
continue
if oc == 0x0a:
out += "\n"
isnewline = 1
continue
if oc < 0x20 or oc >= 0x7f and oc != 0x09:
out += "<%02x>" % oc
continue
out += c
sys.stdout.write(out)
sys.stdout.flush()
logfile.write(out)
logfile.flush()
def main():
usage = "%prog [options] [<serialdevice> [<baud>]]"
opts = optparse.OptionParser(usage)
opts.add_option("-f", "--file",
action="store_false", dest="serial", default=True,
help="read from file instead of serialdevice")
opts.add_option("-n", "--no-adjust",
action="store_false", dest="adjustbaud", default=True,
help="don't adjust times by serial rate")
opts.add_option("-c", "--calibrate-read",
action="store_true", dest="calibrate_read", default=False,
help="read from serial port to calibrate it")
opts.add_option("-C", "--calibrate-write",
action="store_true", dest="calibrate_write", default=False,
help="write to serial port to calibrate it")
opts.add_option("-t", "--time",
type="float", dest="time", default=None,
help="time to write one byte on serial port (in us)")
options, args = opts.parse_args()
serialport = 0
baud = 115200
if len(args) > 2:
opts.error("Too many arguments")
if len(args) > 0:
serialport = args[0]
if len(args) > 1:
baud = int(args[1])
byteadjust = float(BITSPERBYTE) / baud
if options.time is not None:
byteadjust = options.time / 1000000.0
if not options.adjustbaud:
byteadjust = 0.0
if options.serial:
# Read from serial port
try:
import serial
except ImportError:
print """
Unable to find pyserial package ( http://pyserial.sourceforge.net/ ).
On Linux machines try: yum install pyserial
Or: apt-get install python-serial
"""
sys.exit(1)
ser = serial.Serial(serialport, baud, timeout=0)
else:
# Read from a file
ser = open(serialport, 'rb')
import fcntl
import os
fcntl.fcntl(ser, fcntl.F_SETFL
, fcntl.fcntl(ser, fcntl.F_GETFL) | os.O_NONBLOCK)
if options.calibrate_read:
calibrateserialread(ser, byteadjust)
return
if options.calibrate_write:
calibrateserialwrite(ser, byteadjust)
return
logname = time.strftime("seriallog-%Y%m%d_%H%M%S.log")
f = open(logname, 'wb')
readserial(ser, f, byteadjust)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
# Script that tries to find how much stack space each function in an
# object is using.
#
# Copyright (C) 2008 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# Usage:
# objdump -m i386 -M i8086 -M suffix -d out/rom16.o | tools/checkstack.py
import sys
import re
# Functions that change stacks
STACKHOP = ['__send_disk_op']
# List of functions we can assume are never called.
#IGNORE = ['panic', '__dprintf']
IGNORE = ['panic']
OUTPUTDESC = """
#funcname1[preamble_stack_usage,max_usage_with_callers]:
# insn_addr:called_function [usage_at_call_point+caller_preamble,total_usage]
#
#funcname2[p,m,max_usage_to_yield_point]:
# insn_addr:called_function [u+c,t,usage_to_yield_point]
"""
# Find out maximum stack usage for a function
def calcmaxstack(funcs, funcaddr):
info = funcs[funcaddr]
# Find max of all nested calls.
maxusage = info[1]
maxyieldusage = doesyield = 0
if info[3] is not None:
maxyieldusage = info[3]
doesyield = 1
info[2] = maxusage
info[4] = info[3]
seenbefore = {}
totcalls = 0
for insnaddr, calladdr, usage in info[6]:
callinfo = funcs.get(calladdr)
if callinfo is None:
continue
if callinfo[2] is None:
calcmaxstack(funcs, calladdr)
if callinfo[0] not in seenbefore:
seenbefore[callinfo[0]] = 1
totcalls += 1 + callinfo[5]
funcnameroot = callinfo[0].split('.')[0]
if funcnameroot in IGNORE:
# This called function is ignored - don't contribute it to
# the max stack.
continue
if funcnameroot in STACKHOP:
if usage > maxusage:
maxusage = usage
if callinfo[4] is not None:
doesyield = 1
if usage > maxyieldusage:
maxyieldusage = usage
continue
totusage = usage + callinfo[2]
if totusage > maxusage:
maxusage = totusage
if callinfo[4] is not None:
doesyield = 1
totyieldusage = usage + callinfo[4]
if totyieldusage > maxyieldusage:
maxyieldusage = totyieldusage
info[2] = maxusage
if doesyield:
info[4] = maxyieldusage
info[5] = totcalls
# Try to arrange output so that functions that call each other are
# near each other.
def orderfuncs(funcaddrs, availfuncs):
l = [(availfuncs[funcaddr][5], availfuncs[funcaddr][0], funcaddr)
for funcaddr in funcaddrs if funcaddr in availfuncs]
l.sort()
l.reverse()
out = []
while l:
count, name, funcaddr = l.pop(0)
if funcaddr not in availfuncs:
continue
calladdrs = [calls[1] for calls in availfuncs[funcaddr][6]]
del availfuncs[funcaddr]
out = out + orderfuncs(calladdrs, availfuncs) + [funcaddr]
return out
# Update function info with a found "yield" point.
def noteYield(info, stackusage):
prevyield = info[3]
if prevyield is None or prevyield < stackusage:
info[3] = stackusage
# Update function info with a found "call" point.
def noteCall(info, subfuncs, insnaddr, calladdr, stackusage):
if (calladdr, stackusage) in subfuncs:
# Already noted a nearly identical call - ignore this one.
return
info[6].append((insnaddr, calladdr, stackusage))
subfuncs[(calladdr, stackusage)] = 1
hex_s = r'[0-9a-f]+'
re_func = re.compile(r'^(?P<funcaddr>' + hex_s + r') <(?P<func>.*)>:$')
re_asm = re.compile(
r'^[ ]*(?P<insnaddr>' + hex_s
+ r'):\t.*\t(addr32 )?(?P<insn>.+?)[ ]*((?P<calladdr>' + hex_s
+ r') <(?P<ref>.*)>)?$')
re_usestack = re.compile(
r'^(push[f]?[lw])|(sub.* [$](?P<num>0x' + hex_s + r'),%esp)$')
def calc():
# funcs[funcaddr] = [funcname, basicstackusage, maxstackusage
# , yieldusage, maxyieldusage, totalcalls
# , [(insnaddr, calladdr, stackusage), ...]]
funcs = {-1: ['<indirect>', 0, 0, None, None, 0, []]}
cur = None
atstart = 0
stackusage = 0
# Parse input lines
for line in sys.stdin.readlines():
m = re_func.match(line)
if m is not None:
# Found function
funcaddr = int(m.group('funcaddr'), 16)
funcs[funcaddr] = cur = [m.group('func'), 0, None, None, None, 0, []]
stackusage = 0
atstart = 1
subfuncs = {}
continue
m = re_asm.match(line)
if m is not None:
insn = m.group('insn')
im = re_usestack.match(insn)
if im is not None:
if insn.startswith('pushl') or insn.startswith('pushfl'):
stackusage += 4
continue
elif insn.startswith('pushw') or insn.startswith('pushfw'):
stackusage += 2
continue
stackusage += int(im.group('num'), 16)
if atstart:
if '%esp' in insn or insn.startswith('leal'):
# Still part of initial header
continue
cur[1] = stackusage
atstart = 0
insnaddr = m.group('insnaddr')
calladdr = m.group('calladdr')
if calladdr is None:
if insn.startswith('lcallw'):
noteCall(cur, subfuncs, insnaddr, -1, stackusage + 4)
noteYield(cur, stackusage + 4)
elif insn.startswith('int'):
noteCall(cur, subfuncs, insnaddr, -1, stackusage + 6)
noteYield(cur, stackusage + 6)
elif insn.startswith('sti'):
noteYield(cur, stackusage)
else:
# misc instruction
continue
else:
# Jump or call insn
calladdr = int(calladdr, 16)
ref = m.group('ref')
if '+' in ref:
# Inter-function jump.
pass
elif insn.startswith('j'):
# Tail call
noteCall(cur, subfuncs, insnaddr, calladdr, 0)
elif insn.startswith('calll'):
noteCall(cur, subfuncs, insnaddr, calladdr, stackusage + 4)
else:
print "unknown call", ref
noteCall(cur, subfuncs, insnaddr, calladdr, stackusage)
# Reset stack usage to preamble usage
stackusage = cur[1]
#print "other", repr(line)
# Calculate maxstackusage
for funcaddr, info in funcs.items():
if info[2] is not None:
continue
calcmaxstack(funcs, funcaddr)
# Sort functions for output
funcaddrs = orderfuncs(funcs.keys(), funcs.copy())
# Show all functions
print OUTPUTDESC
for funcaddr in funcaddrs:
name, basicusage, maxusage, yieldusage, maxyieldusage, count, calls = \
funcs[funcaddr]
if maxusage == 0 and maxyieldusage is None:
continue
yieldstr = ""
if maxyieldusage is not None:
yieldstr = ",%d" % maxyieldusage
print "\n%s[%d,%d%s]:" % (name, basicusage, maxusage, yieldstr)
for insnaddr, calladdr, stackusage in calls:
callinfo = funcs.get(calladdr, ("<unknown>", 0, 0, 0, None))
yieldstr = ""
if callinfo[4] is not None:
yieldstr = ",%d" % (stackusage + callinfo[4])
print " %04s:%-40s [%d+%d,%d%s]" % (
insnaddr, callinfo[0], stackusage, callinfo[1]
, stackusage+callinfo[2], yieldstr)
def main():
calc()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
# Copyright (C) 2011 Red Hat, Inc., Michael S. Tsirkin <mst@redhat.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# Process mixed ASL/AML listing (.lst file) produced by iasl -l
# Locate and execute ACPI_EXTRACT directives, output offset info
#
# Documentation of ACPI_EXTRACT_* directive tags:
#
# These directive tags output offset information from AML for BIOS runtime
# table generation.
# Each directive is of the form:
# ACPI_EXTRACT_<TYPE> <array_name> <Operator> (...)
# and causes the extractor to create an array
# named <array_name> with offset, in the generated AML,
# of an object of a given type in the following <Operator>.
#
# A directive must fit on a single code line.
#
# Object type in AML is verified, a mismatch causes a build failure.
#
# Directives and operators currently supported are:
# ACPI_EXTRACT_NAME_DWORD_CONST - extract a Dword Const object from Name()
# ACPI_EXTRACT_NAME_WORD_CONST - extract a Word Const object from Name()
# ACPI_EXTRACT_NAME_BYTE_CONST - extract a Byte Const object from Name()
# ACPI_EXTRACT_METHOD_STRING - extract a NameString from Method()
# ACPI_EXTRACT_NAME_STRING - extract a NameString from Name()
# ACPI_EXTRACT_PROCESSOR_START - start of Processor() block
# ACPI_EXTRACT_PROCESSOR_STRING - extract a NameString from Processor()
# ACPI_EXTRACT_PROCESSOR_END - offset at last byte of Processor() + 1
#
# ACPI_EXTRACT_ALL_CODE - create an array storing the generated AML bytecode
#
# ACPI_EXTRACT is not allowed anywhere else in code, except in comments.
import re;
import sys;
import fileinput;
aml = []
asl = []
output = {}
debug = ""
class asl_line:
line = None
lineno = None
aml_offset = None
def die(diag):
sys.stderr.write("Error: %s; %s\n" % (diag, debug))
sys.exit(1)
#Store an ASL command, matching AML offset, and input line (for debugging)
def add_asl(lineno, line):
l = asl_line()
l.line = line
l.lineno = lineno
l.aml_offset = len(aml)
asl.append(l)
#Store an AML byte sequence
#Verify that offset output by iasl matches # of bytes so far
def add_aml(offset, line):
o = int(offset, 16);
# Sanity check: offset must match size of code so far
if (o != len(aml)):
die("Offset 0x%x != 0x%x" % (o, len(aml)))
# Strip any trailing dots and ASCII dump after "
line = re.sub(r'\s*\.*\s*".*$',"", line)
# Strip traling whitespace
line = re.sub(r'\s+$',"", line)
# Strip leading whitespace
line = re.sub(r'^\s+',"", line)
# Split on whitespace
code = re.split(r'\s+', line)
for c in code:
# Require a legal hex number, two digits
if (not(re.search(r'^[0-9A-Fa-f][0-9A-Fa-f]$', c))):
die("Unexpected octet %s" % c);
aml.append(int(c, 16));
# Process aml bytecode array, decoding AML
def aml_pkglen_bytes(offset):
# PkgLength can be multibyte. Bits 8-7 give the # of extra bytes.
pkglenbytes = aml[offset] >> 6;
return pkglenbytes + 1
def aml_pkglen(offset):
pkgstart = offset
pkglenbytes = aml_pkglen_bytes(offset)
pkglen = aml[offset] & 0x3F
# If multibyte, first nibble only uses bits 0-3
if ((pkglenbytes > 0) and (pkglen & 0x30)):
die("PkgLen bytes 0x%x but first nibble 0x%x expected 0x0X" %
(pkglen, pkglen))
offset += 1
pkglenbytes -= 1
for i in range(pkglenbytes):
pkglen |= aml[offset + i] << (i * 8 + 4)
if (len(aml) < pkgstart + pkglen):
die("PckgLen 0x%x at offset 0x%x exceeds AML size 0x%x" %
(pkglen, offset, len(aml)))
return pkglen
# Given method offset, find its NameString offset
def aml_method_string(offset):
#0x14 MethodOp PkgLength NameString MethodFlags TermList
if (aml[offset] != 0x14):
die( "Method offset 0x%x: expected 0x14 actual 0x%x" %
(offset, aml[offset]));
offset += 1;
pkglenbytes = aml_pkglen_bytes(offset)
offset += pkglenbytes;
return offset;
# Given name offset, find its NameString offset
def aml_name_string(offset):
#0x08 NameOp NameString DataRef
if (aml[offset] != 0x08):
die( "Name offset 0x%x: expected 0x08 actual 0x%x" %
(offset, aml[offset]));
return offset + 1;
# Given data offset, find dword const offset
def aml_data_dword_const(offset):
#0x08 NameOp NameString DataRef
if (aml[offset] != 0x0C):
die( "Name offset 0x%x: expected 0x0C actual 0x%x" %
(offset, aml[offset]));
return offset + 1;
# Given data offset, find word const offset
def aml_data_word_const(offset):
#0x08 NameOp NameString DataRef
if (aml[offset] != 0x0B):
die( "Name offset 0x%x: expected 0x0B actual 0x%x" %
(offset, aml[offset]));
return offset + 1;
# Given data offset, find byte const offset
def aml_data_byte_const(offset):
#0x08 NameOp NameString DataRef
if (aml[offset] != 0x0A):
die( "Name offset 0x%x: expected 0x0A actual 0x%x" %
(offset, aml[offset]));
return offset + 1;
# Given name offset, find dword const offset
def aml_name_dword_const(offset):
return aml_data_dword_const(aml_name_string(offset) + 4)
# Given name offset, find word const offset
def aml_name_word_const(offset):
return aml_data_word_const(aml_name_string(offset) + 4)
# Given name offset, find byte const offset
def aml_name_byte_const(offset):
return aml_data_byte_const(aml_name_string(offset) + 4)
def aml_processor_start(offset):
#0x5B 0x83 ProcessorOp PkgLength NameString ProcID
if ((aml[offset] != 0x5B) or (aml[offset + 1] != 0x83)):
die( "Name offset 0x%x: expected 0x5B 0x83 actual 0x%x 0x%x" %
(offset, aml[offset], aml[offset + 1]));
return offset
def aml_processor_string(offset):
#0x5B 0x83 ProcessorOp PkgLength NameString ProcID
start = aml_processor_start(offset)
offset += 2
pkglenbytes = aml_pkglen_bytes(offset)
offset += pkglenbytes
return offset
def aml_processor_end(offset):
start = aml_processor_start(offset)
offset += 2
pkglenbytes = aml_pkglen_bytes(offset)
pkglen = aml_pkglen(offset)
return offset + pkglen
lineno = 0
for line in fileinput.input():
# Strip trailing newline
line = line.rstrip();
# line number and debug string to output in case of errors
lineno = lineno + 1
debug = "input line %d: %s" % (lineno, line)
#ASL listing: space, then line#, then ...., then code
pasl = re.compile('^\s+([0-9]+)\.\.\.\.\s*')
m = pasl.search(line)
if (m):
add_asl(lineno, pasl.sub("", line));
# AML listing: offset in hex, then ...., then code
paml = re.compile('^([0-9A-Fa-f]+)\.\.\.\.\s*')
m = paml.search(line)
if (m):
add_aml(m.group(1), paml.sub("", line))
# Now go over code
# Track AML offset of a previous non-empty ASL command
prev_aml_offset = -1
for i in range(len(asl)):
debug = "input line %d: %s" % (asl[i].lineno, asl[i].line)
l = asl[i].line
# skip if not an extract directive
a = len(re.findall(r'ACPI_EXTRACT', l))
if (not a):
# If not empty, store AML offset. Will be used for sanity checks
# IASL seems to put {}. at random places in the listing.
# Ignore any non-words for the purpose of this test.
m = re.search(r'\w+', l)
if (m):
prev_aml_offset = asl[i].aml_offset
continue
if (a > 1):
die("Expected at most one ACPI_EXTRACT per line, actual %d" % a)
mext = re.search(r'''
^\s* # leading whitespace
/\*\s* # start C comment
(ACPI_EXTRACT_\w+) # directive: group(1)
\s+ # whitspace separates directive from array name
(\w+) # array name: group(2)
\s*\*/ # end of C comment
\s*$ # trailing whitespace
''', l, re.VERBOSE)
if (not mext):
die("Stray ACPI_EXTRACT in input")
# previous command must have produced some AML,
# otherwise we are in a middle of a block
if (prev_aml_offset == asl[i].aml_offset):
die("ACPI_EXTRACT directive in the middle of a block")
directive = mext.group(1)
array = mext.group(2)
offset = asl[i].aml_offset
if (directive == "ACPI_EXTRACT_ALL_CODE"):
if array in output:
die("%s directive used more than once" % directive)
output[array] = aml
continue
if (directive == "ACPI_EXTRACT_NAME_DWORD_CONST"):
offset = aml_name_dword_const(offset)
elif (directive == "ACPI_EXTRACT_NAME_WORD_CONST"):
offset = aml_name_word_const(offset)
elif (directive == "ACPI_EXTRACT_NAME_BYTE_CONST"):
offset = aml_name_byte_const(offset)
elif (directive == "ACPI_EXTRACT_NAME_STRING"):
offset = aml_name_string(offset)
elif (directive == "ACPI_EXTRACT_METHOD_STRING"):
offset = aml_method_string(offset)
elif (directive == "ACPI_EXTRACT_PROCESSOR_START"):
offset = aml_processor_start(offset)
elif (directive == "ACPI_EXTRACT_PROCESSOR_STRING"):
offset = aml_processor_string(offset)
elif (directive == "ACPI_EXTRACT_PROCESSOR_END"):
offset = aml_processor_end(offset)
else:
die("Unsupported directive %s" % directive)
if array not in output:
output[array] = []
output[array].append(offset)
debug = "at end of file"
def get_value_type(maxvalue):
#Use type large enough to fit the table
if (maxvalue >= 0x10000):
return "int"
elif (maxvalue >= 0x100):
return "short"
else:
return "char"
# Pretty print output
for array in output.keys():
otype = get_value_type(max(output[array]))
odata = []
for value in output[array]:
odata.append("0x%x" % value)
sys.stdout.write("static unsigned %s %s[] = {\n" % (otype, array))
sys.stdout.write(",\n".join(odata))
sys.stdout.write('\n};\n');
| Python |
#!/usr/bin/env python
# Script to report the checksum of a file.
#
# Copyright (C) 2009 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys
def main():
data = sys.stdin.read()
ords = map(ord, data)
print "sum=%x\n" % sum(ords)
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
# Encode an integer in little endian format in a file.
#
# Copyright (C) 2011 Kevin O'Connor <kevin@koconnor.net>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import sys
import struct
def main():
filename = sys.argv[1]
value = int(sys.argv[2])
outval = struct.pack('<Q', value)
f = open(filename, 'wb')
f.write(outval)
f.close()
if __name__ == '__main__':
main()
| Python |
# *-*- Mode: Python -*-*
##
#
# Echo back a unique integer value, and prepend to response a
# leading sentinel byte (0xFF) the client can check scan for.
#
# This is used by clients talking to the guest agent over the
# wire to ensure the stream is in sync and doesn't contain stale
# data from previous client. It must be issued upon initial
# connection, and after any client-side timeouts (including
# timeouts on receiving a response to this command).
#
# After issuing this request, all guest agent responses should be
# ignored until the response containing the unique integer value
# the client passed in is returned. Receival of the 0xFF sentinel
# byte must be handled as an indication that the client's
# lexer/tokenizer/parser state should be flushed/reset in
# preparation for reliably receiving the subsequent response. As
# an optimization, clients may opt to ignore all data until a
# sentinel value is receiving to avoid unnecessary processing of
# stale data.
#
# Similarly, clients should also precede this *request*
# with a 0xFF byte to make sure the guest agent flushes any
# partially read JSON data from a previous client connection.
#
# @id: randomly generated 64-bit integer
#
# Returns: The unique integer id passed in by the client
#
# Since: 1.1
# ##
{ 'command': 'guest-sync-delimited'
'data': { 'id': 'int' },
'returns': 'int' }
##
# @guest-sync:
#
# Echo back a unique integer value
#
# This is used by clients talking to the guest agent over the
# wire to ensure the stream is in sync and doesn't contain stale
# data from previous client. All guest agent responses should be
# ignored until the provided unique integer value is returned,
# and it is up to the client to handle stale whole or
# partially-delivered JSON text in such a way that this response
# can be obtained.
#
# In cases where a partial stale response was previously
# received by the client, this cannot always be done reliably.
# One particular scenario being if qemu-ga responses are fed
# character-by-character into a JSON parser. In these situations,
# using guest-sync-delimited may be optimal.
#
# For clients that fetch responses line by line and convert them
# to JSON objects, guest-sync should be sufficient, but note that
# in cases where the channel is dirty some attempts at parsing the
# response may result in a parser error.
#
# Such clients should also precede this command
# with a 0xFF byte to make sure the guest agent flushes any
# partially read JSON data from a previous session.
#
# @id: randomly generated 64-bit integer
#
# Returns: The unique integer id passed in by the client
#
# Since: 0.15.0
##
{ 'command': 'guest-sync'
'data': { 'id': 'int' },
'returns': 'int' }
##
# @guest-ping:
#
# Ping the guest agent, a non-error return implies success
#
# Since: 0.15.0
##
{ 'command': 'guest-ping' }
##
# @GuestAgentCommandInfo:
#
# Information about guest agent commands.
#
# @name: name of the command
#
# @enabled: whether command is currently enabled by guest admin
#
# Since 1.1.0
##
{ 'type': 'GuestAgentCommandInfo',
'data': { 'name': 'str', 'enabled': 'bool' } }
##
# @GuestAgentInfo
#
# Information about guest agent.
#
# @version: guest agent version
#
# @supported_commands: Information about guest agent commands
#
# Since 0.15.0
##
{ 'type': 'GuestAgentInfo',
'data': { 'version': 'str',
'supported_commands': ['GuestAgentCommandInfo'] } }
##
# @guest-info:
#
# Get some information about the guest agent.
#
# Returns: @GuestAgentInfo
#
# Since: 0.15.0
##
{ 'command': 'guest-info',
'returns': 'GuestAgentInfo' }
##
# @guest-shutdown:
#
# Initiate guest-activated shutdown. Note: this is an asynchronous
# shutdown request, with no guarantee of successful shutdown.
#
# @mode: #optional "halt", "powerdown" (default), or "reboot"
#
# This command does NOT return a response on success. Success condition
# is indicated by the VM exiting with a zero exit status or, when
# running with --no-shutdown, by issuing the query-status QMP command
# to confirm the VM status is "shutdown".
#
# Since: 0.15.0
##
{ 'command': 'guest-shutdown', 'data': { '*mode': 'str' },
'success-response': 'no' }
##
# @guest-file-open:
#
# Open a file in the guest and retrieve a file handle for it
#
# @filepath: Full path to the file in the guest to open.
#
# @mode: #optional open mode, as per fopen(), "r" is the default.
#
# Returns: Guest file handle on success.
#
# Since: 0.15.0
##
{ 'command': 'guest-file-open',
'data': { 'path': 'str', '*mode': 'str' },
'returns': 'int' }
##
# @guest-file-close:
#
# Close an open file in the guest
#
# @handle: filehandle returned by guest-file-open
#
# Returns: Nothing on success.
#
# Since: 0.15.0
##
{ 'command': 'guest-file-close',
'data': { 'handle': 'int' } }
##
# @GuestFileRead
#
# Result of guest agent file-read operation
#
# @count: number of bytes read (note: count is *before*
# base64-encoding is applied)
#
# @buf-b64: base64-encoded bytes read
#
# @eof: whether EOF was encountered during read operation.
#
# Since: 0.15.0
##
{ 'type': 'GuestFileRead',
'data': { 'count': 'int', 'buf-b64': 'str', 'eof': 'bool' } }
##
# @guest-file-read:
#
# Read from an open file in the guest. Data will be base64-encoded
#
# @handle: filehandle returned by guest-file-open
#
# @count: #optional maximum number of bytes to read (default is 4KB)
#
# Returns: @GuestFileRead on success.
#
# Since: 0.15.0
##
{ 'command': 'guest-file-read',
'data': { 'handle': 'int', '*count': 'int' },
'returns': 'GuestFileRead' }
##
# @GuestFileWrite
#
# Result of guest agent file-write operation
#
# @count: number of bytes written (note: count is actual bytes
# written, after base64-decoding of provided buffer)
#
# @eof: whether EOF was encountered during write operation.
#
# Since: 0.15.0
##
{ 'type': 'GuestFileWrite',
'data': { 'count': 'int', 'eof': 'bool' } }
##
# @guest-file-write:
#
# Write to an open file in the guest.
#
# @handle: filehandle returned by guest-file-open
#
# @buf-b64: base64-encoded string representing data to be written
#
# @count: #optional bytes to write (actual bytes, after base64-decode),
# default is all content in buf-b64 buffer after base64 decoding
#
# Returns: @GuestFileWrite on success.
#
# Since: 0.15.0
##
{ 'command': 'guest-file-write',
'data': { 'handle': 'int', 'buf-b64': 'str', '*count': 'int' },
'returns': 'GuestFileWrite' }
##
# @GuestFileSeek
#
# Result of guest agent file-seek operation
#
# @position: current file position
#
# @eof: whether EOF was encountered during file seek
#
# Since: 0.15.0
##
{ 'type': 'GuestFileSeek',
'data': { 'position': 'int', 'eof': 'bool' } }
##
# @guest-file-seek:
#
# Seek to a position in the file, as with fseek(), and return the
# current file position afterward. Also encapsulates ftell()'s
# functionality, just Set offset=0, whence=SEEK_CUR.
#
# @handle: filehandle returned by guest-file-open
#
# @offset: bytes to skip over in the file stream
#
# @whence: SEEK_SET, SEEK_CUR, or SEEK_END, as with fseek()
#
# Returns: @GuestFileSeek on success.
#
# Since: 0.15.0
##
{ 'command': 'guest-file-seek',
'data': { 'handle': 'int', 'offset': 'int', 'whence': 'int' },
'returns': 'GuestFileSeek' }
##
# @guest-file-flush:
#
# Write file changes bufferred in userspace to disk/kernel buffers
#
# @handle: filehandle returned by guest-file-open
#
# Returns: Nothing on success.
#
# Since: 0.15.0
##
{ 'command': 'guest-file-flush',
'data': { 'handle': 'int' } }
##
# @GuestFsFreezeStatus
#
# An enumation of filesystem freeze states
#
# @thawed: filesystems thawed/unfrozen
#
# @frozen: all non-network guest filesystems frozen
#
# Since: 0.15.0
##
{ 'enum': 'GuestFsfreezeStatus',
'data': [ 'thawed', 'frozen' ] }
##
# @guest-fsfreeze-status:
#
# Get guest fsfreeze state. error state indicates
#
# Returns: GuestFsfreezeStatus ("thawed", "frozen", etc., as defined below)
#
# Note: This may fail to properly report the current state as a result of
# some other guest processes having issued an fs freeze/thaw.
#
# Since: 0.15.0
##
{ 'command': 'guest-fsfreeze-status',
'returns': 'GuestFsfreezeStatus' }
##
# @guest-fsfreeze-freeze:
#
# Sync and freeze all freezable, local guest filesystems
#
# Returns: Number of file systems currently frozen. On error, all filesystems
# will be thawed.
#
# Since: 0.15.0
##
{ 'command': 'guest-fsfreeze-freeze',
'returns': 'int' }
##
# @guest-fsfreeze-thaw:
#
# Unfreeze all frozen guest filesystems
#
# Returns: Number of file systems thawed by this call
#
# Note: if return value does not match the previous call to
# guest-fsfreeze-freeze, this likely means some freezable
# filesystems were unfrozen before this call, and that the
# filesystem state may have changed before issuing this
# command.
#
# Since: 0.15.0
##
{ 'command': 'guest-fsfreeze-thaw',
'returns': 'int' }
##
# @guest-suspend-disk
#
# Suspend guest to disk.
#
# This command tries to execute the scripts provided by the pm-utils package.
# If it's not available, the suspend operation will be performed by manually
# writing to a sysfs file.
#
# For the best results it's strongly recommended to have the pm-utils
# package installed in the guest.
#
# This command does NOT return a response on success. There is a high chance
# the command succeeded if the VM exits with a zero exit status or, when
# running with --no-shutdown, by issuing the query-status QMP command to
# to confirm the VM status is "shutdown". However, the VM could also exit
# (or set its status to "shutdown") due to other reasons.
#
# The following errors may be returned:
# If suspend to disk is not supported, Unsupported
#
# Notes: It's strongly recommended to issue the guest-sync command before
# sending commands when the guest resumes
#
# Since: 1.1
##
{ 'command': 'guest-suspend-disk', 'success-response': 'no' }
##
# @guest-suspend-ram
#
# Suspend guest to ram.
#
# This command tries to execute the scripts provided by the pm-utils package.
# If it's not available, the suspend operation will be performed by manually
# writing to a sysfs file.
#
# For the best results it's strongly recommended to have the pm-utils
# package installed in the guest.
#
# IMPORTANT: guest-suspend-ram requires QEMU to support the 'system_wakeup'
# command. Thus, it's *required* to query QEMU for the presence of the
# 'system_wakeup' command before issuing guest-suspend-ram.
#
# This command does NOT return a response on success. There are two options
# to check for success:
# 1. Wait for the SUSPEND QMP event from QEMU
# 2. Issue the query-status QMP command to confirm the VM status is
# "suspended"
#
# The following errors may be returned:
# If suspend to ram is not supported, Unsupported
#
# Notes: It's strongly recommended to issue the guest-sync command before
# sending commands when the guest resumes
#
# Since: 1.1
##
{ 'command': 'guest-suspend-ram', 'success-response': 'no' }
##
# @guest-suspend-hybrid
#
# Save guest state to disk and suspend to ram.
#
# This command requires the pm-utils package to be installed in the guest.
#
# IMPORTANT: guest-suspend-hybrid requires QEMU to support the 'system_wakeup'
# command. Thus, it's *required* to query QEMU for the presence of the
# 'system_wakeup' command before issuing guest-suspend-hybrid.
#
# This command does NOT return a response on success. There are two options
# to check for success:
# 1. Wait for the SUSPEND QMP event from QEMU
# 2. Issue the query-status QMP command to confirm the VM status is
# "suspended"
#
# The following errors may be returned:
# If hybrid suspend is not supported, Unsupported
#
# Notes: It's strongly recommended to issue the guest-sync command before
# sending commands when the guest resumes
#
# Since: 1.1
##
{ 'command': 'guest-suspend-hybrid', 'success-response': 'no' }
##
# @GuestIpAddressType:
#
# An enumeration of supported IP address types
#
# @ipv4: IP version 4
#
# @ipv6: IP version 6
#
# Since: 1.1
##
{ 'enum': 'GuestIpAddressType',
'data': [ 'ipv4', 'ipv6' ] }
##
# @GuestIpAddress:
#
# @ip-address: IP address
#
# @ip-address-type: Type of @ip-address (e.g. ipv4, ipv6)
#
# @prefix: Network prefix length of @ip-address
#
# Since: 1.1
##
{ 'type': 'GuestIpAddress',
'data': {'ip-address': 'str',
'ip-address-type': 'GuestIpAddressType',
'prefix': 'int'} }
##
# @GuestNetworkInterface:
#
# @name: The name of interface for which info are being delivered
#
# @hardware-address: Hardware address of @name
#
# @ip-addresses: List of addresses assigned to @name
#
# Since: 1.1
##
{ 'type': 'GuestNetworkInterface',
'data': {'name': 'str',
'*hardware-address': 'str',
'*ip-addresses': ['GuestIpAddress'] } }
##
# @guest-network-get-interfaces:
#
# Get list of guest IP addresses, MAC addresses
# and netmasks.
#
# Returns: List of GuestNetworkInfo on success.
#
# Since: 1.1
##
{ 'command': 'guest-network-get-interfaces',
'returns': ['GuestNetworkInterface'] }
| Python |
# -*- Mode: Python -*-
#
# QAPI Schema
##
# @NameInfo:
#
# Guest name information.
#
# @name: #optional The name of the guest
#
# Since 0.14.0
##
{ 'type': 'NameInfo', 'data': {'*name': 'str'} }
##
# @query-name:
#
# Return the name information of a guest.
#
# Returns: @NameInfo of the guest
#
# Since 0.14.0
##
{ 'command': 'query-name', 'returns': 'NameInfo' }
##
# @VersionInfo:
#
# A description of QEMU's version.
#
# @qemu.major: The major version of QEMU
#
# @qemu.minor: The minor version of QEMU
#
# @qemu.micro: The micro version of QEMU. By current convention, a micro
# version of 50 signifies a development branch. A micro version
# greater than or equal to 90 signifies a release candidate for
# the next minor version. A micro version of less than 50
# signifies a stable release.
#
# @package: QEMU will always set this field to an empty string. Downstream
# versions of QEMU should set this to a non-empty string. The
# exact format depends on the downstream however it highly
# recommended that a unique name is used.
#
# Since: 0.14.0
##
{ 'type': 'VersionInfo',
'data': {'qemu': {'major': 'int', 'minor': 'int', 'micro': 'int'},
'package': 'str'} }
##
# @query-version:
#
# Returns the current version of QEMU.
#
# Returns: A @VersionInfo object describing the current version of QEMU.
#
# Since: 0.14.0
##
{ 'command': 'query-version', 'returns': 'VersionInfo' }
##
# @KvmInfo:
#
# Information about support for KVM acceleration
#
# @enabled: true if KVM acceleration is active
#
# @present: true if KVM acceleration is built into this executable
#
# Since: 0.14.0
##
{ 'type': 'KvmInfo', 'data': {'enabled': 'bool', 'present': 'bool'} }
##
# @query-kvm:
#
# Returns information about KVM acceleration
#
# Returns: @KvmInfo
#
# Since: 0.14.0
##
{ 'command': 'query-kvm', 'returns': 'KvmInfo' }
##
# @RunState
#
# An enumation of VM run states.
#
# @debug: QEMU is running on a debugger
#
# @finish-migrate: guest is paused to finish the migration process
#
# @inmigrate: guest is paused waiting for an incoming migration
#
# @internal-error: An internal error that prevents further guest execution
# has occurred
#
# @io-error: the last IOP has failed and the device is configured to pause
# on I/O errors
#
# @paused: guest has been paused via the 'stop' command
#
# @postmigrate: guest is paused following a successful 'migrate'
#
# @prelaunch: QEMU was started with -S and guest has not started
#
# @restore-vm: guest is paused to restore VM state
#
# @running: guest is actively running
#
# @save-vm: guest is paused to save the VM state
#
# @shutdown: guest is shut down (and -no-shutdown is in use)
#
# @suspended: guest is suspended (ACPI S3)
#
# @watchdog: the watchdog action is configured to pause and has been triggered
##
{ 'enum': 'RunState',
'data': [ 'debug', 'inmigrate', 'internal-error', 'io-error', 'paused',
'postmigrate', 'prelaunch', 'finish-migrate', 'restore-vm',
'running', 'save-vm', 'shutdown', 'suspended', 'watchdog' ] }
##
# @StatusInfo:
#
# Information about VCPU run state
#
# @running: true if all VCPUs are runnable, false if not runnable
#
# @singlestep: true if VCPUs are in single-step mode
#
# @status: the virtual machine @RunState
#
# Since: 0.14.0
#
# Notes: @singlestep is enabled through the GDB stub
##
{ 'type': 'StatusInfo',
'data': {'running': 'bool', 'singlestep': 'bool', 'status': 'RunState'} }
##
# @query-status:
#
# Query the run status of all VCPUs
#
# Returns: @StatusInfo reflecting all VCPUs
#
# Since: 0.14.0
##
{ 'command': 'query-status', 'returns': 'StatusInfo' }
##
# @UuidInfo:
#
# Guest UUID information.
#
# @UUID: the UUID of the guest
#
# Since: 0.14.0
#
# Notes: If no UUID was specified for the guest, a null UUID is returned.
##
{ 'type': 'UuidInfo', 'data': {'UUID': 'str'} }
##
# @query-uuid:
#
# Query the guest UUID information.
#
# Returns: The @UuidInfo for the guest
#
# Since 0.14.0
##
{ 'command': 'query-uuid', 'returns': 'UuidInfo' }
##
# @ChardevInfo:
#
# Information about a character device.
#
# @label: the label of the character device
#
# @filename: the filename of the character device
#
# Notes: @filename is encoded using the QEMU command line character device
# encoding. See the QEMU man page for details.
#
# Since: 0.14.0
##
{ 'type': 'ChardevInfo', 'data': {'label': 'str', 'filename': 'str'} }
##
# @query-chardev:
#
# Returns information about current character devices.
#
# Returns: a list of @ChardevInfo
#
# Since: 0.14.0
##
{ 'command': 'query-chardev', 'returns': ['ChardevInfo'] }
##
# @CommandInfo:
#
# Information about a QMP command
#
# @name: The command name
#
# Since: 0.14.0
##
{ 'type': 'CommandInfo', 'data': {'name': 'str'} }
##
# @query-commands:
#
# Return a list of supported QMP commands by this server
#
# Returns: A list of @CommandInfo for all supported commands
#
# Since: 0.14.0
##
{ 'command': 'query-commands', 'returns': ['CommandInfo'] }
##
# @MigrationStats
#
# Detailed migration status.
#
# @transferred: amount of bytes already transferred to the target VM
#
# @remaining: amount of bytes remaining to be transferred to the target VM
#
# @total: total amount of bytes involved in the migration process
#
# Since: 0.14.0.
##
{ 'type': 'MigrationStats',
'data': {'transferred': 'int', 'remaining': 'int', 'total': 'int' } }
##
# @MigrationInfo
#
# Information about current migration process.
#
# @status: #optional string describing the current migration status.
# As of 0.14.0 this can be 'active', 'completed', 'failed' or
# 'cancelled'. If this field is not returned, no migration process
# has been initiated
#
# @ram: #optional @MigrationStats containing detailed migration status,
# only returned if status is 'active'
#
# @disk: #optional @MigrationStats containing detailed disk migration
# status, only returned if status is 'active' and it is a block
# migration
#
# Since: 0.14.0
##
{ 'type': 'MigrationInfo',
'data': {'*status': 'str', '*ram': 'MigrationStats',
'*disk': 'MigrationStats'} }
##
# @query-migrate
#
# Returns information about current migration process.
#
# Returns: @MigrationInfo
#
# Since: 0.14.0
##
{ 'command': 'query-migrate', 'returns': 'MigrationInfo' }
##
# @MouseInfo:
#
# Information about a mouse device.
#
# @name: the name of the mouse device
#
# @index: the index of the mouse device
#
# @current: true if this device is currently receiving mouse events
#
# @absolute: true if this device supports absolute coordinates as input
#
# Since: 0.14.0
##
{ 'type': 'MouseInfo',
'data': {'name': 'str', 'index': 'int', 'current': 'bool',
'absolute': 'bool'} }
##
# @query-mice:
#
# Returns information about each active mouse device
#
# Returns: a list of @MouseInfo for each device
#
# Since: 0.14.0
##
{ 'command': 'query-mice', 'returns': ['MouseInfo'] }
##
# @CpuInfo:
#
# Information about a virtual CPU
#
# @CPU: the index of the virtual CPU
#
# @current: this only exists for backwards compatible and should be ignored
#
# @halted: true if the virtual CPU is in the halt state. Halt usually refers
# to a processor specific low power mode.
#
# @pc: #optional If the target is i386 or x86_64, this is the 64-bit instruction
# pointer.
# If the target is Sparc, this is the PC component of the
# instruction pointer.
#
# @nip: #optional If the target is PPC, the instruction pointer
#
# @npc: #optional If the target is Sparc, the NPC component of the instruction
# pointer
#
# @PC: #optional If the target is MIPS, the instruction pointer
#
# @thread_id: ID of the underlying host thread
#
# Since: 0.14.0
#
# Notes: @halted is a transient state that changes frequently. By the time the
# data is sent to the client, the guest may no longer be halted.
##
{ 'type': 'CpuInfo',
'data': {'CPU': 'int', 'current': 'bool', 'halted': 'bool', '*pc': 'int',
'*nip': 'int', '*npc': 'int', '*PC': 'int', 'thread_id': 'int'} }
##
# @query-cpus:
#
# Returns a list of information about each virtual CPU.
#
# Returns: a list of @CpuInfo for each virtual CPU
#
# Since: 0.14.0
##
{ 'command': 'query-cpus', 'returns': ['CpuInfo'] }
##
# @BlockDeviceInfo:
#
# Information about the backing device for a block device.
#
# @file: the filename of the backing device
#
# @ro: true if the backing device was open read-only
#
# @drv: the name of the block format used to open the backing device. As of
# 0.14.0 this can be: 'blkdebug', 'bochs', 'cloop', 'cow', 'dmg',
# 'file', 'file', 'ftp', 'ftps', 'host_cdrom', 'host_device',
# 'host_floppy', 'http', 'https', 'nbd', 'parallels', 'qcow',
# 'qcow2', 'raw', 'tftp', 'vdi', 'vmdk', 'vpc', 'vvfat'
#
# @backing_file: #optional the name of the backing file (for copy-on-write)
#
# @encrypted: true if the backing device is encrypted
#
# @bps: total throughput limit in bytes per second is specified
#
# @bps_rd: read throughput limit in bytes per second is specified
#
# @bps_wr: write throughput limit in bytes per second is specified
#
# @iops: total I/O operations per second is specified
#
# @iops_rd: read I/O operations per second is specified
#
# @iops_wr: write I/O operations per second is specified
#
# Since: 0.14.0
#
# Notes: This interface is only found in @BlockInfo.
##
{ 'type': 'BlockDeviceInfo',
'data': { 'file': 'str', 'ro': 'bool', 'drv': 'str',
'*backing_file': 'str', 'encrypted': 'bool',
'bps': 'int', 'bps_rd': 'int', 'bps_wr': 'int',
'iops': 'int', 'iops_rd': 'int', 'iops_wr': 'int'} }
##
# @BlockDeviceIoStatus:
#
# An enumeration of block device I/O status.
#
# @ok: The last I/O operation has succeeded
#
# @failed: The last I/O operation has failed
#
# @nospace: The last I/O operation has failed due to a no-space condition
#
# Since: 1.0
##
{ 'enum': 'BlockDeviceIoStatus', 'data': [ 'ok', 'failed', 'nospace' ] }
##
# @BlockInfo:
#
# Block device information. This structure describes a virtual device and
# the backing device associated with it.
#
# @device: The device name associated with the virtual device.
#
# @type: This field is returned only for compatibility reasons, it should
# not be used (always returns 'unknown')
#
# @removable: True if the device supports removable media.
#
# @locked: True if the guest has locked this device from having its media
# removed
#
# @tray_open: #optional True if the device has a tray and it is open
# (only present if removable is true)
#
# @io-status: #optional @BlockDeviceIoStatus. Only present if the device
# supports it and the VM is configured to stop on errors
#
# @inserted: #optional @BlockDeviceInfo describing the device if media is
# present
#
# Since: 0.14.0
##
{ 'type': 'BlockInfo',
'data': {'device': 'str', 'type': 'str', 'removable': 'bool',
'locked': 'bool', '*inserted': 'BlockDeviceInfo',
'*tray_open': 'bool', '*io-status': 'BlockDeviceIoStatus'} }
##
# @query-block:
#
# Get a list of BlockInfo for all virtual block devices.
#
# Returns: a list of @BlockInfo describing each virtual block device
#
# Since: 0.14.0
##
{ 'command': 'query-block', 'returns': ['BlockInfo'] }
##
# @BlockDeviceStats:
#
# Statistics of a virtual block device or a block backing device.
#
# @rd_bytes: The number of bytes read by the device.
#
# @wr_bytes: The number of bytes written by the device.
#
# @rd_operations: The number of read operations performed by the device.
#
# @wr_operations: The number of write operations performed by the device.
#
# @flush_operations: The number of cache flush operations performed by the
# device (since 0.15.0)
#
# @flush_total_time_ns: Total time spend on cache flushes in nano-seconds
# (since 0.15.0).
#
# @wr_total_time_ns: Total time spend on writes in nano-seconds (since 0.15.0).
#
# @rd_total_time_ns: Total_time_spend on reads in nano-seconds (since 0.15.0).
#
# @wr_highest_offset: The offset after the greatest byte written to the
# device. The intended use of this information is for
# growable sparse files (like qcow2) that are used on top
# of a physical device.
#
# Since: 0.14.0
##
{ 'type': 'BlockDeviceStats',
'data': {'rd_bytes': 'int', 'wr_bytes': 'int', 'rd_operations': 'int',
'wr_operations': 'int', 'flush_operations': 'int',
'flush_total_time_ns': 'int', 'wr_total_time_ns': 'int',
'rd_total_time_ns': 'int', 'wr_highest_offset': 'int' } }
##
# @BlockStats:
#
# Statistics of a virtual block device or a block backing device.
#
# @device: #optional If the stats are for a virtual block device, the name
# corresponding to the virtual block device.
#
# @stats: A @BlockDeviceStats for the device.
#
# @parent: #optional This may point to the backing block device if this is a
# a virtual block device. If it's a backing block, this will point
# to the backing file is one is present.
#
# Since: 0.14.0
##
{ 'type': 'BlockStats',
'data': {'*device': 'str', 'stats': 'BlockDeviceStats',
'*parent': 'BlockStats'} }
##
# @query-blockstats:
#
# Query the @BlockStats for all virtual block devices.
#
# Returns: A list of @BlockStats for each virtual block devices.
#
# Since: 0.14.0
##
{ 'command': 'query-blockstats', 'returns': ['BlockStats'] }
##
# @VncClientInfo:
#
# Information about a connected VNC client.
#
# @host: The host name of the client. QEMU tries to resolve this to a DNS name
# when possible.
#
# @family: 'ipv6' if the client is connected via IPv6 and TCP
# 'ipv4' if the client is connected via IPv4 and TCP
# 'unix' if the client is connected via a unix domain socket
# 'unknown' otherwise
#
# @service: The service name of the client's port. This may depends on the
# host system's service database so symbolic names should not be
# relied on.
#
# @x509_dname: #optional If x509 authentication is in use, the Distinguished
# Name of the client.
#
# @sasl_username: #optional If SASL authentication is in use, the SASL username
# used for authentication.
#
# Since: 0.14.0
##
{ 'type': 'VncClientInfo',
'data': {'host': 'str', 'family': 'str', 'service': 'str',
'*x509_dname': 'str', '*sasl_username': 'str'} }
##
# @VncInfo:
#
# Information about the VNC session.
#
# @enabled: true if the VNC server is enabled, false otherwise
#
# @host: #optional The hostname the VNC server is bound to. This depends on
# the name resolution on the host and may be an IP address.
#
# @family: #optional 'ipv6' if the host is listening for IPv6 connections
# 'ipv4' if the host is listening for IPv4 connections
# 'unix' if the host is listening on a unix domain socket
# 'unknown' otherwise
#
# @service: #optional The service name of the server's port. This may depends
# on the host system's service database so symbolic names should not
# be relied on.
#
# @auth: #optional the current authentication type used by the server
# 'none' if no authentication is being used
# 'vnc' if VNC authentication is being used
# 'vencrypt+plain' if VEncrypt is used with plain text authentication
# 'vencrypt+tls+none' if VEncrypt is used with TLS and no authentication
# 'vencrypt+tls+vnc' if VEncrypt is used with TLS and VNC authentication
# 'vencrypt+tls+plain' if VEncrypt is used with TLS and plain text auth
# 'vencrypt+x509+none' if VEncrypt is used with x509 and no auth
# 'vencrypt+x509+vnc' if VEncrypt is used with x509 and VNC auth
# 'vencrypt+x509+plain' if VEncrypt is used with x509 and plain text auth
# 'vencrypt+tls+sasl' if VEncrypt is used with TLS and SASL auth
# 'vencrypt+x509+sasl' if VEncrypt is used with x509 and SASL auth
#
# @clients: a list of @VncClientInfo of all currently connected clients
#
# Since: 0.14.0
##
{ 'type': 'VncInfo',
'data': {'enabled': 'bool', '*host': 'str', '*family': 'str',
'*service': 'str', '*auth': 'str', '*clients': ['VncClientInfo']} }
##
# @query-vnc:
#
# Returns information about the current VNC server
#
# Returns: @VncInfo
# If VNC support is not compiled in, FeatureDisabled
#
# Since: 0.14.0
##
{ 'command': 'query-vnc', 'returns': 'VncInfo' }
##
# @SpiceChannel
#
# Information about a SPICE client channel.
#
# @host: The host name of the client. QEMU tries to resolve this to a DNS name
# when possible.
#
# @family: 'ipv6' if the client is connected via IPv6 and TCP
# 'ipv4' if the client is connected via IPv4 and TCP
# 'unix' if the client is connected via a unix domain socket
# 'unknown' otherwise
#
# @port: The client's port number.
#
# @connection-id: SPICE connection id number. All channels with the same id
# belong to the same SPICE session.
#
# @connection-type: SPICE channel type number. "1" is the main control
# channel, filter for this one if you want to track spice
# sessions only
#
# @channel-id: SPICE channel ID number. Usually "0", might be different when
# multiple channels of the same type exist, such as multiple
# display channels in a multihead setup
#
# @tls: true if the channel is encrypted, false otherwise.
#
# Since: 0.14.0
##
{ 'type': 'SpiceChannel',
'data': {'host': 'str', 'family': 'str', 'port': 'str',
'connection-id': 'int', 'channel-type': 'int', 'channel-id': 'int',
'tls': 'bool'} }
##
# @SpiceQueryMouseMode
#
# An enumation of Spice mouse states.
#
# @client: Mouse cursor position is determined by the client.
#
# @server: Mouse cursor position is determined by the server.
#
# @unknown: No information is available about mouse mode used by
# the spice server.
#
# Note: spice/enums.h has a SpiceMouseMode already, hence the name.
#
# Since: 1.1
##
{ 'enum': 'SpiceQueryMouseMode',
'data': [ 'client', 'server', 'unknown' ] }
##
# @SpiceInfo
#
# Information about the SPICE session.
#
# @enabled: true if the SPICE server is enabled, false otherwise
#
# @host: #optional The hostname the SPICE server is bound to. This depends on
# the name resolution on the host and may be an IP address.
#
# @port: #optional The SPICE server's port number.
#
# @compiled-version: #optional SPICE server version.
#
# @tls-port: #optional The SPICE server's TLS port number.
#
# @auth: #optional the current authentication type used by the server
# 'none' if no authentication is being used
# 'spice' uses SASL or direct TLS authentication, depending on command
# line options
#
# @mouse-mode: The mode in which the mouse cursor is displayed currently. Can
# be determined by the client or the server, or unknown if spice
# server doesn't provide this information.
#
# Since: 1.1
#
# @channels: a list of @SpiceChannel for each active spice channel
#
# Since: 0.14.0
##
{ 'type': 'SpiceInfo',
'data': {'enabled': 'bool', '*host': 'str', '*port': 'int',
'*tls-port': 'int', '*auth': 'str', '*compiled-version': 'str',
'mouse-mode': 'SpiceQueryMouseMode', '*channels': ['SpiceChannel']} }
##
# @query-spice
#
# Returns information about the current SPICE server
#
# Returns: @SpiceInfo
#
# Since: 0.14.0
##
{ 'command': 'query-spice', 'returns': 'SpiceInfo' }
##
# @BalloonInfo:
#
# Information about the guest balloon device.
#
# @actual: the number of bytes the balloon currently contains
#
# @mem_swapped_in: #optional number of pages swapped in within the guest
#
# @mem_swapped_out: #optional number of pages swapped out within the guest
#
# @major_page_faults: #optional number of major page faults within the guest
#
# @minor_page_faults: #optional number of minor page faults within the guest
#
# @free_mem: #optional amount of memory (in bytes) free in the guest
#
# @total_mem: #optional amount of memory (in bytes) visible to the guest
#
# Since: 0.14.0
#
# Notes: all current versions of QEMU do not fill out optional information in
# this structure.
##
{ 'type': 'BalloonInfo',
'data': {'actual': 'int', '*mem_swapped_in': 'int',
'*mem_swapped_out': 'int', '*major_page_faults': 'int',
'*minor_page_faults': 'int', '*free_mem': 'int',
'*total_mem': 'int'} }
##
# @query-balloon:
#
# Return information about the balloon device.
#
# Returns: @BalloonInfo on success
# If the balloon driver is enabled but not functional because the KVM
# kernel module cannot support it, KvmMissingCap
# If no balloon device is present, DeviceNotActive
#
# Since: 0.14.0
##
{ 'command': 'query-balloon', 'returns': 'BalloonInfo' }
##
# @PciMemoryRange:
#
# A PCI device memory region
#
# @base: the starting address (guest physical)
#
# @limit: the ending address (guest physical)
#
# Since: 0.14.0
##
{ 'type': 'PciMemoryRange', 'data': {'base': 'int', 'limit': 'int'} }
##
# @PciMemoryRegion
#
# Information about a PCI device I/O region.
#
# @bar: the index of the Base Address Register for this region
#
# @type: 'io' if the region is a PIO region
# 'memory' if the region is a MMIO region
#
# @prefetch: #optional if @type is 'memory', true if the memory is prefetchable
#
# @mem_type_64: #optional if @type is 'memory', true if the BAR is 64-bit
#
# Since: 0.14.0
##
{ 'type': 'PciMemoryRegion',
'data': {'bar': 'int', 'type': 'str', 'address': 'int', 'size': 'int',
'*prefetch': 'bool', '*mem_type_64': 'bool' } }
##
# @PciBridgeInfo:
#
# Information about a PCI Bridge device
#
# @bus.number: primary bus interface number. This should be the number of the
# bus the device resides on.
#
# @bus.secondary: secondary bus interface number. This is the number of the
# main bus for the bridge
#
# @bus.subordinate: This is the highest number bus that resides below the
# bridge.
#
# @bus.io_range: The PIO range for all devices on this bridge
#
# @bus.memory_range: The MMIO range for all devices on this bridge
#
# @bus.prefetchable_range: The range of prefetchable MMIO for all devices on
# this bridge
#
# @devices: a list of @PciDeviceInfo for each device on this bridge
#
# Since: 0.14.0
##
{ 'type': 'PciBridgeInfo',
'data': {'bus': { 'number': 'int', 'secondary': 'int', 'subordinate': 'int',
'io_range': 'PciMemoryRange',
'memory_range': 'PciMemoryRange',
'prefetchable_range': 'PciMemoryRange' },
'*devices': ['PciDeviceInfo']} }
##
# @PciDeviceInfo:
#
# Information about a PCI device
#
# @bus: the bus number of the device
#
# @slot: the slot the device is located in
#
# @function: the function of the slot used by the device
#
# @class_info.desc: #optional a string description of the device's class
#
# @class_info.class: the class code of the device
#
# @id.device: the PCI device id
#
# @id.vendor: the PCI vendor id
#
# @irq: #optional if an IRQ is assigned to the device, the IRQ number
#
# @qdev_id: the device name of the PCI device
#
# @pci_bridge: if the device is a PCI bridge, the bridge information
#
# @regions: a list of the PCI I/O regions associated with the device
#
# Notes: the contents of @class_info.desc are not stable and should only be
# treated as informational.
#
# Since: 0.14.0
##
{ 'type': 'PciDeviceInfo',
'data': {'bus': 'int', 'slot': 'int', 'function': 'int',
'class_info': {'*desc': 'str', 'class': 'int'},
'id': {'device': 'int', 'vendor': 'int'},
'*irq': 'int', 'qdev_id': 'str', '*pci_bridge': 'PciBridgeInfo',
'regions': ['PciMemoryRegion']} }
##
# @PciInfo:
#
# Information about a PCI bus
#
# @bus: the bus index
#
# @devices: a list of devices on this bus
#
# Since: 0.14.0
##
{ 'type': 'PciInfo', 'data': {'bus': 'int', 'devices': ['PciDeviceInfo']} }
##
# @query-pci:
#
# Return information about the PCI bus topology of the guest.
#
# Returns: a list of @PciInfo for each PCI bus
#
# Since: 0.14.0
##
{ 'command': 'query-pci', 'returns': ['PciInfo'] }
##
# @BlockJobInfo:
#
# Information about a long-running block device operation.
#
# @type: the job type ('stream' for image streaming)
#
# @device: the block device name
#
# @len: the maximum progress value
#
# @offset: the current progress value
#
# @speed: the rate limit, bytes per second
#
# Since: 1.1
##
{ 'type': 'BlockJobInfo',
'data': {'type': 'str', 'device': 'str', 'len': 'int',
'offset': 'int', 'speed': 'int'} }
##
# @query-block-jobs:
#
# Return information about long-running block device operations.
#
# Returns: a list of @BlockJobInfo for each active block job
#
# Since: 1.1
##
{ 'command': 'query-block-jobs', 'returns': ['BlockJobInfo'] }
##
# @quit:
#
# This command will cause the QEMU process to exit gracefully. While every
# attempt is made to send the QMP response before terminating, this is not
# guaranteed. When using this interface, a premature EOF would not be
# unexpected.
#
# Since: 0.14.0
##
{ 'command': 'quit' }
##
# @stop:
#
# Stop all guest VCPU execution.
#
# Since: 0.14.0
#
# Notes: This function will succeed even if the guest is already in the stopped
# state
##
{ 'command': 'stop' }
##
# @system_reset:
#
# Performs a hard reset of a guest.
#
# Since: 0.14.0
##
{ 'command': 'system_reset' }
##
# @system_powerdown:
#
# Requests that a guest perform a powerdown operation.
#
# Since: 0.14.0
#
# Notes: A guest may or may not respond to this command. This command
# returning does not indicate that a guest has accepted the request or
# that it has shut down. Many guests will respond to this command by
# prompting the user in some way.
##
{ 'command': 'system_powerdown' }
##
# @cpu:
#
# This command is a nop that is only provided for the purposes of compatibility.
#
# Since: 0.14.0
#
# Notes: Do not use this command.
##
{ 'command': 'cpu', 'data': {'index': 'int'} }
##
# @memsave:
#
# Save a portion of guest memory to a file.
#
# @val: the virtual address of the guest to start from
#
# @size: the size of memory region to save
#
# @filename: the file to save the memory to as binary data
#
# @cpu-index: #optional the index of the virtual CPU to use for translating the
# virtual address (defaults to CPU 0)
#
# Returns: Nothing on success
# If @cpu is not a valid VCPU, InvalidParameterValue
# If @filename cannot be opened, OpenFileFailed
# If an I/O error occurs while writing the file, IOError
#
# Since: 0.14.0
#
# Notes: Errors were not reliably returned until 1.1
##
{ 'command': 'memsave',
'data': {'val': 'int', 'size': 'int', 'filename': 'str', '*cpu-index': 'int'} }
##
# @pmemsave:
#
# Save a portion of guest physical memory to a file.
#
# @val: the physical address of the guest to start from
#
# @size: the size of memory region to save
#
# @filename: the file to save the memory to as binary data
#
# Returns: Nothing on success
# If @filename cannot be opened, OpenFileFailed
# If an I/O error occurs while writing the file, IOError
#
# Since: 0.14.0
#
# Notes: Errors were not reliably returned until 1.1
##
{ 'command': 'pmemsave',
'data': {'val': 'int', 'size': 'int', 'filename': 'str'} }
##
# @cont:
#
# Resume guest VCPU execution.
#
# Since: 0.14.0
#
# Returns: If successful, nothing
# If the QEMU is waiting for an incoming migration, MigrationExpected
# If QEMU was started with an encrypted block device and a key has
# not yet been set, DeviceEncrypted.
#
# Notes: This command will succeed if the guest is currently running.
##
{ 'command': 'cont' }
##
# @system_wakeup:
#
# Wakeup guest from suspend. Does nothing in case the guest isn't suspended.
#
# Since: 1.1
#
# Returns: nothing.
##
{ 'command': 'system_wakeup' }
##
# @inject-nmi:
#
# Injects an Non-Maskable Interrupt into all guest's VCPUs.
#
# Returns: If successful, nothing
# If the Virtual Machine doesn't support NMI injection, Unsupported
#
# Since: 0.14.0
#
# Notes: Only x86 Virtual Machines support this command.
##
{ 'command': 'inject-nmi' }
##
# @set_link:
#
# Sets the link status of a virtual network adapter.
#
# @name: the device name of the virtual network adapter
#
# @up: true to set the link status to be up
#
# Returns: Nothing on success
# If @name is not a valid network device, DeviceNotFound
#
# Since: 0.14.0
#
# Notes: Not all network adapters support setting link status. This command
# will succeed even if the network adapter does not support link status
# notification.
##
{ 'command': 'set_link', 'data': {'name': 'str', 'up': 'bool'} }
##
# @block_passwd:
#
# This command sets the password of a block device that has not been open
# with a password and requires one.
#
# The two cases where this can happen are a block device is created through
# QEMU's initial command line or a block device is changed through the legacy
# @change interface.
#
# In the event that the block device is created through the initial command
# line, the VM will start in the stopped state regardless of whether '-S' is
# used. The intention is for a management tool to query the block devices to
# determine which ones are encrypted, set the passwords with this command, and
# then start the guest with the @cont command.
#
# @device: the name of the device to set the password on
#
# @password: the password to use for the device
#
# Returns: nothing on success
# If @device is not a valid block device, DeviceNotFound
# If @device is not encrypted, DeviceNotEncrypted
# If @password is not valid for this device, InvalidPassword
#
# Notes: Not all block formats support encryption and some that do are not
# able to validate that a password is correct. Disk corruption may
# occur if an invalid password is specified.
#
# Since: 0.14.0
##
{ 'command': 'block_passwd', 'data': {'device': 'str', 'password': 'str'} }
##
# @balloon:
#
# Request the balloon driver to change its balloon size.
#
# @value: the target size of the balloon in bytes
#
# Returns: Nothing on success
# If the balloon driver is enabled but not functional because the KVM
# kernel module cannot support it, KvmMissingCap
# If no balloon device is present, DeviceNotActive
#
# Notes: This command just issues a request to the guest. When it returns,
# the balloon size may not have changed. A guest can change the balloon
# size independent of this command.
#
# Since: 0.14.0
##
{ 'command': 'balloon', 'data': {'value': 'int'} }
##
# @block_resize
#
# Resize a block image while a guest is running.
#
# @device: the name of the device to get the image resized
#
# @size: new image size in bytes
#
# Returns: nothing on success
# If @device is not a valid block device, DeviceNotFound
# If @size is negative, InvalidParameterValue
# If the block device has no medium inserted, DeviceHasNoMedium
# If the block device does not support resize, Unsupported
# If the block device is read-only, DeviceIsReadOnly
# If a long-running operation is using the device, DeviceInUse
#
# Since: 0.14.0
##
{ 'command': 'block_resize', 'data': { 'device': 'str', 'size': 'int' }}
##
# @NewImageMode
#
# An enumeration that tells QEMU how to set the backing file path in
# a new image file.
#
# @existing: QEMU should look for an existing image file.
#
# @absolute-paths: QEMU should create a new image with absolute paths
# for the backing file.
#
# Since: 1.1
##
{ 'enum': 'NewImageMode'
'data': [ 'existing', 'absolute-paths' ] }
##
# @BlockdevSnapshot
#
# @device: the name of the device to generate the snapshot from.
#
# @snapshot-file: the target of the new image. A new file will be created.
#
# @format: #optional the format of the snapshot image, default is 'qcow2'.
#
# @mode: #optional whether and how QEMU should create a new image, default is
# 'absolute-paths'.
##
{ 'type': 'BlockdevSnapshot',
'data': { 'device': 'str', 'snapshot-file': 'str', '*format': 'str',
'*mode': 'NewImageMode' } }
##
# @BlockdevAction
#
# A discriminated record of operations that can be performed with
# @transaction.
##
{ 'union': 'BlockdevAction',
'data': {
'blockdev-snapshot-sync': 'BlockdevSnapshot',
} }
##
# @transaction
#
# Atomically operate on a group of one or more block devices. If
# any operation fails, then the entire set of actions will be
# abandoned and the appropriate error returned. The only operation
# supported is currently blockdev-snapshot-sync.
#
# List of:
# @BlockdevAction: information needed for the device snapshot
#
# Returns: nothing on success
# If @device is not a valid block device, DeviceNotFound
# If @device is busy, DeviceInUse will be returned
# If @snapshot-file can't be created, OpenFileFailed
# If @snapshot-file can't be opened, OpenFileFailed
# If @format is invalid, InvalidBlockFormat
#
# Note: The transaction aborts on the first failure. Therefore, there will
# be only one device or snapshot file returned in an error condition, and
# subsequent actions will not have been attempted.
#
# Since 1.1
##
{ 'command': 'transaction',
'data': { 'actions': [ 'BlockdevAction' ] } }
##
# @blockdev-snapshot-sync
#
# Generates a synchronous snapshot of a block device.
#
# @device: the name of the device to generate the snapshot from.
#
# @snapshot-file: the target of the new image. If the file exists, or if it
# is a device, the snapshot will be created in the existing
# file/device. If does not exist, a new file will be created.
#
# @format: #optional the format of the snapshot image, default is 'qcow2'.
#
# @mode: #optional whether and how QEMU should create a new image, default is
# 'absolute-paths'.
#
# Returns: nothing on success
# If @device is not a valid block device, DeviceNotFound
# If @snapshot-file can't be opened, OpenFileFailed
# If @format is invalid, InvalidBlockFormat
#
# Since 0.14.0
##
{ 'command': 'blockdev-snapshot-sync',
'data': { 'device': 'str', 'snapshot-file': 'str', '*format': 'str',
'*mode': 'NewImageMode'} }
##
# @human-monitor-command:
#
# Execute a command on the human monitor and return the output.
#
# @command-line: the command to execute in the human monitor
#
# @cpu-index: #optional The CPU to use for commands that require an implicit CPU
#
# Returns: the output of the command as a string
#
# Since: 0.14.0
#
# Notes: This command only exists as a stop-gap. It's use is highly
# discouraged. The semantics of this command are not guaranteed.
#
# Known limitations:
#
# o This command is stateless, this means that commands that depend
# on state information (such as getfd) might not work
#
# o Commands that prompt the user for data (eg. 'cont' when the block
# device is encrypted) don't currently work
##
{ 'command': 'human-monitor-command',
'data': {'command-line': 'str', '*cpu-index': 'int'},
'returns': 'str' }
##
# @migrate_cancel
#
# Cancel the current executing migration process.
#
# Returns: nothing on success
#
# Notes: This command succeeds even if there is no migration process running.
#
# Since: 0.14.0
##
{ 'command': 'migrate_cancel' }
##
# @migrate_set_downtime
#
# Set maximum tolerated downtime for migration.
#
# @value: maximum downtime in seconds
#
# Returns: nothing on success
#
# Since: 0.14.0
##
{ 'command': 'migrate_set_downtime', 'data': {'value': 'number'} }
##
# @migrate_set_speed
#
# Set maximum speed for migration.
#
# @value: maximum speed in bytes.
#
# Returns: nothing on success
#
# Notes: A value lesser than zero will be automatically round up to zero.
#
# Since: 0.14.0
##
{ 'command': 'migrate_set_speed', 'data': {'value': 'int'} }
##
# @ObjectPropertyInfo:
#
# @name: the name of the property
#
# @type: the type of the property. This will typically come in one of four
# forms:
#
# 1) A primitive type such as 'u8', 'u16', 'bool', 'str', or 'double'.
# These types are mapped to the appropriate JSON type.
#
# 2) A legacy type in the form 'legacy<subtype>' where subtype is the
# legacy qdev typename. These types are always treated as strings.
#
# 3) A child type in the form 'child<subtype>' where subtype is a qdev
# device type name. Child properties create the composition tree.
#
# 4) A link type in the form 'link<subtype>' where subtype is a qdev
# device type name. Link properties form the device model graph.
#
# Since: 1.1
#
# Notes: This type is experimental. Its syntax may change in future releases.
##
{ 'type': 'ObjectPropertyInfo',
'data': { 'name': 'str', 'type': 'str' } }
##
# @qom-list:
#
# This command will list any properties of a object given a path in the object
# model.
#
# @path: the path within the object model. See @qom-get for a description of
# this parameter.
#
# Returns: a list of @ObjectPropertyInfo that describe the properties of the
# object.
#
# Since: 1.1
#
# Notes: This command is experimental. It's syntax may change in future
# releases.
##
{ 'command': 'qom-list',
'data': { 'path': 'str' },
'returns': [ 'ObjectPropertyInfo' ] }
##
# @qom-get:
#
# This command will get a property from a object model path and return the
# value.
#
# @path: The path within the object model. There are two forms of supported
# paths--absolute and partial paths.
#
# Absolute paths are derived from the root object and can follow child<>
# or link<> properties. Since they can follow link<> properties, they
# can be arbitrarily long. Absolute paths look like absolute filenames
# and are prefixed with a leading slash.
#
# Partial paths look like relative filenames. They do not begin
# with a prefix. The matching rules for partial paths are subtle but
# designed to make specifying objects easy. At each level of the
# composition tree, the partial path is matched as an absolute path.
# The first match is not returned. At least two matches are searched
# for. A successful result is only returned if only one match is
# found. If more than one match is found, a flag is return to
# indicate that the match was ambiguous.
#
# @property: The property name to read
#
# Returns: The property value. The type depends on the property type. legacy<>
# properties are returned as #str. child<> and link<> properties are
# returns as #str pathnames. All integer property types (u8, u16, etc)
# are returned as #int.
#
# Since: 1.1
#
# Notes: This command is experimental and may change syntax in future releases.
##
{ 'command': 'qom-get',
'data': { 'path': 'str', 'property': 'str' },
'returns': 'visitor',
'gen': 'no' }
##
# @qom-set:
#
# This command will set a property from a object model path.
#
# @path: see @qom-get for a description of this parameter
#
# @property: the property name to set
#
# @value: a value who's type is appropriate for the property type. See @qom-get
# for a description of type mapping.
#
# Since: 1.1
#
# Notes: This command is experimental and may change syntax in future releases.
##
{ 'command': 'qom-set',
'data': { 'path': 'str', 'property': 'str', 'value': 'visitor' },
'gen': 'no' }
##
# @set_password:
#
# Sets the password of a remote display session.
#
# @protocol: `vnc' to modify the VNC server password
# `spice' to modify the Spice server password
#
# @password: the new password
#
# @connected: #optional how to handle existing clients when changing the
# password. If nothing is specified, defaults to `keep'
# `fail' to fail the command if clients are connected
# `disconnect' to disconnect existing clients
# `keep' to maintain existing clients
#
# Returns: Nothing on success
# If Spice is not enabled, DeviceNotFound
# If @protocol does not support connected, InvalidParameter
# If @protocol is invalid, InvalidParameter
# If any other error occurs, SetPasswdFailed
#
# Notes: If VNC is not enabled, SetPasswdFailed is returned.
#
# Since: 0.14.0
##
{ 'command': 'set_password',
'data': {'protocol': 'str', 'password': 'str', '*connected': 'str'} }
##
# @expire_password:
#
# Expire the password of a remote display server.
#
# @protocol: the name of the remote display protocol `vnc' or `spice'
#
# @time: when to expire the password.
# `now' to expire the password immediately
# `never' to cancel password expiration
# `+INT' where INT is the number of seconds from now (integer)
# `INT' where INT is the absolute time in seconds
#
# Returns: Nothing on success
# If @protocol is `spice' and Spice is not active, DeviceNotFound
# If an error occurs setting password expiration, SetPasswdFailed
# If @protocol is not `spice' or 'vnc', InvalidParameter
#
# Since: 0.14.0
#
# Notes: Time is relative to the server and currently there is no way to
# coordinate server time with client time. It is not recommended to
# use the absolute time version of the @time parameter unless you're
# sure you are on the same machine as the QEMU instance.
##
{ 'command': 'expire_password', 'data': {'protocol': 'str', 'time': 'str'} }
##
# @eject:
#
# Ejects a device from a removable drive.
#
# @device: The name of the device
#
# @force: @optional If true, eject regardless of whether the drive is locked.
# If not specified, the default value is false.
#
# Returns: Nothing on success
# If @device is not a valid block device, DeviceNotFound
# If @device is not removable and @force is false, DeviceNotRemovable
# If @force is false and @device is locked, DeviceLocked
#
# Notes: Ejecting a device will no media results in success
#
# Since: 0.14.0
##
{ 'command': 'eject', 'data': {'device': 'str', '*force': 'bool'} }
##
# @change-vnc-password:
#
# Change the VNC server password.
#
# @target: the new password to use with VNC authentication
#
# Since: 1.1
#
# Notes: An empty password in this command will set the password to the empty
# string. Existing clients are unaffected by executing this command.
##
{ 'command': 'change-vnc-password', 'data': {'password': 'str'} }
##
# @change:
#
# This command is multiple commands multiplexed together.
#
# @device: This is normally the name of a block device but it may also be 'vnc'.
# when it's 'vnc', then sub command depends on @target
#
# @target: If @device is a block device, then this is the new filename.
# If @device is 'vnc', then if the value 'password' selects the vnc
# change password command. Otherwise, this specifies a new server URI
# address to listen to for VNC connections.
#
# @arg: If @device is a block device, then this is an optional format to open
# the device with.
# If @device is 'vnc' and @target is 'password', this is the new VNC
# password to set. If this argument is an empty string, then no future
# logins will be allowed.
#
# Returns: Nothing on success.
# If @device is not a valid block device, DeviceNotFound
# If @format is not a valid block format, InvalidBlockFormat
# If the new block device is encrypted, DeviceEncrypted. Note that
# if this error is returned, the device has been opened successfully
# and an additional call to @block_passwd is required to set the
# device's password. The behavior of reads and writes to the block
# device between when these calls are executed is undefined.
#
# Notes: It is strongly recommended that this interface is not used especially
# for changing block devices.
#
# Since: 0.14.0
##
{ 'command': 'change',
'data': {'device': 'str', 'target': 'str', '*arg': 'str'} }
##
# @block_set_io_throttle:
#
# Change I/O throttle limits for a block drive.
#
# @device: The name of the device
#
# @bps: total throughput limit in bytes per second
#
# @bps_rd: read throughput limit in bytes per second
#
# @bps_wr: write throughput limit in bytes per second
#
# @iops: total I/O operations per second
#
# @ops_rd: read I/O operations per second
#
# @iops_wr: write I/O operations per second
#
# Returns: Nothing on success
# If @device is not a valid block device, DeviceNotFound
# If the argument combination is invalid, InvalidParameterCombination
#
# Since: 1.1
##
{ 'command': 'block_set_io_throttle',
'data': { 'device': 'str', 'bps': 'int', 'bps_rd': 'int', 'bps_wr': 'int',
'iops': 'int', 'iops_rd': 'int', 'iops_wr': 'int' } }
##
# @block-stream:
#
# Copy data from a backing file into a block device.
#
# The block streaming operation is performed in the background until the entire
# backing file has been copied. This command returns immediately once streaming
# has started. The status of ongoing block streaming operations can be checked
# with query-block-jobs. The operation can be stopped before it has completed
# using the block-job-cancel command.
#
# If a base file is specified then sectors are not copied from that base file and
# its backing chain. When streaming completes the image file will have the base
# file as its backing file. This can be used to stream a subset of the backing
# file chain instead of flattening the entire image.
#
# On successful completion the image file is updated to drop the backing file
# and the BLOCK_JOB_COMPLETED event is emitted.
#
# @device: the device name
#
# @base: #optional the common backing file name
#
# @speed: #optional the maximum speed, in bytes per second
#
# Returns: Nothing on success
# If streaming is already active on this device, DeviceInUse
# If @device does not exist, DeviceNotFound
# If image streaming is not supported by this device, NotSupported
# If @base does not exist, BaseNotFound
# If @speed is invalid, InvalidParameter
#
# Since: 1.1
##
{ 'command': 'block-stream', 'data': { 'device': 'str', '*base': 'str',
'*speed': 'int' } }
##
# @block-job-set-speed:
#
# Set maximum speed for a background block operation.
#
# This command can only be issued when there is an active block job.
#
# Throttling can be disabled by setting the speed to 0.
#
# @device: the device name
#
# @speed: the maximum speed, in bytes per second, or 0 for unlimited.
# Defaults to 0.
#
# Returns: Nothing on success
# If the job type does not support throttling, NotSupported
# If the speed value is invalid, InvalidParameter
# If streaming is not active on this device, DeviceNotActive
#
# Since: 1.1
##
{ 'command': 'block-job-set-speed',
'data': { 'device': 'str', 'speed': 'int' } }
##
# @block-job-cancel:
#
# Stop an active block streaming operation.
#
# This command returns immediately after marking the active block streaming
# operation for cancellation. It is an error to call this command if no
# operation is in progress.
#
# The operation will cancel as soon as possible and then emit the
# BLOCK_JOB_CANCELLED event. Before that happens the job is still visible when
# enumerated using query-block-jobs.
#
# The image file retains its backing file unless the streaming operation happens
# to complete just as it is being cancelled.
#
# A new block streaming operation can be started at a later time to finish
# copying all data from the backing file.
#
# @device: the device name
#
# Returns: Nothing on success
# If streaming is not active on this device, DeviceNotActive
# If cancellation already in progress, DeviceInUse
#
# Since: 1.1
##
{ 'command': 'block-job-cancel', 'data': { 'device': 'str' } }
##
# @ObjectTypeInfo:
#
# This structure describes a search result from @qom-list-types
#
# @name: the type name found in the search
#
# Since: 1.1
#
# Notes: This command is experimental and may change syntax in future releases.
##
{ 'type': 'ObjectTypeInfo',
'data': { 'name': 'str' } }
##
# @qom-list-types:
#
# This command will return a list of types given search parameters
#
# @implements: if specified, only return types that implement this type name
#
# @abstract: if true, include abstract types in the results
#
# Returns: a list of @ObjectTypeInfo or an empty list if no results are found
#
# Since: 1.1
#
# Notes: This command is experimental and may change syntax in future releases.
##
{ 'command': 'qom-list-types',
'data': { '*implements': 'str', '*abstract': 'bool' },
'returns': [ 'ObjectTypeInfo' ] }
##
# @migrate
#
# Migrates the current running guest to another Virtual Machine.
#
# @uri: the Uniform Resource Identifier of the destination VM
#
# @blk: #optional do block migration (full disk copy)
#
# @inc: #optional incremental disk copy migration
#
# @detach: this argument exists only for compatibility reasons and
# is ignored by QEMU
#
# Returns: nothing on success
#
# Since: 0.14.0
##
{ 'command': 'migrate',
'data': {'uri': 'str', '*blk': 'bool', '*inc': 'bool', '*detach': 'bool' } }
# @xen-save-devices-state:
#
# Save the state of all devices to file. The RAM and the block devices
# of the VM are not saved by this command.
#
# @filename: the file to save the state of the devices to as binary
# data. See xen-save-devices-state.txt for a description of the binary
# format.
#
# Returns: Nothing on success
# If @filename cannot be opened, OpenFileFailed
# If an I/O error occurs while writing the file, IOError
#
# Since: 1.1
##
{ 'command': 'xen-save-devices-state', 'data': {'filename': 'str'} }
##
# @device_del:
#
# Remove a device from a guest
#
# @id: the name of the device
#
# Returns: Nothing on success
# If @id is not a valid device, DeviceNotFound
# If the device does not support unplug, BusNoHotplug
#
# Notes: When this command completes, the device may not be removed from the
# guest. Hot removal is an operation that requires guest cooperation.
# This command merely requests that the guest begin the hot removal
# process.
#
# Since: 0.14.0
##
{ 'command': 'device_del', 'data': {'id': 'str'} }
| Python |
# *-*- Mode: Python -*-*
# for testing enums
{ 'enum': 'EnumOne',
'data': [ 'value1', 'value2', 'value3' ] }
{ 'type': 'NestedEnumsOne',
'data': { 'enum1': 'EnumOne', '*enum2': 'EnumOne', 'enum3': 'EnumOne', '*enum4': 'EnumOne' } }
# for testing nested structs
{ 'type': 'UserDefOne',
'data': { 'integer': 'int', 'string': 'str', '*enum1': 'EnumOne' } }
{ 'type': 'UserDefTwo',
'data': { 'string': 'str',
'dict': { 'string': 'str',
'dict': { 'userdef': 'UserDefOne', 'string': 'str' },
'*dict2': { 'userdef': 'UserDefOne', 'string': 'str' } } } }
{ 'type': 'UserDefNested',
'data': { 'string0': 'str',
'dict1': { 'string1': 'str',
'dict2': { 'userdef1': 'UserDefOne', 'string2': 'str' },
'*dict3': { 'userdef2': 'UserDefOne', 'string3': 'str' } } } }
# for testing unions
{ 'type': 'UserDefA',
'data': { 'boolean': 'bool' } }
{ 'type': 'UserDefB',
'data': { 'integer': 'int' } }
{ 'union': 'UserDefUnion',
'data': { 'a' : 'UserDefA', 'b' : 'UserDefB' } }
# testing commands
{ 'command': 'user_def_cmd', 'data': {} }
{ 'command': 'user_def_cmd1', 'data': {'ud1a': 'UserDefOne'} }
{ 'command': 'user_def_cmd2', 'data': {'ud1a': 'UserDefOne', 'ud1b': 'UserDefOne'}, 'returns': 'UserDefTwo' }
| Python |
# Copyright (c) 2009 Raymond Hettinger
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
from UserDict import DictMixin
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clear()
self.update(*args, **kwds)
def clear(self):
self.__end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.__map = {} # key --> [key, prev, next]
dict.clear(self)
def __setitem__(self, key, value):
if key not in self:
end = self.__end
curr = end[1]
curr[2] = end[1] = self.__map[key] = [key, curr, end]
dict.__setitem__(self, key, value)
def __delitem__(self, key):
dict.__delitem__(self, key)
key, prev, next = self.__map.pop(key)
prev[2] = next
next[1] = prev
def __iter__(self):
end = self.__end
curr = end[2]
while curr is not end:
yield curr[0]
curr = curr[2]
def __reversed__(self):
end = self.__end
curr = end[1]
while curr is not end:
yield curr[0]
curr = curr[1]
def popitem(self, last=True):
if not self:
raise KeyError('dictionary is empty')
if last:
key = reversed(self).next()
else:
key = iter(self).next()
value = self.pop(key)
return key, value
def __reduce__(self):
items = [[k, self[k]] for k in self]
tmp = self.__map, self.__end
del self.__map, self.__end
inst_dict = vars(self).copy()
self.__map, self.__end = tmp
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def keys(self):
return list(self)
setdefault = DictMixin.setdefault
update = DictMixin.update
pop = DictMixin.pop
values = DictMixin.values
items = DictMixin.items
iterkeys = DictMixin.iterkeys
itervalues = DictMixin.itervalues
iteritems = DictMixin.iteritems
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
def copy(self):
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
d = cls()
for key in iterable:
d[key] = value
return d
def __eq__(self, other):
if isinstance(other, OrderedDict):
if len(self) != len(other):
return False
for p, q in zip(self.items(), other.items()):
if p != q:
return False
return True
return dict.__eq__(self, other)
def __ne__(self, other):
return not self == other
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Command-line wrapper for the tracetool machinery.
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanha@linux.vnet.ibm.com"
import sys
import getopt
from tracetool import error_write, out
import tracetool.backend
import tracetool.format
_SCRIPT = ""
def error_opt(msg = None):
if msg is not None:
error_write("Error: " + msg + "\n")
backend_descr = "\n".join([ " %-15s %s" % (n, d)
for n,d in tracetool.backend.get_list() ])
format_descr = "\n".join([ " %-15s %s" % (n, d)
for n,d in tracetool.format.get_list() ])
error_write("""\
Usage: %(script)s --format=<format> --backend=<backend> [<options>]
Backends:
%(backends)s
Formats:
%(formats)s
Options:
--help This help message.
--list-backends Print list of available backends.
--check-backend Check if the given backend is valid.
--binary <path> Full path to QEMU binary.
--target-type <type> QEMU emulator target type ('system' or 'user').
--target-arch <arch> QEMU emulator target arch.
--probe-prefix <prefix> Prefix for dtrace probe names
(default: qemu-<target-type>-<target-arch>).\
""" % {
"script" : _SCRIPT,
"backends" : backend_descr,
"formats" : format_descr,
})
if msg is None:
sys.exit(0)
else:
sys.exit(1)
def main(args):
global _SCRIPT
_SCRIPT = args[0]
long_opts = [ "backend=", "format=", "help", "list-backends", "check-backend" ]
long_opts += [ "binary=", "target-type=", "target-arch=", "probe-prefix=" ]
try:
opts, args = getopt.getopt(args[1:], "", long_opts)
except getopt.GetoptError, err:
error_opt(str(err))
check_backend = False
arg_backend = ""
arg_format = ""
binary = None
target_type = None
target_arch = None
probe_prefix = None
for opt, arg in opts:
if opt == "--help":
error_opt()
elif opt == "--backend":
arg_backend = arg
elif opt == "--format":
arg_format = arg
elif opt == "--list-backends":
backends = tracetool.backend.get_list()
out(", ".join([ b for b,_ in backends ]))
sys.exit(0)
elif opt == "--check-backend":
check_backend = True
elif opt == "--binary":
binary = arg
elif opt == '--target-type':
target_type = arg
elif opt == '--target-arch':
target_arch = arg
elif opt == '--probe-prefix':
probe_prefix = arg
else:
error_opt("unhandled option: %s" % opt)
if arg_backend is None:
error_opt("backend not set")
if check_backend:
if tracetool.backend.exists(arg_backend):
sys.exit(0)
else:
sys.exit(1)
if arg_format == "stap":
if binary is None:
error_opt("--binary is required for SystemTAP tapset generator")
if probe_prefix is None and target_type is None:
error_opt("--target-type is required for SystemTAP tapset generator")
if probe_prefix is None and target_arch is None:
error_opt("--target-arch is required for SystemTAP tapset generator")
if probe_prefix is None:
probe_prefix = ".".join([ "qemu", target_type, target_arch ])
try:
tracetool.generate(sys.stdin, arg_format, arg_backend,
binary = binary, probe_prefix = probe_prefix)
except tracetool.TracetoolError, e:
error_opt(str(e))
if __name__ == "__main__":
main(sys.argv)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Stderr built-in backend.
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanha@linux.vnet.ibm.com"
from tracetool import out
def c(events):
out('#include "trace.h"',
'',
'TraceEvent trace_list[] = {')
for e in events:
out('{.tp_name = "%(name)s", .state=0},',
name = e.name,
)
out('};')
def h(events):
out('#include <stdio.h>',
'#include "trace/stderr.h"',
'',
'extern TraceEvent trace_list[];')
for num, e in enumerate(events):
argnames = ", ".join(e.args.names())
if len(e.args) > 0:
argnames = ", " + argnames
out('static inline void trace_%(name)s(%(args)s)',
'{',
' if (trace_list[%(event_num)s].state != 0) {',
' fprintf(stderr, "%(name)s " %(fmt)s "\\n" %(argnames)s);',
' }',
'}',
name = e.name,
args = e.args,
event_num = num,
fmt = e.fmt,
argnames = argnames,
)
out('',
'#define NR_TRACE_EVENTS %d' % len(events))
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
DTrace/SystemTAP backend.
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanha@linux.vnet.ibm.com"
from tracetool import out
PROBEPREFIX = None
def _probeprefix():
if PROBEPREFIX is None:
raise ValueError("you must set PROBEPREFIX")
return PROBEPREFIX
BINARY = None
def _binary():
if BINARY is None:
raise ValueError("you must set BINARY")
return BINARY
def c(events):
pass
def h(events):
out('#include "trace-dtrace.h"',
'')
for e in events:
out('static inline void trace_%(name)s(%(args)s) {',
' QEMU_%(uppername)s(%(argnames)s);',
'}',
name = e.name,
args = e.args,
uppername = e.name.upper(),
argnames = ", ".join(e.args.names()),
)
def d(events):
out('provider qemu {')
for e in events:
args = str(e.args)
# DTrace provider syntax expects foo() for empty
# params, not foo(void)
if args == 'void':
args = ''
# Define prototype for probe arguments
out('',
'probe %(name)s(%(args)s);',
name = e.name,
args = args,
)
out('',
'};')
def stap(events):
for e in events:
# Define prototype for probe arguments
out('probe %(probeprefix)s.%(name)s = process("%(binary)s").mark("%(name)s")',
'{',
probeprefix = _probeprefix(),
name = e.name,
binary = _binary(),
)
i = 1
if len(e.args) > 0:
for name in e.args.names():
# Append underscore to reserved keywords
if name in ('limit', 'in', 'next', 'self'):
name += '_'
out(' %s = $arg%d;' % (name, i))
i += 1
out('}')
out()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Simple built-in backend.
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanha@linux.vnet.ibm.com"
from tracetool import out
def c(events):
out('#include "trace.h"',
'',
'TraceEvent trace_list[] = {')
for e in events:
out('{.tp_name = "%(name)s", .state=0},',
name = e.name,
)
out('};')
def h(events):
out('#include "trace/simple.h"',
'')
for num, e in enumerate(events):
if len(e.args):
argstr = e.args.names()
arg_prefix = ', (uint64_t)(uintptr_t)'
cast_args = arg_prefix + arg_prefix.join(argstr)
simple_args = (str(num) + cast_args)
else:
simple_args = str(num)
out('static inline void trace_%(name)s(%(args)s)',
'{',
' trace%(argc)d(%(trace_args)s);',
'}',
name = e.name,
args = e.args,
argc = len(e.args),
trace_args = simple_args,
)
out('#define NR_TRACE_EVENTS %d' % len(events))
out('extern TraceEvent trace_list[NR_TRACE_EVENTS];')
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Backend management.
Creating new backends
---------------------
A new backend named 'foo-bar' corresponds to Python module
'tracetool/backend/foo_bar.py'.
A backend module should provide a docstring, whose first non-empty line will be
considered its short description.
All backends must generate their contents through the 'tracetool.out' routine.
Backend functions
-----------------
======== =======================================================================
Function Description
======== =======================================================================
<format> Called to generate the format- and backend-specific code for each of
the specified events. If the function does not exist, the backend is
considered not compatible with the given format.
======== =======================================================================
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanha@linux.vnet.ibm.com"
import os
import tracetool
def get_list():
"""Get a list of (name, description) pairs."""
res = [("nop", "Tracing disabled.")]
modnames = []
for filename in os.listdir(tracetool.backend.__path__[0]):
if filename.endswith('.py') and filename != '__init__.py':
modnames.append(filename.rsplit('.', 1)[0])
for modname in modnames:
module = tracetool.try_import("tracetool.backend." + modname)
# just in case; should never fail unless non-module files are put there
if not module[0]:
continue
module = module[1]
doc = module.__doc__
if doc is None:
doc = ""
doc = doc.strip().split("\n")[0]
name = modname.replace("_", "-")
res.append((name, doc))
return res
def exists(name):
"""Return whether the given backend exists."""
if len(name) == 0:
return False
if name == "nop":
return True
name = name.replace("-", "_")
return tracetool.try_import("tracetool.backend." + name)[1]
def compatible(backend, format):
"""Whether a backend is compatible with the given format."""
if not exists(backend):
raise ValueError("unknown backend: %s" % backend)
backend = backend.replace("-", "_")
format = format.replace("-", "_")
if backend == "nop":
return True
else:
func = tracetool.try_import("tracetool.backend." + backend,
format, None)[1]
return func is not None
def _empty(events):
pass
def generate(backend, format, events):
"""Generate the per-event output for the given (backend, format) pair."""
if not compatible(backend, format):
raise ValueError("backend '%s' not compatible with format '%s'" %
(backend, format))
backend = backend.replace("-", "_")
format = format.replace("-", "_")
if backend == "nop":
func = tracetool.try_import("tracetool.format." + format,
"nop", _empty)[1]
else:
func = tracetool.try_import("tracetool.backend." + backend,
format, None)[1]
func(events)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
LTTng User Space Tracing backend.
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanha@linux.vnet.ibm.com"
from tracetool import out
def c(events):
out('#include <ust/marker.h>',
'#undef mutex_lock',
'#undef mutex_unlock',
'#undef inline',
'#undef wmb',
'#include "trace.h"')
for e in events:
argnames = ", ".join(e.args.names())
if len(e.args) > 0:
argnames = ', ' + argnames
out('DEFINE_TRACE(ust_%(name)s);',
'',
'static void ust_%(name)s_probe(%(args)s)',
'{',
' trace_mark(ust, %(name)s, %(fmt)s%(argnames)s);',
'}',
name = e.name,
args = e.args,
fmt = e.fmt,
argnames = argnames,
)
else:
out('DEFINE_TRACE(ust_%(name)s);',
'',
'static void ust_%(name)s_probe(%(args)s)',
'{',
' trace_mark(ust, %(name)s, UST_MARKER_NOARGS);',
'}',
name = e.name,
args = e.args,
)
# register probes
out('',
'static void __attribute__((constructor)) trace_init(void)',
'{')
for e in events:
out(' register_trace_ust_%(name)s(ust_%(name)s_probe);',
name = e.name,
)
out('}')
def h(events):
out('#include <ust/tracepoint.h>',
'#undef mutex_lock',
'#undef mutex_unlock',
'#undef inline',
'#undef wmb')
for e in events:
if len(e.args) > 0:
out('DECLARE_TRACE(ust_%(name)s, TP_PROTO(%(args)s), TP_ARGS(%(argnames)s));',
'#define trace_%(name)s trace_ust_%(name)s',
name = e.name,
args = e.args,
argnames = ", ".join(e.args.names()),
)
else:
out('_DECLARE_TRACEPOINT_NOARGS(ust_%(name)s);',
'#define trace_%(name)s trace_ust_%(name)s',
name = e.name,
)
out()
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Format management.
Creating new formats
--------------------
A new format named 'foo-bar' corresponds to Python module
'tracetool/format/foo_bar.py'.
A format module should provide a docstring, whose first non-empty line will be
considered its short description.
All formats must generate their contents through the 'tracetool.out' routine.
Format functions
----------------
All the following functions are optional, and no output will be generated if
they do not exist.
======== =======================================================================
Function Description
======== =======================================================================
begin Called to generate the format-specific file header.
end Called to generate the format-specific file footer.
nop Called to generate the per-event contents when the event is disabled or
the selected backend is 'nop'.
======== =======================================================================
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanha@linux.vnet.ibm.com"
import os
import tracetool
def get_list():
"""Get a list of (name, description) pairs."""
res = []
modnames = []
for filename in os.listdir(tracetool.format.__path__[0]):
if filename.endswith('.py') and filename != '__init__.py':
modnames.append(filename.rsplit('.', 1)[0])
for modname in modnames:
module = tracetool.try_import("tracetool.format." + modname)
# just in case; should never fail unless non-module files are put there
if not module[0]:
continue
module = module[1]
doc = module.__doc__
if doc is None:
doc = ""
doc = doc.strip().split("\n")[0]
name = modname.replace("_", "-")
res.append((name, doc))
return res
def exists(name):
"""Return whether the given format exists."""
if len(name) == 0:
return False
name = name.replace("-", "_")
return tracetool.try_import("tracetool.format." + name)[1]
def _empty(events):
pass
def generate_begin(name, events):
"""Generate the header of the format-specific file."""
if not exists(name):
raise ValueError("unknown format: %s" % name)
name = name.replace("-", "_")
func = tracetool.try_import("tracetool.format." + name,
"begin", _empty)[1]
func(events)
def generate_end(name, events):
"""Generate the footer of the format-specific file."""
if not exists(name):
raise ValueError("unknown format: %s" % name)
name = name.replace("-", "_")
func = tracetool.try_import("tracetool.format." + name,
"end", _empty)[1]
func(events)
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Machinery for generating tracing-related intermediate files.
"""
__author__ = "Lluís Vilanova <vilanova@ac.upc.edu>"
__copyright__ = "Copyright 2012, Lluís Vilanova <vilanova@ac.upc.edu>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "stefanha@linux.vnet.ibm.com"
import re
import sys
import tracetool.format
import tracetool.backend
def error_write(*lines):
"""Write a set of error lines."""
sys.stderr.writelines("\n".join(lines) + "\n")
def error(*lines):
"""Write a set of error lines and exit."""
error_write(*lines)
sys.exit(1)
def out(*lines, **kwargs):
"""Write a set of output lines.
You can use kwargs as a shorthand for mapping variables when formating all
the strings in lines.
"""
lines = [ l % kwargs for l in lines ]
sys.stdout.writelines("\n".join(lines) + "\n")
class Arguments:
"""Event arguments description."""
def __init__(self, args):
"""
Parameters
----------
args :
List of (type, name) tuples.
"""
self._args = args
@staticmethod
def build(arg_str):
"""Build and Arguments instance from an argument string.
Parameters
----------
arg_str : str
String describing the event arguments.
"""
res = []
for arg in arg_str.split(","):
arg = arg.strip()
if arg == 'void':
continue
if '*' in arg:
arg_type, identifier = arg.rsplit('*', 1)
arg_type += '*'
identifier = identifier.strip()
else:
arg_type, identifier = arg.rsplit(None, 1)
res.append((arg_type, identifier))
return Arguments(res)
def __iter__(self):
"""Iterate over the (type, name) pairs."""
return iter(self._args)
def __len__(self):
"""Number of arguments."""
return len(self._args)
def __str__(self):
"""String suitable for declaring function arguments."""
if len(self._args) == 0:
return "void"
else:
return ", ".join([ " ".join([t, n]) for t,n in self._args ])
def __repr__(self):
"""Evaluable string representation for this object."""
return "Arguments(\"%s\")" % str(self)
def names(self):
"""List of argument names."""
return [ name for _, name in self._args ]
def types(self):
"""List of argument types."""
return [ type_ for type_, _ in self._args ]
class Event(object):
"""Event description.
Attributes
----------
name : str
The event name.
fmt : str
The event format string.
properties : set(str)
Properties of the event.
args : Arguments
The event arguments.
"""
_CRE = re.compile("((?P<props>.*)\s+)?(?P<name>[^(\s]+)\((?P<args>[^)]*)\)\s*(?P<fmt>\".*)?")
_VALID_PROPS = set(["disable"])
def __init__(self, name, props, fmt, args):
"""
Parameters
----------
name : string
Event name.
props : list of str
Property names.
fmt : str
Event printing format.
args : Arguments
Event arguments.
"""
self.name = name
self.properties = props
self.fmt = fmt
self.args = args
unknown_props = set(self.properties) - self._VALID_PROPS
if len(unknown_props) > 0:
raise ValueError("Unknown properties: %s" % ", ".join(unknown_props))
@staticmethod
def build(line_str):
"""Build an Event instance from a string.
Parameters
----------
line_str : str
Line describing the event.
"""
m = Event._CRE.match(line_str)
assert m is not None
groups = m.groupdict('')
name = groups["name"]
props = groups["props"].split()
fmt = groups["fmt"]
args = Arguments.build(groups["args"])
return Event(name, props, fmt, args)
def __repr__(self):
"""Evaluable string representation for this object."""
return "Event('%s %s(%s) %s')" % (" ".join(self.properties),
self.name,
self.args,
self.fmt)
def _read_events(fobj):
res = []
for line in fobj:
if not line.strip():
continue
if line.lstrip().startswith('#'):
continue
res.append(Event.build(line))
return res
class TracetoolError (Exception):
"""Exception for calls to generate."""
pass
def try_import(mod_name, attr_name = None, attr_default = None):
"""Try to import a module and get an attribute from it.
Parameters
----------
mod_name : str
Module name.
attr_name : str, optional
Name of an attribute in the module.
attr_default : optional
Default value if the attribute does not exist in the module.
Returns
-------
A pair indicating whether the module could be imported and the module or
object or attribute value.
"""
try:
module = __import__(mod_name, globals(), locals(), ["__package__"])
if attr_name is None:
return True, module
return True, getattr(module, str(attr_name), attr_default)
except ImportError:
return False, None
def generate(fevents, format, backend,
binary = None, probe_prefix = None):
"""Generate the output for the given (format, backend) pair.
Parameters
----------
fevents : file
Event description file.
format : str
Output format name.
backend : str
Output backend name.
binary : str or None
See tracetool.backend.dtrace.BINARY.
probe_prefix : str or None
See tracetool.backend.dtrace.PROBEPREFIX.
"""
# fix strange python error (UnboundLocalError tracetool)
import tracetool
format = str(format)
if len(format) is 0:
raise TracetoolError("format not set")
mformat = format.replace("-", "_")
if not tracetool.format.exists(mformat):
raise TracetoolError("unknown format: %s" % format)
backend = str(backend)
if len(backend) is 0:
raise TracetoolError("backend not set")
mbackend = backend.replace("-", "_")
if not tracetool.backend.exists(mbackend):
raise TracetoolError("unknown backend: %s" % backend)
if not tracetool.backend.compatible(mbackend, mformat):
raise TracetoolError("backend '%s' not compatible with format '%s'" %
(backend, format))
import tracetool.backend.dtrace
tracetool.backend.dtrace.BINARY = binary
tracetool.backend.dtrace.PROBEPREFIX = probe_prefix
events = _read_events(fevents)
if backend == "nop":
( e.properies.add("disable") for e in events )
tracetool.format.generate_begin(mformat, events)
tracetool.backend.generate("nop", format,
[ e
for e in events
if "disable" in e.properties ])
tracetool.backend.generate(backend, format,
[ e
for e in events
if "disable" not in e.properties ])
tracetool.format.generate_end(mformat, events)
| Python |
#
# Option ROM signing utility
#
# Authors:
# Jan Kiszka <jan.kiszka@siemens.com>
#
# This work is licensed under the terms of the GNU GPL, version 2 or later.
# See the COPYING file in the top-level directory.
import sys
import struct
if len(sys.argv) < 3:
print('usage: signrom.py input output')
sys.exit(1)
fin = open(sys.argv[1], 'rb')
fout = open(sys.argv[2], 'wb')
fin.seek(2)
size = ord(fin.read(1)) * 512 - 1
fin.seek(0)
data = fin.read(size)
fout.write(data)
checksum = 0
for b in data:
# catch Python 2 vs. 3 differences
if isinstance(b, int):
checksum += b
else:
checksum += ord(b)
checksum = (256 - checksum) % 256
# Python 3 no longer allows chr(checksum)
fout.write(struct.pack('B', checksum))
fin.close()
fout.close()
| Python |
#!/usr/bin/env python
#
# KVM Flight Recorder - ring buffer tracing script
#
# Copyright (C) 2012 IBM Corp
#
# Author: Stefan Hajnoczi <stefanha@linux.vnet.ibm.com>
#
# This script provides a command-line interface to kvm ftrace and is designed
# to be used as a flight recorder that is always running. To start in-memory
# recording:
#
# sudo kvm_flightrecorder start 8192 # 8 MB per-cpu ring buffers
#
# The per-cpu ring buffer size can be given in KB as an optional argument to
# the 'start' subcommand.
#
# To stop the flight recorder:
#
# sudo kvm_flightrecorder stop
#
# To dump the contents of the flight recorder (this can be done when the
# recorder is stopped or while it is running):
#
# sudo kvm_flightrecorder dump >/path/to/dump.txt
#
# To observe the trace while it is running, use the 'tail' subcommand:
#
# sudo kvm_flightrecorder tail
#
# Note that the flight recorder may impact overall system performance by
# consuming CPU cycles. No disk I/O is performed since the ring buffer holds a
# fixed-size in-memory trace.
import sys
import os
tracing_dir = '/sys/kernel/debug/tracing'
def trace_path(*args):
return os.path.join(tracing_dir, *args)
def write_file(path, data):
open(path, 'wb').write(data)
def enable_event(subsystem, event, enable):
write_file(trace_path('events', subsystem, event, 'enable'), '1' if enable else '0')
def enable_subsystem(subsystem, enable):
write_file(trace_path('events', subsystem, 'enable'), '1' if enable else '0')
def start_tracing():
enable_subsystem('kvm', True)
write_file(trace_path('tracing_on'), '1')
def stop_tracing():
write_file(trace_path('tracing_on'), '0')
enable_subsystem('kvm', False)
write_file(trace_path('events', 'enable'), '0')
write_file(trace_path('current_tracer'), 'nop')
def dump_trace():
tracefile = open(trace_path('trace'), 'r')
try:
lines = True
while lines:
lines = tracefile.readlines(64 * 1024)
sys.stdout.writelines(lines)
except KeyboardInterrupt:
pass
def tail_trace():
try:
for line in open(trace_path('trace_pipe'), 'r'):
sys.stdout.write(line)
except KeyboardInterrupt:
pass
def usage():
print 'Usage: %s start [buffer_size_kb] | stop | dump | tail' % sys.argv[0]
print 'Control the KVM flight recorder tracing.'
sys.exit(0)
def main():
if len(sys.argv) < 2:
usage()
cmd = sys.argv[1]
if cmd == '--version':
print 'kvm_flightrecorder version 1.0'
sys.exit(0)
if not os.path.isdir(tracing_dir):
print 'Unable to tracing debugfs directory, try:'
print 'mount -t debugfs none /sys/kernel/debug'
sys.exit(1)
if not os.access(tracing_dir, os.W_OK):
print 'Unable to write to tracing debugfs directory, please run as root'
sys.exit(1)
if cmd == 'start':
stop_tracing() # clean up first
if len(sys.argv) == 3:
try:
buffer_size_kb = int(sys.argv[2])
except ValueError:
print 'Invalid per-cpu trace buffer size in KB'
sys.exit(1)
write_file(trace_path('buffer_size_kb'), str(buffer_size_kb))
print 'Per-CPU ring buffer size set to %d KB' % buffer_size_kb
start_tracing()
print 'KVM flight recorder enabled'
elif cmd == 'stop':
stop_tracing()
print 'KVM flight recorder disabled'
elif cmd == 'dump':
dump_trace()
elif cmd == 'tail':
tail_trace()
else:
usage()
if __name__ == '__main__':
sys.exit(main())
| Python |
#!/usr/bin/python
#
# tool for querying VMX capabilities
#
# Copyright 2009-2010 Red Hat, Inc.
#
# Authors:
# Avi Kivity <avi@redhat.com>
#
# This work is licensed under the terms of the GNU GPL, version 2. See
# the COPYING file in the top-level directory.
MSR_IA32_VMX_BASIC = 0x480
MSR_IA32_VMX_PINBASED_CTLS = 0x481
MSR_IA32_VMX_PROCBASED_CTLS = 0x482
MSR_IA32_VMX_EXIT_CTLS = 0x483
MSR_IA32_VMX_ENTRY_CTLS = 0x484
MSR_IA32_VMX_MISC_CTLS = 0x485
MSR_IA32_VMX_PROCBASED_CTLS2 = 0x48B
MSR_IA32_VMX_EPT_VPID_CAP = 0x48C
MSR_IA32_VMX_TRUE_PINBASED_CTLS = 0x48D
MSR_IA32_VMX_TRUE_PROCBASED_CTLS = 0x48E
MSR_IA32_VMX_TRUE_EXIT_CTLS = 0x48F
MSR_IA32_VMX_TRUE_ENTRY_CTLS = 0x490
class msr(object):
def __init__(self):
try:
self.f = file('/dev/cpu/0/msr')
except:
self.f = file('/dev/msr0')
def read(self, index, default = None):
import struct
self.f.seek(index)
try:
return struct.unpack('Q', self.f.read(8))[0]
except:
return default
class Control(object):
def __init__(self, name, bits, cap_msr, true_cap_msr = None):
self.name = name
self.bits = bits
self.cap_msr = cap_msr
self.true_cap_msr = true_cap_msr
def read2(self, nr):
m = msr()
val = m.read(nr, 0)
return (val & 0xffffffff, val >> 32)
def show(self):
print self.name
mbz, mb1 = self.read2(self.cap_msr)
tmbz, tmb1 = 0, 0
if self.true_cap_msr:
tmbz, tmb1 = self.read2(self.true_cap_msr)
for bit in sorted(self.bits.keys()):
zero = not (mbz & (1 << bit))
one = mb1 & (1 << bit)
true_zero = not (tmbz & (1 << bit))
true_one = tmb1 & (1 << bit)
s= '?'
if (self.true_cap_msr and true_zero and true_one
and one and not zero):
s = 'default'
elif zero and not one:
s = 'no'
elif one and not zero:
s = 'forced'
elif one and zero:
s = 'yes'
print ' %-40s %s' % (self.bits[bit], s)
class Misc(object):
def __init__(self, name, bits, msr):
self.name = name
self.bits = bits
self.msr = msr
def show(self):
print self.name
value = msr().read(self.msr, 0)
def first_bit(key):
if type(key) is tuple:
return key[0]
else:
return key
for bits in sorted(self.bits.keys(), key = first_bit):
if type(bits) is tuple:
lo, hi = bits
fmt = int
else:
lo = hi = bits
def fmt(x):
return { True: 'yes', False: 'no' }[x]
v = (value >> lo) & ((1 << (hi - lo + 1)) - 1)
print ' %-40s %s' % (self.bits[bits], fmt(v))
controls = [
Control(
name = 'pin-based controls',
bits = {
0: 'External interrupt exiting',
3: 'NMI exiting',
5: 'Virtual NMIs',
6: 'Activate VMX-preemption timer',
},
cap_msr = MSR_IA32_VMX_PINBASED_CTLS,
true_cap_msr = MSR_IA32_VMX_TRUE_PINBASED_CTLS,
),
Control(
name = 'primary processor-based controls',
bits = {
2: 'Interrupt window exiting',
3: 'Use TSC offsetting',
7: 'HLT exiting',
9: 'INVLPG exiting',
10: 'MWAIT exiting',
11: 'RDPMC exiting',
12: 'RDTSC exiting',
15: 'CR3-load exiting',
16: 'CR3-store exiting',
19: 'CR8-load exiting',
20: 'CR8-store exiting',
21: 'Use TPR shadow',
22: 'NMI-window exiting',
23: 'MOV-DR exiting',
24: 'Unconditional I/O exiting',
25: 'Use I/O bitmaps',
27: 'Monitor trap flag',
28: 'Use MSR bitmaps',
29: 'MONITOR exiting',
30: 'PAUSE exiting',
31: 'Activate secondary control',
},
cap_msr = MSR_IA32_VMX_PROCBASED_CTLS,
true_cap_msr = MSR_IA32_VMX_TRUE_PROCBASED_CTLS,
),
Control(
name = 'secondary processor-based controls',
bits = {
0: 'Virtualize APIC accesses',
1: 'Enable EPT',
2: 'Descriptor-table exiting',
4: 'Virtualize x2APIC mode',
5: 'Enable VPID',
6: 'WBINVD exiting',
7: 'Unrestricted guest',
10: 'PAUSE-loop exiting',
},
cap_msr = MSR_IA32_VMX_PROCBASED_CTLS2,
),
Control(
name = 'VM-Exit controls',
bits = {
2: 'Save debug controls',
9: 'Host address-space size',
12: 'Load IA32_PERF_GLOBAL_CTRL',
15: 'Acknowledge interrupt on exit',
18: 'Save IA32_PAT',
19: 'Load IA32_PAT',
20: 'Save IA32_EFER',
21: 'Load IA32_EFER',
22: 'Save VMX-preemption timer value',
},
cap_msr = MSR_IA32_VMX_EXIT_CTLS,
true_cap_msr = MSR_IA32_VMX_TRUE_EXIT_CTLS,
),
Control(
name = 'VM-Entry controls',
bits = {
2: 'Load debug controls',
9: 'IA-64 mode guest',
10: 'Entry to SMM',
11: 'Deactivate dual-monitor treatment',
13: 'Load IA32_PERF_GLOBAL_CTRL',
14: 'Load IA32_PAT',
15: 'Load IA32_EFER',
},
cap_msr = MSR_IA32_VMX_ENTRY_CTLS,
true_cap_msr = MSR_IA32_VMX_TRUE_ENTRY_CTLS,
),
Misc(
name = 'Miscellaneous data',
bits = {
(0,4): 'VMX-preemption timer scale (log2)',
5: 'Store EFER.LMA into IA-32e mode guest control',
6: 'HLT activity state',
7: 'Shutdown activity state',
8: 'Wait-for-SIPI activity state',
(16,24): 'Number of CR3-target values',
(25,27): 'MSR-load/store count recommenation',
(32,62): 'MSEG revision identifier',
},
msr = MSR_IA32_VMX_MISC_CTLS,
),
Misc(
name = 'VPID and EPT capabilities',
bits = {
0: 'Execute-only EPT translations',
6: 'Page-walk length 4',
8: 'Paging-structure memory type UC',
14: 'Paging-structure memory type WB',
16: '2MB EPT pages',
17: '1GB EPT pages',
20: 'INVEPT supported',
25: 'Single-context INVEPT',
26: 'All-context INVEPT',
32: 'INVVPID supported',
40: 'Individual-address INVVPID',
41: 'Single-context INVVPID',
42: 'All-context INVVPID',
43: 'Single-context-retaining-globals INVVPID',
},
msr = MSR_IA32_VMX_EPT_VPID_CAP,
),
]
for c in controls:
c.show()
| Python |
#!/usr/bin/python
#
# top-like utility for displaying kvm statistics
#
# Copyright 2006-2008 Qumranet Technologies
# Copyright 2008-2011 Red Hat, Inc.
#
# Authors:
# Avi Kivity <avi@redhat.com>
#
# This work is licensed under the terms of the GNU GPL, version 2. See
# the COPYING file in the top-level directory.
import curses
import sys, os, time, optparse
class DebugfsProvider(object):
def __init__(self):
self.base = '/sys/kernel/debug/kvm'
self._fields = os.listdir(self.base)
def fields(self):
return self._fields
def select(self, fields):
self._fields = fields
def read(self):
def val(key):
return int(file(self.base + '/' + key).read())
return dict([(key, val(key)) for key in self._fields])
vmx_exit_reasons = {
0: 'EXCEPTION_NMI',
1: 'EXTERNAL_INTERRUPT',
2: 'TRIPLE_FAULT',
7: 'PENDING_INTERRUPT',
8: 'NMI_WINDOW',
9: 'TASK_SWITCH',
10: 'CPUID',
12: 'HLT',
14: 'INVLPG',
15: 'RDPMC',
16: 'RDTSC',
18: 'VMCALL',
19: 'VMCLEAR',
20: 'VMLAUNCH',
21: 'VMPTRLD',
22: 'VMPTRST',
23: 'VMREAD',
24: 'VMRESUME',
25: 'VMWRITE',
26: 'VMOFF',
27: 'VMON',
28: 'CR_ACCESS',
29: 'DR_ACCESS',
30: 'IO_INSTRUCTION',
31: 'MSR_READ',
32: 'MSR_WRITE',
33: 'INVALID_STATE',
36: 'MWAIT_INSTRUCTION',
39: 'MONITOR_INSTRUCTION',
40: 'PAUSE_INSTRUCTION',
41: 'MCE_DURING_VMENTRY',
43: 'TPR_BELOW_THRESHOLD',
44: 'APIC_ACCESS',
48: 'EPT_VIOLATION',
49: 'EPT_MISCONFIG',
54: 'WBINVD',
55: 'XSETBV',
}
svm_exit_reasons = {
0x000: 'READ_CR0',
0x003: 'READ_CR3',
0x004: 'READ_CR4',
0x008: 'READ_CR8',
0x010: 'WRITE_CR0',
0x013: 'WRITE_CR3',
0x014: 'WRITE_CR4',
0x018: 'WRITE_CR8',
0x020: 'READ_DR0',
0x021: 'READ_DR1',
0x022: 'READ_DR2',
0x023: 'READ_DR3',
0x024: 'READ_DR4',
0x025: 'READ_DR5',
0x026: 'READ_DR6',
0x027: 'READ_DR7',
0x030: 'WRITE_DR0',
0x031: 'WRITE_DR1',
0x032: 'WRITE_DR2',
0x033: 'WRITE_DR3',
0x034: 'WRITE_DR4',
0x035: 'WRITE_DR5',
0x036: 'WRITE_DR6',
0x037: 'WRITE_DR7',
0x040: 'EXCP_BASE',
0x060: 'INTR',
0x061: 'NMI',
0x062: 'SMI',
0x063: 'INIT',
0x064: 'VINTR',
0x065: 'CR0_SEL_WRITE',
0x066: 'IDTR_READ',
0x067: 'GDTR_READ',
0x068: 'LDTR_READ',
0x069: 'TR_READ',
0x06a: 'IDTR_WRITE',
0x06b: 'GDTR_WRITE',
0x06c: 'LDTR_WRITE',
0x06d: 'TR_WRITE',
0x06e: 'RDTSC',
0x06f: 'RDPMC',
0x070: 'PUSHF',
0x071: 'POPF',
0x072: 'CPUID',
0x073: 'RSM',
0x074: 'IRET',
0x075: 'SWINT',
0x076: 'INVD',
0x077: 'PAUSE',
0x078: 'HLT',
0x079: 'INVLPG',
0x07a: 'INVLPGA',
0x07b: 'IOIO',
0x07c: 'MSR',
0x07d: 'TASK_SWITCH',
0x07e: 'FERR_FREEZE',
0x07f: 'SHUTDOWN',
0x080: 'VMRUN',
0x081: 'VMMCALL',
0x082: 'VMLOAD',
0x083: 'VMSAVE',
0x084: 'STGI',
0x085: 'CLGI',
0x086: 'SKINIT',
0x087: 'RDTSCP',
0x088: 'ICEBP',
0x089: 'WBINVD',
0x08a: 'MONITOR',
0x08b: 'MWAIT',
0x08c: 'MWAIT_COND',
0x400: 'NPF',
}
vendor_exit_reasons = {
'vmx': vmx_exit_reasons,
'svm': svm_exit_reasons,
}
exit_reasons = None
for line in file('/proc/cpuinfo').readlines():
if line.startswith('flags'):
for flag in line.split():
if flag in vendor_exit_reasons:
exit_reasons = vendor_exit_reasons[flag]
filters = {
'kvm_exit': ('exit_reason', exit_reasons)
}
def invert(d):
return dict((x[1], x[0]) for x in d.iteritems())
for f in filters:
filters[f] = (filters[f][0], invert(filters[f][1]))
import ctypes, struct, array
libc = ctypes.CDLL('libc.so.6')
syscall = libc.syscall
class perf_event_attr(ctypes.Structure):
_fields_ = [('type', ctypes.c_uint32),
('size', ctypes.c_uint32),
('config', ctypes.c_uint64),
('sample_freq', ctypes.c_uint64),
('sample_type', ctypes.c_uint64),
('read_format', ctypes.c_uint64),
('flags', ctypes.c_uint64),
('wakeup_events', ctypes.c_uint32),
('bp_type', ctypes.c_uint32),
('bp_addr', ctypes.c_uint64),
('bp_len', ctypes.c_uint64),
]
def _perf_event_open(attr, pid, cpu, group_fd, flags):
return syscall(298, ctypes.pointer(attr), ctypes.c_int(pid),
ctypes.c_int(cpu), ctypes.c_int(group_fd),
ctypes.c_long(flags))
PERF_TYPE_HARDWARE = 0
PERF_TYPE_SOFTWARE = 1
PERF_TYPE_TRACEPOINT = 2
PERF_TYPE_HW_CACHE = 3
PERF_TYPE_RAW = 4
PERF_TYPE_BREAKPOINT = 5
PERF_SAMPLE_IP = 1 << 0
PERF_SAMPLE_TID = 1 << 1
PERF_SAMPLE_TIME = 1 << 2
PERF_SAMPLE_ADDR = 1 << 3
PERF_SAMPLE_READ = 1 << 4
PERF_SAMPLE_CALLCHAIN = 1 << 5
PERF_SAMPLE_ID = 1 << 6
PERF_SAMPLE_CPU = 1 << 7
PERF_SAMPLE_PERIOD = 1 << 8
PERF_SAMPLE_STREAM_ID = 1 << 9
PERF_SAMPLE_RAW = 1 << 10
PERF_FORMAT_TOTAL_TIME_ENABLED = 1 << 0
PERF_FORMAT_TOTAL_TIME_RUNNING = 1 << 1
PERF_FORMAT_ID = 1 << 2
PERF_FORMAT_GROUP = 1 << 3
import re
sys_tracing = '/sys/kernel/debug/tracing'
class Group(object):
def __init__(self, cpu):
self.events = []
self.group_leader = None
self.cpu = cpu
def add_event(self, name, event_set, tracepoint, filter = None):
self.events.append(Event(group = self,
name = name, event_set = event_set,
tracepoint = tracepoint, filter = filter))
if len(self.events) == 1:
self.file = os.fdopen(self.events[0].fd)
def read(self):
bytes = 8 * (1 + len(self.events))
fmt = 'xxxxxxxx' + 'q' * len(self.events)
return dict(zip([event.name for event in self.events],
struct.unpack(fmt, self.file.read(bytes))))
class Event(object):
def __init__(self, group, name, event_set, tracepoint, filter = None):
self.name = name
attr = perf_event_attr()
attr.type = PERF_TYPE_TRACEPOINT
attr.size = ctypes.sizeof(attr)
id_path = os.path.join(sys_tracing, 'events', event_set,
tracepoint, 'id')
id = int(file(id_path).read())
attr.config = id
attr.sample_type = (PERF_SAMPLE_RAW
| PERF_SAMPLE_TIME
| PERF_SAMPLE_CPU)
attr.sample_period = 1
attr.read_format = PERF_FORMAT_GROUP
group_leader = -1
if group.events:
group_leader = group.events[0].fd
fd = _perf_event_open(attr, -1, group.cpu, group_leader, 0)
if fd == -1:
raise Exception('perf_event_open failed')
if filter:
import fcntl
fcntl.ioctl(fd, 0x40082406, filter)
self.fd = fd
def enable(self):
import fcntl
fcntl.ioctl(self.fd, 0x00002400, 0)
def disable(self):
import fcntl
fcntl.ioctl(self.fd, 0x00002401, 0)
class TracepointProvider(object):
def __init__(self):
path = os.path.join(sys_tracing, 'events', 'kvm')
fields = [f
for f in os.listdir(path)
if os.path.isdir(os.path.join(path, f))]
extra = []
for f in fields:
if f in filters:
subfield, values = filters[f]
for name, number in values.iteritems():
extra.append(f + '(' + name + ')')
fields += extra
self._setup(fields)
self.select(fields)
def fields(self):
return self._fields
def _setup(self, _fields):
self._fields = _fields
cpure = r'cpu([0-9]+)'
self.cpus = [int(re.match(cpure, x).group(1))
for x in os.listdir('/sys/devices/system/cpu')
if re.match(cpure, x)]
import resource
nfiles = len(self.cpus) * 1000
resource.setrlimit(resource.RLIMIT_NOFILE, (nfiles, nfiles))
events = []
self.group_leaders = []
for cpu in self.cpus:
group = Group(cpu)
for name in _fields:
tracepoint = name
filter = None
m = re.match(r'(.*)\((.*)\)', name)
if m:
tracepoint, sub = m.groups()
filter = '%s==%d\0' % (filters[tracepoint][0],
filters[tracepoint][1][sub])
event = group.add_event(name, event_set = 'kvm',
tracepoint = tracepoint,
filter = filter)
self.group_leaders.append(group)
def select(self, fields):
for group in self.group_leaders:
for event in group.events:
if event.name in fields:
event.enable()
else:
event.disable()
def read(self):
from collections import defaultdict
ret = defaultdict(int)
for group in self.group_leaders:
for name, val in group.read().iteritems():
ret[name] += val
return ret
class Stats:
def __init__(self, provider, fields = None):
self.provider = provider
self.fields_filter = fields
self._update()
def _update(self):
def wanted(key):
import re
if not self.fields_filter:
return True
return re.match(self.fields_filter, key) is not None
self.values = dict([(key, None)
for key in provider.fields()
if wanted(key)])
self.provider.select(self.values.keys())
def set_fields_filter(self, fields_filter):
self.fields_filter = fields_filter
self._update()
def get(self):
new = self.provider.read()
for key in self.provider.fields():
oldval = self.values.get(key, (0, 0))
newval = new[key]
newdelta = None
if oldval is not None:
newdelta = newval - oldval[0]
self.values[key] = (newval, newdelta)
return self.values
if not os.access('/sys/kernel/debug', os.F_OK):
print 'Please enable CONFIG_DEBUG_FS in your kernel'
sys.exit(1)
if not os.access('/sys/kernel/debug/kvm', os.F_OK):
print "Please mount debugfs ('mount -t debugfs debugfs /sys/kernel/debug')"
print "and ensure the kvm modules are loaded"
sys.exit(1)
label_width = 40
number_width = 10
def tui(screen, stats):
curses.use_default_colors()
curses.noecho()
drilldown = False
fields_filter = stats.fields_filter
def update_drilldown():
if not fields_filter:
if drilldown:
stats.set_fields_filter(None)
else:
stats.set_fields_filter(r'^[^\(]*$')
update_drilldown()
def refresh(sleeptime):
screen.erase()
screen.addstr(0, 0, 'kvm statistics')
row = 2
s = stats.get()
def sortkey(x):
if s[x][1]:
return (-s[x][1], -s[x][0])
else:
return (0, -s[x][0])
for key in sorted(s.keys(), key = sortkey):
if row >= screen.getmaxyx()[0]:
break
values = s[key]
if not values[0] and not values[1]:
break
col = 1
screen.addstr(row, col, key)
col += label_width
screen.addstr(row, col, '%10d' % (values[0],))
col += number_width
if values[1] is not None:
screen.addstr(row, col, '%8d' % (values[1] / sleeptime,))
row += 1
screen.refresh()
sleeptime = 0.25
while True:
refresh(sleeptime)
curses.halfdelay(int(sleeptime * 10))
sleeptime = 3
try:
c = screen.getkey()
if c == 'x':
drilldown = not drilldown
update_drilldown()
if c == 'q':
break
except KeyboardInterrupt:
break
except curses.error:
continue
def batch(stats):
s = stats.get()
time.sleep(1)
s = stats.get()
for key in sorted(s.keys()):
values = s[key]
print '%-22s%10d%10d' % (key, values[0], values[1])
def log(stats):
keys = sorted(stats.get().iterkeys())
def banner():
for k in keys:
print '%10s' % k[0:9],
print
def statline():
s = stats.get()
for k in keys:
print ' %9d' % s[k][1],
print
line = 0
banner_repeat = 20
while True:
time.sleep(1)
if line % banner_repeat == 0:
banner()
statline()
line += 1
options = optparse.OptionParser()
options.add_option('-1', '--once', '--batch',
action = 'store_true',
default = False,
dest = 'once',
help = 'run in batch mode for one second',
)
options.add_option('-l', '--log',
action = 'store_true',
default = False,
dest = 'log',
help = 'run in logging mode (like vmstat)',
)
options.add_option('-f', '--fields',
action = 'store',
default = None,
dest = 'fields',
help = 'fields to display (regex)',
)
(options, args) = options.parse_args(sys.argv)
try:
provider = TracepointProvider()
except:
provider = DebugfsProvider()
stats = Stats(provider, fields = options.fields)
if options.log:
log(stats)
elif not options.once:
import curses.wrapper
curses.wrapper(tui, stats)
else:
batch(stats)
| Python |
#!/usr/bin/env python
#
# Pretty-printer for simple trace backend binary trace files
#
# Copyright IBM, Corp. 2010
#
# This work is licensed under the terms of the GNU GPL, version 2. See
# the COPYING file in the top-level directory.
#
# For help see docs/tracing.txt
import struct
import re
import inspect
header_event_id = 0xffffffffffffffff
header_magic = 0xf2b177cb0aa429b4
header_version = 0
dropped_event_id = 0xfffffffffffffffe
trace_fmt = '=QQQQQQQQ'
trace_len = struct.calcsize(trace_fmt)
event_re = re.compile(r'(disable\s+)?([a-zA-Z0-9_]+)\(([^)]*)\).*')
def parse_events(fobj):
"""Parse a trace-events file into {event_num: (name, arg1, ...)}."""
def get_argnames(args):
"""Extract argument names from a parameter list."""
return tuple(arg.split()[-1].lstrip('*') for arg in args.split(','))
events = {dropped_event_id: ('dropped', 'count')}
event_num = 0
for line in fobj:
m = event_re.match(line.strip())
if m is None:
continue
disable, name, args = m.groups()
events[event_num] = (name,) + get_argnames(args)
event_num += 1
return events
def read_record(fobj):
"""Deserialize a trace record from a file into a tuple (event_num, timestamp, arg1, ..., arg6)."""
s = fobj.read(trace_len)
if len(s) != trace_len:
return None
return struct.unpack(trace_fmt, s)
def read_trace_file(fobj):
"""Deserialize trace records from a file, yielding record tuples (event_num, timestamp, arg1, ..., arg6)."""
header = read_record(fobj)
if header is None or \
header[0] != header_event_id or \
header[1] != header_magic or \
header[2] != header_version:
raise ValueError('not a trace file or incompatible version')
while True:
rec = read_record(fobj)
if rec is None:
break
yield rec
class Analyzer(object):
"""A trace file analyzer which processes trace records.
An analyzer can be passed to run() or process(). The begin() method is
invoked, then each trace record is processed, and finally the end() method
is invoked.
If a method matching a trace event name exists, it is invoked to process
that trace record. Otherwise the catchall() method is invoked."""
def begin(self):
"""Called at the start of the trace."""
pass
def catchall(self, event, rec):
"""Called if no specific method for processing a trace event has been found."""
pass
def end(self):
"""Called at the end of the trace."""
pass
def process(events, log, analyzer):
"""Invoke an analyzer on each event in a log."""
if isinstance(events, str):
events = parse_events(open(events, 'r'))
if isinstance(log, str):
log = open(log, 'rb')
def build_fn(analyzer, event):
fn = getattr(analyzer, event[0], None)
if fn is None:
return analyzer.catchall
event_argcount = len(event) - 1
fn_argcount = len(inspect.getargspec(fn)[0]) - 1
if fn_argcount == event_argcount + 1:
# Include timestamp as first argument
return lambda _, rec: fn(*rec[1:2 + event_argcount])
else:
# Just arguments, no timestamp
return lambda _, rec: fn(*rec[2:2 + event_argcount])
analyzer.begin()
fn_cache = {}
for rec in read_trace_file(log):
event_num = rec[0]
event = events[event_num]
if event_num not in fn_cache:
fn_cache[event_num] = build_fn(analyzer, event)
fn_cache[event_num](event, rec)
analyzer.end()
def run(analyzer):
"""Execute an analyzer on a trace file given on the command-line.
This function is useful as a driver for simple analysis scripts. More
advanced scripts will want to call process() instead."""
import sys
if len(sys.argv) != 3:
sys.stderr.write('usage: %s <trace-events> <trace-file>\n' % sys.argv[0])
sys.exit(1)
events = parse_events(open(sys.argv[1], 'r'))
process(events, sys.argv[2], analyzer)
if __name__ == '__main__':
class Formatter(Analyzer):
def __init__(self):
self.last_timestamp = None
def catchall(self, event, rec):
timestamp = rec[1]
if self.last_timestamp is None:
self.last_timestamp = timestamp
delta_ns = timestamp - self.last_timestamp
self.last_timestamp = timestamp
fields = [event[0], '%0.3f' % (delta_ns / 1000.0)]
for i in xrange(1, len(event)):
fields.append('%s=0x%x' % (event[i], rec[i + 1]))
print ' '.join(fields)
run(Formatter())
| Python |
#!/usr/bin/python
# GDB debugging support
#
# Copyright 2012 Red Hat, Inc. and/or its affiliates
#
# Authors:
# Avi Kivity <avi@redhat.com>
#
# This work is licensed under the terms of the GNU GPL, version 2. See
# the COPYING file in the top-level directory.
#
# Contributions after 2012-01-13 are licensed under the terms of the
# GNU GPL, version 2 or (at your option) any later version.
import gdb
def isnull(ptr):
return ptr == gdb.Value(0).cast(ptr.type)
def int128(p):
return long(p['lo']) + (long(p['hi']) << 64)
class QemuCommand(gdb.Command):
'''Prefix for QEMU debug support commands'''
def __init__(self):
gdb.Command.__init__(self, 'qemu', gdb.COMMAND_DATA,
gdb.COMPLETE_NONE, True)
class MtreeCommand(gdb.Command):
'''Display the memory tree hierarchy'''
def __init__(self):
gdb.Command.__init__(self, 'qemu mtree', gdb.COMMAND_DATA,
gdb.COMPLETE_NONE)
self.queue = []
def invoke(self, arg, from_tty):
self.seen = set()
self.queue_root('address_space_memory')
self.queue_root('address_space_io')
self.process_queue()
def queue_root(self, varname):
ptr = gdb.parse_and_eval(varname)['root']
self.queue.append(ptr)
def process_queue(self):
while self.queue:
ptr = self.queue.pop(0)
if long(ptr) in self.seen:
continue
self.print_item(ptr)
def print_item(self, ptr, offset = gdb.Value(0), level = 0):
self.seen.add(long(ptr))
addr = ptr['addr']
addr += offset
size = int128(ptr['size'])
alias = ptr['alias']
klass = ''
if not isnull(alias):
klass = ' (alias)'
elif not isnull(ptr['ops']):
klass = ' (I/O)'
elif bool(ptr['ram']):
klass = ' (RAM)'
gdb.write('%s%016x-%016x %s%s (@ %s)\n'
% (' ' * level,
long(addr),
long(addr + (size - 1)),
ptr['name'].string(),
klass,
ptr,
),
gdb.STDOUT)
if not isnull(alias):
gdb.write('%s alias: %s@%016x (@ %s)\n' %
(' ' * level,
alias['name'].string(),
ptr['alias_offset'],
alias,
),
gdb.STDOUT)
self.queue.append(alias)
subregion = ptr['subregions']['tqh_first']
level += 1
while not isnull(subregion):
self.print_item(subregion, addr, level)
subregion = subregion['subregions_link']['tqe_next']
QemuCommand()
MtreeCommand()
| Python |
#
# QAPI types generator
#
# Copyright IBM, Corp. 2011
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
#
# This work is licensed under the terms of the GNU GPLv2.
# See the COPYING.LIB file in the top-level directory.
from ordereddict import OrderedDict
from qapi import *
import sys
import os
import getopt
import errno
def generate_fwd_struct(name, members):
return mcgen('''
typedef struct %(name)s %(name)s;
typedef struct %(name)sList
{
%(name)s *value;
struct %(name)sList *next;
} %(name)sList;
''',
name=name)
def generate_struct(structname, fieldname, members):
ret = mcgen('''
struct %(name)s
{
''',
name=structname)
for argname, argentry, optional, structured in parse_args(members):
if optional:
ret += mcgen('''
bool has_%(c_name)s;
''',
c_name=c_var(argname))
if structured:
push_indent()
ret += generate_struct("", argname, argentry)
pop_indent()
else:
ret += mcgen('''
%(c_type)s %(c_name)s;
''',
c_type=c_type(argentry), c_name=c_var(argname))
if len(fieldname):
fieldname = " " + fieldname
ret += mcgen('''
}%(field)s;
''',
field=fieldname)
return ret
def generate_enum_lookup(name, values):
ret = mcgen('''
const char *%(name)s_lookup[] = {
''',
name=name)
i = 0
for value in values:
ret += mcgen('''
"%(value)s",
''',
value=value.lower())
ret += mcgen('''
NULL,
};
''')
return ret
def generate_enum(name, values):
lookup_decl = mcgen('''
extern const char *%(name)s_lookup[];
''',
name=name)
enum_decl = mcgen('''
typedef enum %(name)s
{
''',
name=name)
# append automatically generated _MAX value
enum_values = values + [ 'MAX' ]
i = 0
for value in enum_values:
enum_decl += mcgen('''
%(abbrev)s_%(value)s = %(i)d,
''',
abbrev=de_camel_case(name).upper(),
value=c_fun(value).upper(),
i=i)
i += 1
enum_decl += mcgen('''
} %(name)s;
''',
name=name)
return lookup_decl + enum_decl
def generate_union(name, typeinfo):
ret = mcgen('''
struct %(name)s
{
%(name)sKind kind;
union {
void *data;
''',
name=name)
for key in typeinfo:
ret += mcgen('''
%(c_type)s %(c_name)s;
''',
c_type=c_type(typeinfo[key]),
c_name=c_fun(key))
ret += mcgen('''
};
};
''')
return ret
def generate_type_cleanup_decl(name):
ret = mcgen('''
void qapi_free_%(type)s(%(c_type)s obj);
''',
c_type=c_type(name),type=name)
return ret
def generate_type_cleanup(name):
ret = mcgen('''
void qapi_free_%(type)s(%(c_type)s obj)
{
QapiDeallocVisitor *md;
Visitor *v;
if (!obj) {
return;
}
md = qapi_dealloc_visitor_new();
v = qapi_dealloc_get_visitor(md);
visit_type_%(type)s(v, &obj, NULL, NULL);
qapi_dealloc_visitor_cleanup(md);
}
''',
c_type=c_type(name),type=name)
return ret
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "chp:o:",
["source", "header", "prefix=", "output-dir="])
except getopt.GetoptError, err:
print str(err)
sys.exit(1)
output_dir = ""
prefix = ""
c_file = 'qapi-types.c'
h_file = 'qapi-types.h'
do_c = False
do_h = False
for o, a in opts:
if o in ("-p", "--prefix"):
prefix = a
elif o in ("-o", "--output-dir"):
output_dir = a + "/"
elif o in ("-c", "--source"):
do_c = True
elif o in ("-h", "--header"):
do_h = True
if not do_c and not do_h:
do_c = True
do_h = True
c_file = output_dir + prefix + c_file
h_file = output_dir + prefix + h_file
try:
os.makedirs(output_dir)
except os.error, e:
if e.errno != errno.EEXIST:
raise
def maybe_open(really, name, opt):
if really:
return open(name, opt)
else:
import StringIO
return StringIO.StringIO()
fdef = maybe_open(do_c, c_file, 'w')
fdecl = maybe_open(do_h, h_file, 'w')
fdef.write(mcgen('''
/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
/*
* deallocation functions for schema-defined QAPI types
*
* Copyright IBM, Corp. 2011
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
* Michael Roth <mdroth@linux.vnet.ibm.com>
*
* This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
* See the COPYING.LIB file in the top-level directory.
*
*/
#include "qapi/qapi-dealloc-visitor.h"
#include "%(prefix)sqapi-types.h"
#include "%(prefix)sqapi-visit.h"
''', prefix=prefix))
fdecl.write(mcgen('''
/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
/*
* schema-defined QAPI types
*
* Copyright IBM, Corp. 2011
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
* See the COPYING.LIB file in the top-level directory.
*
*/
#ifndef %(guard)s
#define %(guard)s
#include "qapi/qapi-types-core.h"
''',
guard=guardname(h_file)))
exprs = parse_schema(sys.stdin)
exprs = filter(lambda expr: not expr.has_key('gen'), exprs)
for expr in exprs:
ret = "\n"
if expr.has_key('type'):
ret += generate_fwd_struct(expr['type'], expr['data'])
elif expr.has_key('enum'):
ret += generate_enum(expr['enum'], expr['data'])
fdef.write(generate_enum_lookup(expr['enum'], expr['data']))
elif expr.has_key('union'):
ret += generate_fwd_struct(expr['union'], expr['data']) + "\n"
ret += generate_enum('%sKind' % expr['union'], expr['data'].keys())
fdef.write(generate_enum_lookup('%sKind' % expr['union'], expr['data'].keys()))
else:
continue
fdecl.write(ret)
for expr in exprs:
ret = "\n"
if expr.has_key('type'):
ret += generate_struct(expr['type'], "", expr['data']) + "\n"
ret += generate_type_cleanup_decl(expr['type'] + "List")
fdef.write(generate_type_cleanup(expr['type'] + "List") + "\n")
ret += generate_type_cleanup_decl(expr['type'])
fdef.write(generate_type_cleanup(expr['type']) + "\n")
elif expr.has_key('union'):
ret += generate_union(expr['union'], expr['data'])
ret += generate_type_cleanup_decl(expr['union'] + "List")
fdef.write(generate_type_cleanup(expr['union'] + "List") + "\n")
ret += generate_type_cleanup_decl(expr['union'])
fdef.write(generate_type_cleanup(expr['union']) + "\n")
else:
continue
fdecl.write(ret)
fdecl.write('''
#endif
''')
fdecl.flush()
fdecl.close()
fdef.flush()
fdef.close()
| Python |
#!/usr/bin/env python
# Pretty print 9p simpletrace log
# Usage: ./analyse-9p-simpletrace <trace-events> <trace-pid>
#
# Author: Harsh Prateek Bora
import os
import simpletrace
symbol_9p = {
6 : 'TLERROR',
7 : 'RLERROR',
8 : 'TSTATFS',
9 : 'RSTATFS',
12 : 'TLOPEN',
13 : 'RLOPEN',
14 : 'TLCREATE',
15 : 'RLCREATE',
16 : 'TSYMLINK',
17 : 'RSYMLINK',
18 : 'TMKNOD',
19 : 'RMKNOD',
20 : 'TRENAME',
21 : 'RRENAME',
22 : 'TREADLINK',
23 : 'RREADLINK',
24 : 'TGETATTR',
25 : 'RGETATTR',
26 : 'TSETATTR',
27 : 'RSETATTR',
30 : 'TXATTRWALK',
31 : 'RXATTRWALK',
32 : 'TXATTRCREATE',
33 : 'RXATTRCREATE',
40 : 'TREADDIR',
41 : 'RREADDIR',
50 : 'TFSYNC',
51 : 'RFSYNC',
52 : 'TLOCK',
53 : 'RLOCK',
54 : 'TGETLOCK',
55 : 'RGETLOCK',
70 : 'TLINK',
71 : 'RLINK',
72 : 'TMKDIR',
73 : 'RMKDIR',
74 : 'TRENAMEAT',
75 : 'RRENAMEAT',
76 : 'TUNLINKAT',
77 : 'RUNLINKAT',
100 : 'TVERSION',
101 : 'RVERSION',
102 : 'TAUTH',
103 : 'RAUTH',
104 : 'TATTACH',
105 : 'RATTACH',
106 : 'TERROR',
107 : 'RERROR',
108 : 'TFLUSH',
109 : 'RFLUSH',
110 : 'TWALK',
111 : 'RWALK',
112 : 'TOPEN',
113 : 'ROPEN',
114 : 'TCREATE',
115 : 'RCREATE',
116 : 'TREAD',
117 : 'RREAD',
118 : 'TWRITE',
119 : 'RWRITE',
120 : 'TCLUNK',
121 : 'RCLUNK',
122 : 'TREMOVE',
123 : 'RREMOVE',
124 : 'TSTAT',
125 : 'RSTAT',
126 : 'TWSTAT',
127 : 'RWSTAT'
}
class VirtFSRequestTracker(simpletrace.Analyzer):
def begin(self):
print "Pretty printing 9p simpletrace log ..."
def v9fs_rerror(self, tag, id, err):
print "RERROR (tag =", tag, ", id =", symbol_9p[id], ", err = \"", os.strerror(err), "\")"
def v9fs_version(self, tag, id, msize, version):
print "TVERSION (tag =", tag, ", msize =", msize, ", version =", version, ")"
def v9fs_version_return(self, tag, id, msize, version):
print "RVERSION (tag =", tag, ", msize =", msize, ", version =", version, ")"
def v9fs_attach(self, tag, id, fid, afid, uname, aname):
print "TATTACH (tag =", tag, ", fid =", fid, ", afid =", afid, ", uname =", uname, ", aname =", aname, ")"
def v9fs_attach_return(self, tag, id, type, version, path):
print "RATTACH (tag =", tag, ", qid={type =", type, ", version =", version, ", path =", path, "})"
def v9fs_stat(self, tag, id, fid):
print "TSTAT (tag =", tag, ", fid =", fid, ")"
def v9fs_stat_return(self, tag, id, mode, atime, mtime, length):
print "RSTAT (tag =", tag, ", mode =", mode, ", atime =", atime, ", mtime =", mtime, ", length =", length, ")"
def v9fs_getattr(self, tag, id, fid, request_mask):
print "TGETATTR (tag =", tag, ", fid =", fid, ", request_mask =", hex(request_mask), ")"
def v9fs_getattr_return(self, tag, id, result_mask, mode, uid, gid):
print "RGETATTR (tag =", tag, ", result_mask =", hex(result_mask), ", mode =", oct(mode), ", uid =", uid, ", gid =", gid, ")"
def v9fs_walk(self, tag, id, fid, newfid, nwnames):
print "TWALK (tag =", tag, ", fid =", fid, ", newfid =", newfid, ", nwnames =", nwnames, ")"
def v9fs_walk_return(self, tag, id, nwnames, qids):
print "RWALK (tag =", tag, ", nwnames =", nwnames, ", qids =", hex(qids), ")"
def v9fs_open(self, tag, id, fid, mode):
print "TOPEN (tag =", tag, ", fid =", fid, ", mode =", oct(mode), ")"
def v9fs_open_return(self, tag, id, type, version, path, iounit):
print "ROPEN (tag =", tag, ", qid={type =", type, ", version =", version, ", path =", path, "}, iounit =", iounit, ")"
def v9fs_lcreate(self, tag, id, dfid, flags, mode, gid):
print "TLCREATE (tag =", tag, ", dfid =", dfid, ", flags =", oct(flags), ", mode =", oct(mode), ", gid =", gid, ")"
def v9fs_lcreate_return(self, tag, id, type, version, path, iounit):
print "RLCREATE (tag =", tag, ", qid={type =", type, ", version =", version, ", path =", path, "}, iounit =", iounit, ")"
def v9fs_fsync(self, tag, id, fid, datasync):
print "TFSYNC (tag =", tag, ", fid =", fid, ", datasync =", datasync, ")"
def v9fs_clunk(self, tag, id, fid):
print "TCLUNK (tag =", tag, ", fid =", fid, ")"
def v9fs_read(self, tag, id, fid, off, max_count):
print "TREAD (tag =", tag, ", fid =", fid, ", off =", off, ", max_count =", max_count, ")"
def v9fs_read_return(self, tag, id, count, err):
print "RREAD (tag =", tag, ", count =", count, ", err =", err, ")"
def v9fs_readdir(self, tag, id, fid, offset, max_count):
print "TREADDIR (tag =", tag, ", fid =", fid, ", offset =", offset, ", max_count =", max_count, ")"
def v9fs_readdir_return(self, tag, id, count, retval):
print "RREADDIR (tag =", tag, ", count =", count, ", retval =", retval, ")"
def v9fs_write(self, tag, id, fid, off, count, cnt):
print "TWRITE (tag =", tag, ", fid =", fid, ", off =", off, ", count =", count, ", cnt =", cnt, ")"
def v9fs_write_return(self, tag, id, total, err):
print "RWRITE (tag =", tag, ", total =", total, ", err =", err, ")"
def v9fs_create(self, tag, id, fid, name, perm, mode):
print "TCREATE (tag =", tag, ", fid =", fid, ", perm =", oct(perm), ", name =", name, ", mode =", oct(mode), ")"
def v9fs_create_return(self, tag, id, type, version, path, iounit):
print "RCREATE (tag =", tag, ", qid={type =", type, ", version =", version, ", path =", path, "}, iounit =", iounit, ")"
def v9fs_symlink(self, tag, id, fid, name, symname, gid):
print "TSYMLINK (tag =", tag, ", fid =", fid, ", name =", name, ", symname =", symname, ", gid =", gid, ")"
def v9fs_symlink_return(self, tag, id, type, version, path):
print "RSYMLINK (tag =", tag, ", qid={type =", type, ", version =", version, ", path =", path, "})"
def v9fs_flush(self, tag, id, flush_tag):
print "TFLUSH (tag =", tag, ", flush_tag =", flush_tag, ")"
def v9fs_link(self, tag, id, dfid, oldfid, name):
print "TLINK (tag =", tag, ", dfid =", dfid, ", oldfid =", oldfid, ", name =", name, ")"
def v9fs_remove(self, tag, id, fid):
print "TREMOVE (tag =", tag, ", fid =", fid, ")"
def v9fs_wstat(self, tag, id, fid, mode, atime, mtime):
print "TWSTAT (tag =", tag, ", fid =", fid, ", mode =", oct(mode), ", atime =", atime, "mtime =", mtime, ")"
def v9fs_mknod(self, tag, id, fid, mode, major, minor):
print "TMKNOD (tag =", tag, ", fid =", fid, ", mode =", oct(mode), ", major =", major, ", minor =", minor, ")"
def v9fs_lock(self, tag, id, fid, type, start, length):
print "TLOCK (tag =", tag, ", fid =", fid, "type =", type, ", start =", start, ", length =", length, ")"
def v9fs_lock_return(self, tag, id, status):
print "RLOCK (tag =", tag, ", status =", status, ")"
def v9fs_getlock(self, tag, id, fid, type, start, length):
print "TGETLOCK (tag =", tag, ", fid =", fid, "type =", type, ", start =", start, ", length =", length, ")"
def v9fs_getlock_return(self, tag, id, type, start, length, proc_id):
print "RGETLOCK (tag =", tag, "type =", type, ", start =", start, ", length =", length, ", proc_id =", proc_id, ")"
def v9fs_mkdir(self, tag, id, fid, name, mode, gid):
print "TMKDIR (tag =", tag, ", fid =", fid, ", name =", name, ", mode =", mode, ", gid =", gid, ")"
def v9fs_mkdir_return(self, tag, id, type, version, path, err):
print "RMKDIR (tag =", tag, ", qid={type =", type, ", version =", version, ", path =", path, "}, err =", err, ")"
def v9fs_xattrwalk(self, tag, id, fid, newfid, name):
print "TXATTRWALK (tag =", tag, ", fid =", fid, ", newfid =", newfid, ", xattr name =", name, ")"
def v9fs_xattrwalk_return(self, tag, id, size):
print "RXATTRWALK (tag =", tag, ", xattrsize =", size, ")"
def v9fs_xattrcreate(self, tag, id, fid, name, size, flags):
print "TXATTRCREATE (tag =", tag, ", fid =", fid, ", name =", name, ", xattrsize =", size, ", flags =", flags, ")"
def v9fs_readlink(self, tag, id, fid):
print "TREADLINK (tag =", tag, ", fid =", fid, ")"
def v9fs_readlink_return(self, tag, id, target):
print "RREADLINK (tag =", tag, ", target =", target, ")"
simpletrace.run(VirtFSRequestTracker())
| Python |
#
# QAPI command marshaller generator
#
# Copyright IBM, Corp. 2011
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
# Michael Roth <mdroth@linux.vnet.ibm.com>
#
# This work is licensed under the terms of the GNU GPLv2.
# See the COPYING.LIB file in the top-level directory.
from ordereddict import OrderedDict
from qapi import *
import sys
import os
import getopt
import errno
def type_visitor(name):
if type(name) == list:
return 'visit_type_%sList' % name[0]
else:
return 'visit_type_%s' % name
def generate_decl_enum(name, members, genlist=True):
return mcgen('''
void %(visitor)s(Visitor *m, %(name)s * obj, const char *name, Error **errp);
''',
visitor=type_visitor(name))
def generate_command_decl(name, args, ret_type):
arglist=""
for argname, argtype, optional, structured in parse_args(args):
argtype = c_type(argtype)
if argtype == "char *":
argtype = "const char *"
if optional:
arglist += "bool has_%s, " % c_var(argname)
arglist += "%s %s, " % (argtype, c_var(argname))
return mcgen('''
%(ret_type)s qmp_%(name)s(%(args)sError **errp);
''',
ret_type=c_type(ret_type), name=c_fun(name), args=arglist).strip()
def gen_sync_call(name, args, ret_type, indent=0):
ret = ""
arglist=""
retval=""
if ret_type:
retval = "retval = "
for argname, argtype, optional, structured in parse_args(args):
if optional:
arglist += "has_%s, " % c_var(argname)
arglist += "%s, " % (c_var(argname))
push_indent(indent)
ret = mcgen('''
%(retval)sqmp_%(name)s(%(args)serrp);
''',
name=c_fun(name), args=arglist, retval=retval).rstrip()
if ret_type:
ret += "\n" + mcgen(''''
if (!error_is_set(errp)) {
%(marshal_output_call)s
}
''',
marshal_output_call=gen_marshal_output_call(name, ret_type)).rstrip()
pop_indent(indent)
return ret.rstrip()
def gen_marshal_output_call(name, ret_type):
if not ret_type:
return ""
return "qmp_marshal_output_%s(retval, ret, errp);" % c_fun(name)
def gen_visitor_output_containers_decl(ret_type):
ret = ""
push_indent()
if ret_type:
ret += mcgen('''
QmpOutputVisitor *mo;
QapiDeallocVisitor *md;
Visitor *v;
''')
pop_indent()
return ret
def gen_visitor_input_containers_decl(args):
ret = ""
push_indent()
if len(args) > 0:
ret += mcgen('''
QmpInputVisitor *mi;
QapiDeallocVisitor *md;
Visitor *v;
''')
pop_indent()
return ret.rstrip()
def gen_visitor_input_vars_decl(args):
ret = ""
push_indent()
for argname, argtype, optional, structured in parse_args(args):
if optional:
ret += mcgen('''
bool has_%(argname)s = false;
''',
argname=c_var(argname))
if c_type(argtype).endswith("*"):
ret += mcgen('''
%(argtype)s %(argname)s = NULL;
''',
argname=c_var(argname), argtype=c_type(argtype))
else:
ret += mcgen('''
%(argtype)s %(argname)s;
''',
argname=c_var(argname), argtype=c_type(argtype))
pop_indent()
return ret.rstrip()
def gen_visitor_input_block(args, obj, dealloc=False):
ret = ""
if len(args) == 0:
return ret
push_indent()
if dealloc:
ret += mcgen('''
md = qapi_dealloc_visitor_new();
v = qapi_dealloc_get_visitor(md);
''')
else:
ret += mcgen('''
mi = qmp_input_visitor_new_strict(%(obj)s);
v = qmp_input_get_visitor(mi);
''',
obj=obj)
for argname, argtype, optional, structured in parse_args(args):
if optional:
ret += mcgen('''
visit_start_optional(v, &has_%(c_name)s, "%(name)s", errp);
if (has_%(c_name)s) {
''',
c_name=c_var(argname), name=argname)
push_indent()
ret += mcgen('''
%(visitor)s(v, &%(c_name)s, "%(name)s", errp);
''',
c_name=c_var(argname), name=argname, argtype=argtype,
visitor=type_visitor(argtype))
if optional:
pop_indent()
ret += mcgen('''
}
visit_end_optional(v, errp);
''')
if dealloc:
ret += mcgen('''
qapi_dealloc_visitor_cleanup(md);
''')
else:
ret += mcgen('''
qmp_input_visitor_cleanup(mi);
''')
pop_indent()
return ret.rstrip()
def gen_marshal_output(name, args, ret_type, middle_mode):
if not ret_type:
return ""
ret = mcgen('''
static void qmp_marshal_output_%(c_name)s(%(c_ret_type)s ret_in, QObject **ret_out, Error **errp)
{
QapiDeallocVisitor *md = qapi_dealloc_visitor_new();
QmpOutputVisitor *mo = qmp_output_visitor_new();
Visitor *v;
v = qmp_output_get_visitor(mo);
%(visitor)s(v, &ret_in, "unused", errp);
if (!error_is_set(errp)) {
*ret_out = qmp_output_get_qobject(mo);
}
qmp_output_visitor_cleanup(mo);
v = qapi_dealloc_get_visitor(md);
%(visitor)s(v, &ret_in, "unused", errp);
qapi_dealloc_visitor_cleanup(md);
}
''',
c_ret_type=c_type(ret_type), c_name=c_fun(name),
visitor=type_visitor(ret_type))
return ret
def gen_marshal_input_decl(name, args, ret_type, middle_mode):
if middle_mode:
return 'int qmp_marshal_input_%s(Monitor *mon, const QDict *qdict, QObject **ret)' % c_fun(name)
else:
return 'static void qmp_marshal_input_%s(QDict *args, QObject **ret, Error **errp)' % c_fun(name)
def gen_marshal_input(name, args, ret_type, middle_mode):
hdr = gen_marshal_input_decl(name, args, ret_type, middle_mode)
ret = mcgen('''
%(header)s
{
''',
header=hdr)
if middle_mode:
ret += mcgen('''
Error *local_err = NULL;
Error **errp = &local_err;
QDict *args = (QDict *)qdict;
''')
if ret_type:
if c_type(ret_type).endswith("*"):
retval = " %s retval = NULL;" % c_type(ret_type)
else:
retval = " %s retval;" % c_type(ret_type)
ret += mcgen('''
%(retval)s
''',
retval=retval)
if len(args) > 0:
ret += mcgen('''
%(visitor_input_containers_decl)s
%(visitor_input_vars_decl)s
%(visitor_input_block)s
''',
visitor_input_containers_decl=gen_visitor_input_containers_decl(args),
visitor_input_vars_decl=gen_visitor_input_vars_decl(args),
visitor_input_block=gen_visitor_input_block(args, "QOBJECT(args)"))
else:
ret += mcgen('''
(void)args;
''')
ret += mcgen('''
if (error_is_set(errp)) {
goto out;
}
%(sync_call)s
''',
sync_call=gen_sync_call(name, args, ret_type, indent=4))
ret += mcgen('''
out:
''')
ret += mcgen('''
%(visitor_input_block_cleanup)s
''',
visitor_input_block_cleanup=gen_visitor_input_block(args, None,
dealloc=True))
if middle_mode:
ret += mcgen('''
if (local_err) {
qerror_report_err(local_err);
error_free(local_err);
return -1;
}
return 0;
''')
else:
ret += mcgen('''
return;
''')
ret += mcgen('''
}
''')
return ret
def option_value_matches(opt, val, cmd):
if opt in cmd and cmd[opt] == val:
return True
return False
def gen_registry(commands):
registry=""
push_indent()
for cmd in commands:
options = 'QCO_NO_OPTIONS'
if option_value_matches('success-response', 'no', cmd):
options = 'QCO_NO_SUCCESS_RESP'
registry += mcgen('''
qmp_register_command("%(name)s", qmp_marshal_input_%(c_name)s, %(opts)s);
''',
name=cmd['command'], c_name=c_fun(cmd['command']),
opts=options)
pop_indent()
ret = mcgen('''
static void qmp_init_marshal(void)
{
%(registry)s
}
qapi_init(qmp_init_marshal);
''',
registry=registry.rstrip())
return ret
def gen_command_decl_prologue(header, guard, prefix=""):
ret = mcgen('''
/* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
/*
* schema-defined QAPI function prototypes
*
* Copyright IBM, Corp. 2011
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
* See the COPYING.LIB file in the top-level directory.
*
*/
#ifndef %(guard)s
#define %(guard)s
#include "%(prefix)sqapi-types.h"
#include "error.h"
''',
header=basename(header), guard=guardname(header), prefix=prefix)
return ret
def gen_command_def_prologue(prefix="", proxy=False):
ret = mcgen('''
/* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
/*
* schema-defined QMP->QAPI command dispatch
*
* Copyright IBM, Corp. 2011
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
* See the COPYING.LIB file in the top-level directory.
*
*/
#include "qemu-objects.h"
#include "qapi/qmp-core.h"
#include "qapi/qapi-visit-core.h"
#include "qapi/qmp-output-visitor.h"
#include "qapi/qmp-input-visitor.h"
#include "qapi/qapi-dealloc-visitor.h"
#include "%(prefix)sqapi-types.h"
#include "%(prefix)sqapi-visit.h"
''',
prefix=prefix)
if not proxy:
ret += '#include "%sqmp-commands.h"' % prefix
return ret + "\n\n"
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "chp:o:m",
["source", "header", "prefix=",
"output-dir=", "type=", "middle"])
except getopt.GetoptError, err:
print str(err)
sys.exit(1)
output_dir = ""
prefix = ""
dispatch_type = "sync"
c_file = 'qmp-marshal.c'
h_file = 'qmp-commands.h'
middle_mode = False
do_c = False
do_h = False
for o, a in opts:
if o in ("-p", "--prefix"):
prefix = a
elif o in ("-o", "--output-dir"):
output_dir = a + "/"
elif o in ("-t", "--type"):
dispatch_type = a
elif o in ("-m", "--middle"):
middle_mode = True
elif o in ("-c", "--source"):
do_c = True
elif o in ("-h", "--header"):
do_h = True
if not do_c and not do_h:
do_c = True
do_h = True
c_file = output_dir + prefix + c_file
h_file = output_dir + prefix + h_file
def maybe_open(really, name, opt):
if really:
return open(name, opt)
else:
import StringIO
return StringIO.StringIO()
try:
os.makedirs(output_dir)
except os.error, e:
if e.errno != errno.EEXIST:
raise
exprs = parse_schema(sys.stdin)
commands = filter(lambda expr: expr.has_key('command'), exprs)
commands = filter(lambda expr: not expr.has_key('gen'), commands)
if dispatch_type == "sync":
fdecl = maybe_open(do_h, h_file, 'w')
fdef = maybe_open(do_c, c_file, 'w')
ret = gen_command_decl_prologue(header=basename(h_file), guard=guardname(h_file), prefix=prefix)
fdecl.write(ret)
ret = gen_command_def_prologue(prefix=prefix)
fdef.write(ret)
for cmd in commands:
arglist = []
ret_type = None
if cmd.has_key('data'):
arglist = cmd['data']
if cmd.has_key('returns'):
ret_type = cmd['returns']
ret = generate_command_decl(cmd['command'], arglist, ret_type) + "\n"
fdecl.write(ret)
if ret_type:
ret = gen_marshal_output(cmd['command'], arglist, ret_type, middle_mode) + "\n"
fdef.write(ret)
if middle_mode:
fdecl.write('%s;\n' % gen_marshal_input_decl(cmd['command'], arglist, ret_type, middle_mode))
ret = gen_marshal_input(cmd['command'], arglist, ret_type, middle_mode) + "\n"
fdef.write(ret)
fdecl.write("\n#endif\n");
if not middle_mode:
ret = gen_registry(commands)
fdef.write(ret)
fdef.flush()
fdef.close()
fdecl.flush()
fdecl.close()
| Python |
#
# QAPI helper library
#
# Copyright IBM, Corp. 2011
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
#
# This work is licensed under the terms of the GNU GPLv2.
# See the COPYING.LIB file in the top-level directory.
from ordereddict import OrderedDict
def tokenize(data):
while len(data):
if data[0] in ['{', '}', ':', ',', '[', ']']:
yield data[0]
data = data[1:]
elif data[0] in ' \n':
data = data[1:]
elif data[0] == "'":
data = data[1:]
string = ''
while data[0] != "'":
string += data[0]
data = data[1:]
data = data[1:]
yield string
def parse(tokens):
if tokens[0] == '{':
ret = OrderedDict()
tokens = tokens[1:]
while tokens[0] != '}':
key = tokens[0]
tokens = tokens[1:]
tokens = tokens[1:] # :
value, tokens = parse(tokens)
if tokens[0] == ',':
tokens = tokens[1:]
ret[key] = value
tokens = tokens[1:]
return ret, tokens
elif tokens[0] == '[':
ret = []
tokens = tokens[1:]
while tokens[0] != ']':
value, tokens = parse(tokens)
if tokens[0] == ',':
tokens = tokens[1:]
ret.append(value)
tokens = tokens[1:]
return ret, tokens
else:
return tokens[0], tokens[1:]
def evaluate(string):
return parse(map(lambda x: x, tokenize(string)))[0]
def parse_schema(fp):
exprs = []
expr = ''
expr_eval = None
for line in fp:
if line.startswith('#') or line == '\n':
continue
if line.startswith(' '):
expr += line
elif expr:
expr_eval = evaluate(expr)
if expr_eval.has_key('enum'):
add_enum(expr_eval['enum'])
elif expr_eval.has_key('union'):
add_enum('%sKind' % expr_eval['union'])
exprs.append(expr_eval)
expr = line
else:
expr += line
if expr:
expr_eval = evaluate(expr)
if expr_eval.has_key('enum'):
add_enum(expr_eval['enum'])
elif expr_eval.has_key('union'):
add_enum('%sKind' % expr_eval['union'])
exprs.append(expr_eval)
return exprs
def parse_args(typeinfo):
for member in typeinfo:
argname = member
argentry = typeinfo[member]
optional = False
structured = False
if member.startswith('*'):
argname = member[1:]
optional = True
if isinstance(argentry, OrderedDict):
structured = True
yield (argname, argentry, optional, structured)
def de_camel_case(name):
new_name = ''
for ch in name:
if ch.isupper() and new_name:
new_name += '_'
if ch == '-':
new_name += '_'
else:
new_name += ch.lower()
return new_name
def camel_case(name):
new_name = ''
first = True
for ch in name:
if ch in ['_', '-']:
first = True
elif first:
new_name += ch.upper()
first = False
else:
new_name += ch.lower()
return new_name
def c_var(name):
return name.replace('-', '_').lstrip("*")
def c_fun(name):
return c_var(name).replace('.', '_')
def c_list_type(name):
return '%sList' % name
def type_name(name):
if type(name) == list:
return c_list_type(name[0])
return name
enum_types = []
def add_enum(name):
global enum_types
enum_types.append(name)
def is_enum(name):
global enum_types
return (name in enum_types)
def c_type(name):
if name == 'str':
return 'char *'
elif name == 'int':
return 'int64_t'
elif name == 'bool':
return 'bool'
elif name == 'number':
return 'double'
elif type(name) == list:
return '%s *' % c_list_type(name[0])
elif is_enum(name):
return name
elif name == None or len(name) == 0:
return 'void'
elif name == name.upper():
return '%sEvent *' % camel_case(name)
else:
return '%s *' % name
def genindent(count):
ret = ""
for i in range(count):
ret += " "
return ret
indent_level = 0
def push_indent(indent_amount=4):
global indent_level
indent_level += indent_amount
def pop_indent(indent_amount=4):
global indent_level
indent_level -= indent_amount
def cgen(code, **kwds):
indent = genindent(indent_level)
lines = code.split('\n')
lines = map(lambda x: indent + x, lines)
return '\n'.join(lines) % kwds + '\n'
def mcgen(code, **kwds):
return cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
def basename(filename):
return filename.split("/")[-1]
def guardname(filename):
guard = basename(filename).rsplit(".", 1)[0]
for substr in [".", " ", "-"]:
guard = guard.replace(substr, "_")
return guard.upper() + '_H'
| Python |
#
# QAPI visitor generator
#
# Copyright IBM, Corp. 2011
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
# Michael Roth <mdroth@linux.vnet.ibm.com>
#
# This work is licensed under the terms of the GNU GPLv2.
# See the COPYING.LIB file in the top-level directory.
from ordereddict import OrderedDict
from qapi import *
import sys
import os
import getopt
import errno
def generate_visit_struct_body(field_prefix, members):
ret = ""
if len(field_prefix):
field_prefix = field_prefix + "."
for argname, argentry, optional, structured in parse_args(members):
if optional:
ret += mcgen('''
visit_start_optional(m, (obj && *obj) ? &(*obj)->%(c_prefix)shas_%(c_name)s : NULL, "%(name)s", errp);
if ((*obj)->%(prefix)shas_%(c_name)s) {
''',
c_prefix=c_var(field_prefix), prefix=field_prefix,
c_name=c_var(argname), name=argname)
push_indent()
if structured:
ret += mcgen('''
visit_start_struct(m, NULL, "", "%(name)s", 0, errp);
''',
name=argname)
ret += generate_visit_struct_body(field_prefix + argname, argentry)
ret += mcgen('''
visit_end_struct(m, errp);
''')
else:
ret += mcgen('''
visit_type_%(type)s(m, (obj && *obj) ? &(*obj)->%(c_prefix)s%(c_name)s : NULL, "%(name)s", errp);
''',
c_prefix=c_var(field_prefix), prefix=field_prefix,
type=type_name(argentry), c_name=c_var(argname),
name=argname)
if optional:
pop_indent()
ret += mcgen('''
}
visit_end_optional(m, errp);
''')
return ret
def generate_visit_struct(name, members):
ret = mcgen('''
void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
{
if (error_is_set(errp)) {
return;
}
visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), errp);
if (obj && !*obj) {
goto end;
}
''',
name=name)
push_indent()
ret += generate_visit_struct_body("", members)
pop_indent()
ret += mcgen('''
end:
visit_end_struct(m, errp);
}
''')
return ret
def generate_visit_list(name, members):
return mcgen('''
void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp)
{
GenericList *i, **prev = (GenericList **)obj;
if (error_is_set(errp)) {
return;
}
visit_start_list(m, name, errp);
for (; (i = visit_next_list(m, prev, errp)) != NULL; prev = &i) {
%(name)sList *native_i = (%(name)sList *)i;
visit_type_%(name)s(m, &native_i->value, NULL, errp);
}
visit_end_list(m, errp);
}
''',
name=name)
def generate_visit_enum(name, members):
return mcgen('''
void visit_type_%(name)s(Visitor *m, %(name)s * obj, const char *name, Error **errp)
{
visit_type_enum(m, (int *)obj, %(name)s_lookup, "%(name)s", name, errp);
}
''',
name=name)
def generate_visit_union(name, members):
ret = generate_visit_enum('%sKind' % name, members.keys())
ret += mcgen('''
void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp)
{
Error *err = NULL;
if (error_is_set(errp)) {
return;
}
visit_start_struct(m, (void **)obj, "%(name)s", name, sizeof(%(name)s), &err);
if (obj && !*obj) {
goto end;
}
visit_type_%(name)sKind(m, &(*obj)->kind, "type", &err);
if (err) {
error_propagate(errp, err);
goto end;
}
switch ((*obj)->kind) {
''',
name=name)
for key in members:
ret += mcgen('''
case %(abbrev)s_KIND_%(enum)s:
visit_type_%(c_type)s(m, &(*obj)->%(c_name)s, "data", errp);
break;
''',
abbrev = de_camel_case(name).upper(),
enum = c_fun(de_camel_case(key)).upper(),
c_type=members[key],
c_name=c_fun(key))
ret += mcgen('''
default:
abort();
}
end:
visit_end_struct(m, errp);
}
''')
return ret
def generate_declaration(name, members, genlist=True):
ret = mcgen('''
void visit_type_%(name)s(Visitor *m, %(name)s ** obj, const char *name, Error **errp);
''',
name=name)
if genlist:
ret += mcgen('''
void visit_type_%(name)sList(Visitor *m, %(name)sList ** obj, const char *name, Error **errp);
''',
name=name)
return ret
def generate_decl_enum(name, members, genlist=True):
return mcgen('''
void visit_type_%(name)s(Visitor *m, %(name)s * obj, const char *name, Error **errp);
''',
name=name)
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], "chp:o:",
["source", "header", "prefix=", "output-dir="])
except getopt.GetoptError, err:
print str(err)
sys.exit(1)
output_dir = ""
prefix = ""
c_file = 'qapi-visit.c'
h_file = 'qapi-visit.h'
do_c = False
do_h = False
for o, a in opts:
if o in ("-p", "--prefix"):
prefix = a
elif o in ("-o", "--output-dir"):
output_dir = a + "/"
elif o in ("-c", "--source"):
do_c = True
elif o in ("-h", "--header"):
do_h = True
if not do_c and not do_h:
do_c = True
do_h = True
c_file = output_dir + prefix + c_file
h_file = output_dir + prefix + h_file
try:
os.makedirs(output_dir)
except os.error, e:
if e.errno != errno.EEXIST:
raise
def maybe_open(really, name, opt):
if really:
return open(name, opt)
else:
import StringIO
return StringIO.StringIO()
fdef = maybe_open(do_c, c_file, 'w')
fdecl = maybe_open(do_h, h_file, 'w')
fdef.write(mcgen('''
/* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
/*
* schema-defined QAPI visitor functions
*
* Copyright IBM, Corp. 2011
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
* See the COPYING.LIB file in the top-level directory.
*
*/
#include "%(header)s"
''',
header=basename(h_file)))
fdecl.write(mcgen('''
/* THIS FILE IS AUTOMATICALLY GENERATED, DO NOT MODIFY */
/*
* schema-defined QAPI visitor function
*
* Copyright IBM, Corp. 2011
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
* See the COPYING.LIB file in the top-level directory.
*
*/
#ifndef %(guard)s
#define %(guard)s
#include "qapi/qapi-visit-core.h"
#include "%(prefix)sqapi-types.h"
''',
prefix=prefix, guard=guardname(h_file)))
exprs = parse_schema(sys.stdin)
for expr in exprs:
if expr.has_key('type'):
ret = generate_visit_struct(expr['type'], expr['data'])
ret += generate_visit_list(expr['type'], expr['data'])
fdef.write(ret)
ret = generate_declaration(expr['type'], expr['data'])
fdecl.write(ret)
elif expr.has_key('union'):
ret = generate_visit_union(expr['union'], expr['data'])
ret += generate_visit_list(expr['union'], expr['data'])
fdef.write(ret)
ret = generate_decl_enum('%sKind' % expr['union'], expr['data'].keys())
ret += generate_declaration(expr['union'], expr['data'])
fdecl.write(ret)
elif expr.has_key('enum'):
ret = generate_visit_enum(expr['enum'], expr['data'])
fdef.write(ret)
ret = generate_decl_enum(expr['enum'], expr['data'])
fdecl.write(ret)
fdecl.write('''
#endif
''')
fdecl.flush()
fdecl.close()
fdef.flush()
fdef.close()
| Python |
#!/usr/bin/env python
#
# Tests for image streaming.
#
# Copyright (C) 2012 IBM Corp.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import iotests
from iotests import qemu_img, qemu_io
backing_img = os.path.join(iotests.test_dir, 'backing.img')
mid_img = os.path.join(iotests.test_dir, 'mid.img')
test_img = os.path.join(iotests.test_dir, 'test.img')
class ImageStreamingTestCase(iotests.QMPTestCase):
'''Abstract base class for image streaming test cases'''
def assert_no_active_streams(self):
result = self.vm.qmp('query-block-jobs')
self.assert_qmp(result, 'return', [])
def cancel_and_wait(self, drive='drive0'):
'''Cancel a block job and wait for it to finish'''
result = self.vm.qmp('block-job-cancel', device=drive)
self.assert_qmp(result, 'return', {})
cancelled = False
while not cancelled:
for event in self.vm.get_qmp_events(wait=True):
if event['event'] == 'BLOCK_JOB_CANCELLED':
self.assert_qmp(event, 'data/type', 'stream')
self.assert_qmp(event, 'data/device', drive)
cancelled = True
self.assert_no_active_streams()
class TestSingleDrive(ImageStreamingTestCase):
image_len = 1 * 1024 * 1024 # MB
def setUp(self):
qemu_img('create', backing_img, str(TestSingleDrive.image_len))
qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, mid_img)
qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % mid_img, test_img)
self.vm = iotests.VM().add_drive(test_img)
self.vm.launch()
def tearDown(self):
self.vm.shutdown()
os.remove(test_img)
os.remove(mid_img)
os.remove(backing_img)
def test_stream(self):
self.assert_no_active_streams()
result = self.vm.qmp('block-stream', device='drive0')
self.assert_qmp(result, 'return', {})
completed = False
while not completed:
for event in self.vm.get_qmp_events(wait=True):
if event['event'] == 'BLOCK_JOB_COMPLETED':
self.assert_qmp(event, 'data/type', 'stream')
self.assert_qmp(event, 'data/device', 'drive0')
self.assert_qmp(event, 'data/offset', self.image_len)
self.assert_qmp(event, 'data/len', self.image_len)
completed = True
self.assert_no_active_streams()
self.vm.shutdown()
self.assertEqual(qemu_io('-c', 'map', backing_img),
qemu_io('-c', 'map', test_img),
'image file map does not match backing file after streaming')
def test_stream_partial(self):
self.assert_no_active_streams()
result = self.vm.qmp('block-stream', device='drive0', base=mid_img)
self.assert_qmp(result, 'return', {})
completed = False
while not completed:
for event in self.vm.get_qmp_events(wait=True):
if event['event'] == 'BLOCK_JOB_COMPLETED':
self.assert_qmp(event, 'data/type', 'stream')
self.assert_qmp(event, 'data/device', 'drive0')
self.assert_qmp(event, 'data/offset', self.image_len)
self.assert_qmp(event, 'data/len', self.image_len)
completed = True
self.assert_no_active_streams()
self.vm.shutdown()
self.assertEqual(qemu_io('-c', 'map', mid_img),
qemu_io('-c', 'map', test_img),
'image file map does not match backing file after streaming')
def test_device_not_found(self):
result = self.vm.qmp('block-stream', device='nonexistent')
self.assert_qmp(result, 'error/class', 'DeviceNotFound')
class TestStreamStop(ImageStreamingTestCase):
image_len = 8 * 1024 * 1024 * 1024 # GB
def setUp(self):
qemu_img('create', backing_img, str(TestStreamStop.image_len))
qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
self.vm = iotests.VM().add_drive(test_img)
self.vm.launch()
def tearDown(self):
self.vm.shutdown()
os.remove(test_img)
os.remove(backing_img)
def test_stream_stop(self):
import time
self.assert_no_active_streams()
result = self.vm.qmp('block-stream', device='drive0')
self.assert_qmp(result, 'return', {})
time.sleep(1)
events = self.vm.get_qmp_events(wait=False)
self.assertEqual(events, [], 'unexpected QMP event: %s' % events)
self.cancel_and_wait()
class TestSetSpeed(ImageStreamingTestCase):
image_len = 80 * 1024 * 1024 # MB
def setUp(self):
qemu_img('create', backing_img, str(TestSetSpeed.image_len))
qemu_img('create', '-f', iotests.imgfmt, '-o', 'backing_file=%s' % backing_img, test_img)
self.vm = iotests.VM().add_drive(test_img)
self.vm.launch()
def tearDown(self):
self.vm.shutdown()
os.remove(test_img)
os.remove(backing_img)
# This is a short performance test which is not run by default.
# Invoke "IMGFMT=qed ./030 TestSetSpeed.perf_test_throughput"
def perf_test_throughput(self):
self.assert_no_active_streams()
result = self.vm.qmp('block-stream', device='drive0')
self.assert_qmp(result, 'return', {})
result = self.vm.qmp('block-job-set-speed', device='drive0', speed=8 * 1024 * 1024)
self.assert_qmp(result, 'return', {})
completed = False
while not completed:
for event in self.vm.get_qmp_events(wait=True):
if event['event'] == 'BLOCK_JOB_COMPLETED':
self.assert_qmp(event, 'data/type', 'stream')
self.assert_qmp(event, 'data/device', 'drive0')
self.assert_qmp(event, 'data/offset', self.image_len)
self.assert_qmp(event, 'data/len', self.image_len)
completed = True
self.assert_no_active_streams()
def test_set_speed(self):
self.assert_no_active_streams()
result = self.vm.qmp('block-stream', device='drive0')
self.assert_qmp(result, 'return', {})
# Default speed is 0
result = self.vm.qmp('query-block-jobs')
self.assert_qmp(result, 'return[0]/device', 'drive0')
self.assert_qmp(result, 'return[0]/speed', 0)
result = self.vm.qmp('block-job-set-speed', device='drive0', speed=8 * 1024 * 1024)
self.assert_qmp(result, 'return', {})
# Ensure the speed we set was accepted
result = self.vm.qmp('query-block-jobs')
self.assert_qmp(result, 'return[0]/device', 'drive0')
self.assert_qmp(result, 'return[0]/speed', 8 * 1024 * 1024)
self.cancel_and_wait()
# Check setting speed in block-stream works
result = self.vm.qmp('block-stream', device='drive0', speed=4 * 1024 * 1024)
self.assert_qmp(result, 'return', {})
result = self.vm.qmp('query-block-jobs')
self.assert_qmp(result, 'return[0]/device', 'drive0')
self.assert_qmp(result, 'return[0]/speed', 4 * 1024 * 1024)
self.cancel_and_wait()
def test_set_speed_invalid(self):
self.assert_no_active_streams()
result = self.vm.qmp('block-stream', device='drive0', speed=-1)
self.assert_qmp(result, 'error/class', 'InvalidParameter')
self.assert_qmp(result, 'error/data/name', 'speed')
self.assert_no_active_streams()
result = self.vm.qmp('block-stream', device='drive0')
self.assert_qmp(result, 'return', {})
result = self.vm.qmp('block-job-set-speed', device='drive0', speed=-1)
self.assert_qmp(result, 'error/class', 'InvalidParameter')
self.assert_qmp(result, 'error/data/name', 'speed')
self.cancel_and_wait()
if __name__ == '__main__':
iotests.main(supported_fmts=['qcow2', 'qed'])
| Python |
#!/usr/bin/env python
import sys
import struct
import string
class QcowHeaderExtension:
def __init__(self, magic, length, data):
self.magic = magic
self.length = length
self.data = data
@classmethod
def create(cls, magic, data):
return QcowHeaderExtension(magic, len(data), data)
class QcowHeader:
uint32_t = 'I'
uint64_t = 'Q'
fields = [
# Version 2 header fields
[ uint32_t, '%#x', 'magic' ],
[ uint32_t, '%d', 'version' ],
[ uint64_t, '%#x', 'backing_file_offset' ],
[ uint32_t, '%#x', 'backing_file_size' ],
[ uint32_t, '%d', 'cluster_bits' ],
[ uint64_t, '%d', 'size' ],
[ uint32_t, '%d', 'crypt_method' ],
[ uint32_t, '%d', 'l1_size' ],
[ uint64_t, '%#x', 'l1_table_offset' ],
[ uint64_t, '%#x', 'refcount_table_offset' ],
[ uint32_t, '%d', 'refcount_table_clusters' ],
[ uint32_t, '%d', 'nb_snapshots' ],
[ uint64_t, '%#x', 'snapshot_offset' ],
# Version 3 header fields
[ uint64_t, '%#x', 'incompatible_features' ],
[ uint64_t, '%#x', 'compatible_features' ],
[ uint64_t, '%#x', 'autoclear_features' ],
[ uint32_t, '%d', 'refcount_order' ],
[ uint32_t, '%d', 'header_length' ],
];
fmt = '>' + ''.join(field[0] for field in fields)
def __init__(self, fd):
buf_size = struct.calcsize(QcowHeader.fmt)
fd.seek(0)
buf = fd.read(buf_size)
header = struct.unpack(QcowHeader.fmt, buf)
self.__dict__ = dict((field[2], header[i])
for i, field in enumerate(QcowHeader.fields))
self.set_defaults()
self.cluster_size = 1 << self.cluster_bits
fd.seek(self.header_length)
self.load_extensions(fd)
if self.backing_file_offset:
fd.seek(self.backing_file_offset)
self.backing_file = fd.read(self.backing_file_size)
else:
self.backing_file = None
def set_defaults(self):
if self.version == 2:
self.incompatible_features = 0
self.compatible_features = 0
self.autoclear_features = 0
self.refcount_order = 4
self.header_length = 72
def load_extensions(self, fd):
self.extensions = []
if self.backing_file_offset != 0:
end = min(self.cluster_size, self.backing_file_offset)
else:
end = self.cluster_size
while fd.tell() < end:
(magic, length) = struct.unpack('>II', fd.read(8))
if magic == 0:
break
else:
padded = (length + 7) & ~7
data = fd.read(padded)
self.extensions.append(QcowHeaderExtension(magic, length, data))
def update_extensions(self, fd):
fd.seek(self.header_length)
extensions = self.extensions
extensions.append(QcowHeaderExtension(0, 0, ""))
for ex in extensions:
buf = struct.pack('>II', ex.magic, ex.length)
fd.write(buf)
fd.write(ex.data)
if self.backing_file != None:
self.backing_file_offset = fd.tell()
fd.write(self.backing_file)
if fd.tell() > self.cluster_size:
raise Exception("I think I just broke the image...")
def update(self, fd):
header_bytes = self.header_length
self.update_extensions(fd)
fd.seek(0)
header = tuple(self.__dict__[f] for t, p, f in QcowHeader.fields)
buf = struct.pack(QcowHeader.fmt, *header)
buf = buf[0:header_bytes-1]
fd.write(buf)
def dump(self):
for f in QcowHeader.fields:
print "%-25s" % f[2], f[1] % self.__dict__[f[2]]
print ""
def dump_extensions(self):
for ex in self.extensions:
data = ex.data[:ex.length]
if all(c in string.printable for c in data):
data = "'%s'" % data
else:
data = "<binary>"
print "Header extension:"
print "%-25s %#x" % ("magic", ex.magic)
print "%-25s %d" % ("length", ex.length)
print "%-25s %s" % ("data", data)
print ""
def cmd_dump_header(fd):
h = QcowHeader(fd)
h.dump()
h.dump_extensions()
def cmd_add_header_ext(fd, magic, data):
try:
magic = int(magic, 0)
except:
print "'%s' is not a valid magic number" % magic
sys.exit(1)
h = QcowHeader(fd)
h.extensions.append(QcowHeaderExtension.create(magic, data))
h.update(fd)
def cmd_del_header_ext(fd, magic):
try:
magic = int(magic, 0)
except:
print "'%s' is not a valid magic number" % magic
sys.exit(1)
h = QcowHeader(fd)
found = False
for ex in h.extensions:
if ex.magic == magic:
found = True
h.extensions.remove(ex)
if not found:
print "No such header extension"
return
h.update(fd)
cmds = [
[ 'dump-header', cmd_dump_header, 0, 'Dump image header and header extensions' ],
[ 'add-header-ext', cmd_add_header_ext, 2, 'Add a header extension' ],
[ 'del-header-ext', cmd_del_header_ext, 1, 'Delete a header extension' ],
]
def main(filename, cmd, args):
fd = open(filename, "r+b")
try:
for name, handler, num_args, desc in cmds:
if name != cmd:
continue
elif len(args) != num_args:
usage()
return
else:
handler(fd, *args)
return
print "Unknown command '%s'" % cmd
finally:
fd.close()
def usage():
print "Usage: %s <file> <cmd> [<arg>, ...]" % sys.argv[0]
print ""
print "Supported commands:"
for name, handler, num_args, desc in cmds:
print " %-20s - %s" % (name, desc)
if len(sys.argv) < 3:
usage()
sys.exit(1)
main(sys.argv[1], sys.argv[2], sys.argv[3:])
| Python |
# Common utilities and Python wrappers for qemu-iotests
#
# Copyright (C) 2012 IBM Corp.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import os
import re
import subprocess
import unittest
import sys; sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'QMP'))
import qmp
__all__ = ['imgfmt', 'imgproto', 'test_dir' 'qemu_img', 'qemu_io',
'VM', 'QMPTestCase', 'notrun', 'main']
# This will not work if arguments or path contain spaces but is necessary if we
# want to support the override options that ./check supports.
qemu_img_args = os.environ.get('QEMU_IMG', 'qemu-img').strip().split(' ')
qemu_io_args = os.environ.get('QEMU_IO', 'qemu-io').strip().split(' ')
qemu_args = os.environ.get('QEMU', 'qemu').strip().split(' ')
imgfmt = os.environ.get('IMGFMT', 'raw')
imgproto = os.environ.get('IMGPROTO', 'file')
test_dir = os.environ.get('TEST_DIR', '/var/tmp')
def qemu_img(*args):
'''Run qemu-img and return the exit code'''
devnull = open('/dev/null', 'r+')
return subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull)
def qemu_io(*args):
'''Run qemu-io and return the stdout data'''
args = qemu_io_args + list(args)
return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
class VM(object):
'''A QEMU VM'''
def __init__(self):
self._monitor_path = os.path.join(test_dir, 'qemu-mon.%d' % os.getpid())
self._qemu_log_path = os.path.join(test_dir, 'qemu-log.%d' % os.getpid())
self._args = qemu_args + ['-chardev',
'socket,id=mon,path=' + self._monitor_path,
'-mon', 'chardev=mon,mode=control', '-nographic']
self._num_drives = 0
def add_drive(self, path, opts=''):
'''Add a virtio-blk drive to the VM'''
options = ['if=virtio',
'format=%s' % imgfmt,
'cache=none',
'file=%s' % path,
'id=drive%d' % self._num_drives]
if opts:
options.append(opts)
self._args.append('-drive')
self._args.append(','.join(options))
self._num_drives += 1
return self
def launch(self):
'''Launch the VM and establish a QMP connection'''
devnull = open('/dev/null', 'rb')
qemulog = open(self._qemu_log_path, 'wb')
try:
self._qmp = qmp.QEMUMonitorProtocol(self._monitor_path, server=True)
self._popen = subprocess.Popen(self._args, stdin=devnull, stdout=qemulog,
stderr=subprocess.STDOUT)
self._qmp.accept()
except:
os.remove(self._monitor_path)
raise
def shutdown(self):
'''Terminate the VM and clean up'''
if not self._popen is None:
self._qmp.cmd('quit')
self._popen.wait()
os.remove(self._monitor_path)
os.remove(self._qemu_log_path)
self._popen = None
def qmp(self, cmd, **args):
'''Invoke a QMP command and return the result dict'''
return self._qmp.cmd(cmd, args=args)
def get_qmp_events(self, wait=False):
'''Poll for queued QMP events and return a list of dicts'''
events = self._qmp.get_events(wait=wait)
self._qmp.clear_events()
return events
index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
class QMPTestCase(unittest.TestCase):
'''Abstract base class for QMP test cases'''
def dictpath(self, d, path):
'''Traverse a path in a nested dict'''
for component in path.split('/'):
m = index_re.match(component)
if m:
component, idx = m.groups()
idx = int(idx)
if not isinstance(d, dict) or component not in d:
self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
d = d[component]
if m:
if not isinstance(d, list):
self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
try:
d = d[idx]
except IndexError:
self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
return d
def assert_qmp(self, d, path, value):
'''Assert that the value for a specific path in a QMP dict matches'''
result = self.dictpath(d, path)
self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
def notrun(reason):
'''Skip this test suite'''
# Each test in qemu-iotests has a number ("seq")
seq = os.path.basename(sys.argv[0])
open('%s.notrun' % seq, 'wb').write(reason + '\n')
print '%s not run: %s' % (seq, reason)
sys.exit(0)
def main(supported_fmts=[]):
'''Run tests'''
if supported_fmts and (imgfmt not in supported_fmts):
notrun('not suitable for this image format: %s' % imgfmt)
# We need to filter out the time taken from the output so that qemu-iotest
# can reliably diff the results against master output.
import StringIO
output = StringIO.StringIO()
class MyTestRunner(unittest.TextTestRunner):
def __init__(self, stream=output, descriptions=True, verbosity=1):
unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
# unittest.main() will use sys.exit() so expect a SystemExit exception
try:
unittest.main(testRunner=MyTestRunner)
finally:
sys.stderr.write(re.sub(r'Ran (\d+) test[s] in [\d.]+s', r'Ran \1 tests', output.getvalue()))
| Python |
#!/usr/bin/python
#
# QMP command line tool
#
# Copyright IBM, Corp. 2011
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
#
# This work is licensed under the terms of the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
import sys, os
from qmp import QEMUMonitorProtocol
def print_response(rsp, prefix=[]):
if type(rsp) == list:
i = 0
for item in rsp:
if prefix == []:
prefix = ['item']
print_response(item, prefix[:-1] + ['%s[%d]' % (prefix[-1], i)])
i += 1
elif type(rsp) == dict:
for key in rsp.keys():
print_response(rsp[key], prefix + [key])
else:
if len(prefix):
print '%s: %s' % ('.'.join(prefix), rsp)
else:
print '%s' % (rsp)
def main(args):
path = None
# Use QMP_PATH if it's set
if os.environ.has_key('QMP_PATH'):
path = os.environ['QMP_PATH']
while len(args):
arg = args[0]
if arg.startswith('--'):
arg = arg[2:]
if arg.find('=') == -1:
value = True
else:
arg, value = arg.split('=', 1)
if arg in ['path']:
if type(value) == str:
path = value
elif arg in ['help']:
os.execlp('man', 'man', 'qmp')
else:
print 'Unknown argument "%s"' % arg
args = args[1:]
else:
break
if not path:
print "QMP path isn't set, use --path=qmp-monitor-address or set QMP_PATH"
return 1
if len(args):
command, args = args[0], args[1:]
else:
print 'No command found'
print 'Usage: "qmp [--path=qmp-monitor-address] qmp-cmd arguments"'
return 1
if command in ['help']:
os.execlp('man', 'man', 'qmp')
srv = QEMUMonitorProtocol(path)
srv.connect()
def do_command(srv, cmd, **kwds):
rsp = srv.cmd(cmd, kwds)
if rsp.has_key('error'):
raise Exception(rsp['error']['desc'])
return rsp['return']
commands = map(lambda x: x['name'], do_command(srv, 'query-commands'))
srv.close()
if command not in commands:
fullcmd = 'qmp-%s' % command
try:
os.environ['QMP_PATH'] = path
os.execvp(fullcmd, [fullcmd] + args)
except OSError, (errno, msg):
if errno == 2:
print 'Command "%s" not found.' % (fullcmd)
return 1
raise
return 0
srv = QEMUMonitorProtocol(path)
srv.connect()
arguments = {}
for arg in args:
if not arg.startswith('--'):
print 'Unknown argument "%s"' % arg
return 1
arg = arg[2:]
if arg.find('=') == -1:
value = True
else:
arg, value = arg.split('=', 1)
if arg in ['help']:
os.execlp('man', 'man', 'qmp-%s' % command)
return 1
arguments[arg] = value
rsp = do_command(srv, command, **arguments)
print_response(rsp)
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| Python |
#!/usr/bin/python
##
# QEMU Object Model test tools
#
# Copyright IBM, Corp. 2012
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
#
# This work is licensed under the terms of the GNU GPL, version 2 or later. See
# the COPYING file in the top-level directory.
##
import fuse, stat
from fuse import Fuse
import os, posix
from errno import *
from qmp import QEMUMonitorProtocol
fuse.fuse_python_api = (0, 2)
class QOMFS(Fuse):
def __init__(self, qmp, *args, **kwds):
Fuse.__init__(self, *args, **kwds)
self.qmp = qmp
self.qmp.connect()
self.ino_map = {}
self.ino_count = 1
def get_ino(self, path):
if self.ino_map.has_key(path):
return self.ino_map[path]
self.ino_map[path] = self.ino_count
self.ino_count += 1
return self.ino_map[path]
def is_object(self, path):
try:
items = self.qmp.command('qom-list', path=path)
return True
except:
return False
def is_property(self, path):
try:
path, prop = path.rsplit('/', 1)
for item in self.qmp.command('qom-list', path=path):
if item['name'] == prop:
return True
return False
except:
return False
def is_link(self, path):
try:
path, prop = path.rsplit('/', 1)
for item in self.qmp.command('qom-list', path=path):
if item['name'] == prop:
if item['type'].startswith('link<'):
return True
return False
return False
except:
return False
def read(self, path, length, offset):
if not self.is_property(path):
return -ENOENT
path, prop = path.rsplit('/', 1)
try:
data = str(self.qmp.command('qom-get', path=path, property=prop))
data += '\n' # make values shell friendly
except:
return -EPERM
if offset > len(data):
return ''
return str(data[offset:][:length])
def readlink(self, path):
if not self.is_link(path):
return False
path, prop = path.rsplit('/', 1)
prefix = '/'.join(['..'] * (len(path.split('/')) - 1))
return prefix + str(self.qmp.command('qom-get', path=path,
property=prop))
def getattr(self, path):
if self.is_link(path):
value = posix.stat_result((0755 | stat.S_IFLNK,
self.get_ino(path),
0,
2,
1000,
1000,
4096,
0,
0,
0))
elif self.is_object(path):
value = posix.stat_result((0755 | stat.S_IFDIR,
self.get_ino(path),
0,
2,
1000,
1000,
4096,
0,
0,
0))
elif self.is_property(path):
value = posix.stat_result((0644 | stat.S_IFREG,
self.get_ino(path),
0,
1,
1000,
1000,
4096,
0,
0,
0))
else:
value = -ENOENT
return value
def readdir(self, path, offset):
yield fuse.Direntry('.')
yield fuse.Direntry('..')
for item in self.qmp.command('qom-list', path=path):
yield fuse.Direntry(str(item['name']))
if __name__ == '__main__':
import sys, os
fs = QOMFS(QEMUMonitorProtocol(os.environ['QMP_SOCKET']))
fs.main(sys.argv)
| Python |
# QEMU Monitor Protocol Python class
#
# Copyright (C) 2009, 2010 Red Hat Inc.
#
# Authors:
# Luiz Capitulino <lcapitulino@redhat.com>
#
# This work is licensed under the terms of the GNU GPL, version 2. See
# the COPYING file in the top-level directory.
import json
import errno
import socket
class QMPError(Exception):
pass
class QMPConnectError(QMPError):
pass
class QMPCapabilitiesError(QMPError):
pass
class QEMUMonitorProtocol:
def __init__(self, address, server=False):
"""
Create a QEMUMonitorProtocol class.
@param address: QEMU address, can be either a unix socket path (string)
or a tuple in the form ( address, port ) for a TCP
connection
@param server: server mode listens on the socket (bool)
@raise socket.error on socket connection errors
@note No connection is established, this is done by the connect() or
accept() methods
"""
self.__events = []
self.__address = address
self.__sock = self.__get_sock()
if server:
self.__sock.bind(self.__address)
self.__sock.listen(1)
def __get_sock(self):
if isinstance(self.__address, tuple):
family = socket.AF_INET
else:
family = socket.AF_UNIX
return socket.socket(family, socket.SOCK_STREAM)
def __negotiate_capabilities(self):
self.__sockfile = self.__sock.makefile()
greeting = self.__json_read()
if greeting is None or not greeting.has_key('QMP'):
raise QMPConnectError
# Greeting seems ok, negotiate capabilities
resp = self.cmd('qmp_capabilities')
if "return" in resp:
return greeting
raise QMPCapabilitiesError
def __json_read(self, only_event=False):
while True:
data = self.__sockfile.readline()
if not data:
return
resp = json.loads(data)
if 'event' in resp:
self.__events.append(resp)
if not only_event:
continue
return resp
error = socket.error
def connect(self):
"""
Connect to the QMP Monitor and perform capabilities negotiation.
@return QMP greeting dict
@raise socket.error on socket connection errors
@raise QMPConnectError if the greeting is not received
@raise QMPCapabilitiesError if fails to negotiate capabilities
"""
self.__sock.connect(self.__address)
return self.__negotiate_capabilities()
def accept(self):
"""
Await connection from QMP Monitor and perform capabilities negotiation.
@return QMP greeting dict
@raise socket.error on socket connection errors
@raise QMPConnectError if the greeting is not received
@raise QMPCapabilitiesError if fails to negotiate capabilities
"""
self.__sock, _ = self.__sock.accept()
return self.__negotiate_capabilities()
def cmd_obj(self, qmp_cmd):
"""
Send a QMP command to the QMP Monitor.
@param qmp_cmd: QMP command to be sent as a Python dict
@return QMP response as a Python dict or None if the connection has
been closed
"""
try:
self.__sock.sendall(json.dumps(qmp_cmd))
except socket.error, err:
if err[0] == errno.EPIPE:
return
raise socket.error(err)
return self.__json_read()
def cmd(self, name, args=None, id=None):
"""
Build a QMP command and send it to the QMP Monitor.
@param name: command name (string)
@param args: command arguments (dict)
@param id: command id (dict, list, string or int)
"""
qmp_cmd = { 'execute': name }
if args:
qmp_cmd['arguments'] = args
if id:
qmp_cmd['id'] = id
return self.cmd_obj(qmp_cmd)
def command(self, cmd, **kwds):
ret = self.cmd(cmd, kwds)
if ret.has_key('error'):
raise Exception(ret['error']['desc'])
return ret['return']
def get_events(self, wait=False):
"""
Get a list of available QMP events.
@param wait: block until an event is available (bool)
"""
self.__sock.setblocking(0)
try:
self.__json_read()
except socket.error, err:
if err[0] == errno.EAGAIN:
# No data available
pass
self.__sock.setblocking(1)
if not self.__events and wait:
self.__json_read(only_event=True)
return self.__events
def clear_events(self):
"""
Clear current list of pending events.
"""
self.__events = []
def close(self):
self.__sock.close()
self.__sockfile.close()
| Python |
#!/usr/bin/python
##
# QEMU Object Model test tools
#
# Copyright IBM, Corp. 2011
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
#
# This work is licensed under the terms of the GNU GPL, version 2 or later. See
# the COPYING file in the top-level directory.
##
import sys
import os
from qmp import QEMUMonitorProtocol
cmd, args = sys.argv[0], sys.argv[1:]
socket_path = None
path = None
prop = None
value = None
def usage():
return '''environment variables:
QMP_SOCKET=<path | addr:port>
usage:
%s [-h] [-s <QMP socket path | addr:port>] <path>.<property> <value>
''' % cmd
def usage_error(error_msg = "unspecified error"):
sys.stderr.write('%s\nERROR: %s\n' % (usage(), error_msg))
exit(1)
if len(args) > 0:
if args[0] == "-h":
print usage()
exit(0);
elif args[0] == "-s":
try:
socket_path = args[1]
except:
usage_error("missing argument: QMP socket path or address");
args = args[2:]
if not socket_path:
if os.environ.has_key('QMP_SOCKET'):
socket_path = os.environ['QMP_SOCKET']
else:
usage_error("no QMP socket path or address given");
if len(args) > 1:
try:
path, prop = args[0].rsplit('.', 1)
except:
usage_error("invalid format for path/property/value")
value = args[1]
else:
usage_error("not enough arguments")
srv = QEMUMonitorProtocol(socket_path)
srv.connect()
print srv.command('qom-set', path=path, property=prop, value=sys.argv[2])
| Python |
#!/usr/bin/python
##
# QEMU Object Model test tools
#
# Copyright IBM, Corp. 2011
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
#
# This work is licensed under the terms of the GNU GPL, version 2 or later. See
# the COPYING file in the top-level directory.
##
import sys
import os
from qmp import QEMUMonitorProtocol
cmd, args = sys.argv[0], sys.argv[1:]
socket_path = None
path = None
prop = None
def usage():
return '''environment variables:
QMP_SOCKET=<path | addr:port>
usage:
%s [-h] [-s <QMP socket path | addr:port>] <path>.<property>
''' % cmd
def usage_error(error_msg = "unspecified error"):
sys.stderr.write('%s\nERROR: %s\n' % (usage(), error_msg))
exit(1)
if len(args) > 0:
if args[0] == "-h":
print usage()
exit(0);
elif args[0] == "-s":
try:
socket_path = args[1]
except:
usage_error("missing argument: QMP socket path or address");
args = args[2:]
if not socket_path:
if os.environ.has_key('QMP_SOCKET'):
socket_path = os.environ['QMP_SOCKET']
else:
usage_error("no QMP socket path or address given");
if len(args) > 0:
try:
path, prop = args[0].rsplit('.', 1)
except:
usage_error("invalid format for path/property/value")
else:
usage_error("not enough arguments")
srv = QEMUMonitorProtocol(socket_path)
srv.connect()
rsp = srv.command('qom-get', path=path, property=prop)
if type(rsp) == dict:
for i in rsp.keys():
print '%s: %s' % (i, rsp[i])
else:
print rsp
| Python |
#!/usr/bin/python
##
# QEMU Object Model test tools
#
# Copyright IBM, Corp. 2011
#
# Authors:
# Anthony Liguori <aliguori@us.ibm.com>
#
# This work is licensed under the terms of the GNU GPL, version 2 or later. See
# the COPYING file in the top-level directory.
##
import sys
import os
from qmp import QEMUMonitorProtocol
cmd, args = sys.argv[0], sys.argv[1:]
socket_path = None
path = None
prop = None
def usage():
return '''environment variables:
QMP_SOCKET=<path | addr:port>
usage:
%s [-h] [-s <QMP socket path | addr:port>] [<path>]
''' % cmd
def usage_error(error_msg = "unspecified error"):
sys.stderr.write('%s\nERROR: %s\n' % (usage(), error_msg))
exit(1)
if len(args) > 0:
if args[0] == "-h":
print usage()
exit(0);
elif args[0] == "-s":
try:
socket_path = args[1]
except:
usage_error("missing argument: QMP socket path or address");
args = args[2:]
if not socket_path:
if os.environ.has_key('QMP_SOCKET'):
socket_path = os.environ['QMP_SOCKET']
else:
usage_error("no QMP socket path or address given");
srv = QEMUMonitorProtocol(socket_path)
srv.connect()
if len(args) == 0:
print '/'
sys.exit(0)
for item in srv.command('qom-list', path=args[0]):
if item['type'].startswith('child<'):
print '%s/' % item['name']
elif item['type'].startswith('link<'):
print '@%s/' % item['name']
else:
print '%s' % item['name']
| Python |
#!/usr/bin/python
#
# Low-level QEMU shell on top of QMP.
#
# Copyright (C) 2009, 2010 Red Hat Inc.
#
# Authors:
# Luiz Capitulino <lcapitulino@redhat.com>
#
# This work is licensed under the terms of the GNU GPL, version 2. See
# the COPYING file in the top-level directory.
#
# Usage:
#
# Start QEMU with:
#
# # qemu [...] -qmp unix:./qmp-sock,server
#
# Run the shell:
#
# $ qmp-shell ./qmp-sock
#
# Commands have the following format:
#
# < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
#
# For example:
#
# (QEMU) device_add driver=e1000 id=net1
# {u'return': {}}
# (QEMU)
import qmp
import readline
import sys
class QMPCompleter(list):
def complete(self, text, state):
for cmd in self:
if cmd.startswith(text):
if not state:
return cmd
else:
state -= 1
class QMPShellError(Exception):
pass
class QMPShellBadPort(QMPShellError):
pass
# TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and
# _execute_cmd()). Let's design a better one.
class QMPShell(qmp.QEMUMonitorProtocol):
def __init__(self, address):
qmp.QEMUMonitorProtocol.__init__(self, self.__get_address(address))
self._greeting = None
self._completer = None
def __get_address(self, arg):
"""
Figure out if the argument is in the port:host form, if it's not it's
probably a file path.
"""
addr = arg.split(':')
if len(addr) == 2:
try:
port = int(addr[1])
except ValueError:
raise QMPShellBadPort
return ( addr[0], port )
# socket path
return arg
def _fill_completion(self):
for cmd in self.cmd('query-commands')['return']:
self._completer.append(cmd['name'])
def __completer_setup(self):
self._completer = QMPCompleter()
self._fill_completion()
readline.set_completer(self._completer.complete)
readline.parse_and_bind("tab: complete")
# XXX: default delimiters conflict with some command names (eg. query-),
# clearing everything as it doesn't seem to matter
readline.set_completer_delims('')
def __build_cmd(self, cmdline):
"""
Build a QMP input object from a user provided command-line in the
following format:
< command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
"""
cmdargs = cmdline.split()
qmpcmd = { 'execute': cmdargs[0], 'arguments': {} }
for arg in cmdargs[1:]:
opt = arg.split('=')
try:
value = int(opt[1])
except ValueError:
value = opt[1]
qmpcmd['arguments'][opt[0]] = value
return qmpcmd
def _execute_cmd(self, cmdline):
try:
qmpcmd = self.__build_cmd(cmdline)
except:
print 'command format: <command-name> ',
print '[arg-name1=arg1] ... [arg-nameN=argN]'
return True
resp = self.cmd_obj(qmpcmd)
if resp is None:
print 'Disconnected'
return False
print resp
return True
def connect(self):
self._greeting = qmp.QEMUMonitorProtocol.connect(self)
self.__completer_setup()
def show_banner(self, msg='Welcome to the QMP low-level shell!'):
print msg
version = self._greeting['QMP']['version']['qemu']
print 'Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro'])
def read_exec_command(self, prompt):
"""
Read and execute a command.
@return True if execution was ok, return False if disconnected.
"""
try:
cmdline = raw_input(prompt)
except EOFError:
print
return False
if cmdline == '':
for ev in self.get_events():
print ev
self.clear_events()
return True
else:
return self._execute_cmd(cmdline)
class HMPShell(QMPShell):
def __init__(self, address):
QMPShell.__init__(self, address)
self.__cpu_index = 0
def __cmd_completion(self):
for cmd in self.__cmd_passthrough('help')['return'].split('\r\n'):
if cmd and cmd[0] != '[' and cmd[0] != '\t':
name = cmd.split()[0] # drop help text
if name == 'info':
continue
if name.find('|') != -1:
# Command in the form 'foobar|f' or 'f|foobar', take the
# full name
opt = name.split('|')
if len(opt[0]) == 1:
name = opt[1]
else:
name = opt[0]
self._completer.append(name)
self._completer.append('help ' + name) # help completion
def __info_completion(self):
for cmd in self.__cmd_passthrough('info')['return'].split('\r\n'):
if cmd:
self._completer.append('info ' + cmd.split()[1])
def __other_completion(self):
# special cases
self._completer.append('help info')
def _fill_completion(self):
self.__cmd_completion()
self.__info_completion()
self.__other_completion()
def __cmd_passthrough(self, cmdline, cpu_index = 0):
return self.cmd_obj({ 'execute': 'human-monitor-command', 'arguments':
{ 'command-line': cmdline,
'cpu-index': cpu_index } })
def _execute_cmd(self, cmdline):
if cmdline.split()[0] == "cpu":
# trap the cpu command, it requires special setting
try:
idx = int(cmdline.split()[1])
if not 'return' in self.__cmd_passthrough('info version', idx):
print 'bad CPU index'
return True
self.__cpu_index = idx
except ValueError:
print 'cpu command takes an integer argument'
return True
resp = self.__cmd_passthrough(cmdline, self.__cpu_index)
if resp is None:
print 'Disconnected'
return False
assert 'return' in resp or 'error' in resp
if 'return' in resp:
# Success
if len(resp['return']) > 0:
print resp['return'],
else:
# Error
print '%s: %s' % (resp['error']['class'], resp['error']['desc'])
return True
def show_banner(self):
QMPShell.show_banner(self, msg='Welcome to the HMP shell!')
def die(msg):
sys.stderr.write('ERROR: %s\n' % msg)
sys.exit(1)
def fail_cmdline(option=None):
if option:
sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option)
sys.stderr.write('qemu-shell [ -H ] < UNIX socket path> | < TCP address:port >\n')
sys.exit(1)
def main():
addr = ''
try:
if len(sys.argv) == 2:
qemu = QMPShell(sys.argv[1])
addr = sys.argv[1]
elif len(sys.argv) == 3:
if sys.argv[1] != '-H':
fail_cmdline(sys.argv[1])
qemu = HMPShell(sys.argv[2])
addr = sys.argv[2]
else:
fail_cmdline()
except QMPShellBadPort:
die('bad port number in command-line')
try:
qemu.connect()
except qmp.QMPConnectError:
die('Didn\'t get QMP greeting message')
except qmp.QMPCapabilitiesError:
die('Could not negotiate capabilities')
except qemu.error:
die('Could not connect to %s' % addr)
qemu.show_banner()
while qemu.read_exec_command('(QEMU) '):
pass
qemu.close()
if __name__ == '__main__':
main()
| Python |
#! /usr/bin/env python
# GLib Testing Framework Utility -*- Mode: python; -*-
# Copyright (C) 2007 Imendio AB
# Authors: Tim Janik
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
import sys, re, xml.dom.minidom
pkginstall_configvars = {
#@PKGINSTALL_CONFIGVARS_IN24LINES@ # configvars are substituted upon script installation
}
# xml utilities
def find_child (node, child_name):
for child in node.childNodes:
if child.nodeName == child_name:
return child
return None
def list_children (node, child_name):
rlist = []
for child in node.childNodes:
if child.nodeName == child_name:
rlist += [ child ]
return rlist
def find_node (node, name = None):
if not node or node.nodeName == name or not name:
return node
for child in node.childNodes:
c = find_node (child, name)
if c:
return c
return None
def node_as_text (node, name = None):
if name:
node = find_node (node, name)
txt = ''
if node:
if node.nodeValue:
txt += node.nodeValue
for child in node.childNodes:
txt += node_as_text (child)
return txt
def attribute_as_text (node, aname, node_name = None):
node = find_node (node, node_name)
if not node:
return ''
attr = node.attributes.get (aname, '')
if hasattr (attr, 'value'):
return attr.value
return ''
# HTML utilities
def html_indent_string (n):
uncollapsible_space = ' ' # HTML won't compress alternating sequences of ' ' and ' '
string = ''
for i in range (0, (n + 1) / 2):
string += uncollapsible_space
return string
# TestBinary object, instantiated per test binary in the log file
class TestBinary:
def __init__ (self, name):
self.name = name
self.testcases = []
self.duration = 0
self.success_cases = 0
self.skipped_cases = 0
self.file = '???'
self.random_seed = ''
# base class to handle processing/traversion of XML nodes
class TreeProcess:
def __init__ (self):
self.nest_level = 0
def trampoline (self, node):
name = node.nodeName
if name == '#text':
self.handle_text (node)
else:
try: method = getattr (self, 'handle_' + re.sub ('[^a-zA-Z0-9]', '_', name))
except: method = None
if method:
return method (node)
else:
return self.process_recursive (name, node)
def process_recursive (self, node_name, node):
self.process_children (node)
def process_children (self, node):
self.nest_level += 1
for child in node.childNodes:
self.trampoline (child)
self.nest_level += 1
# test report reader, this class collects some statistics and merges duplicate test binary runs
class ReportReader (TreeProcess):
def __init__ (self):
TreeProcess.__init__ (self)
self.binary_names = []
self.binaries = {}
self.last_binary = None
def binary_list (self):
lst = []
for name in self.binary_names:
lst += [ self.binaries[name] ]
return lst
def handle_testcase (self, node):
self.last_binary.testcases += [ node ]
result = attribute_as_text (node, 'result', 'status')
if result == 'success':
self.last_binary.success_cases += 1
if bool (int (attribute_as_text (node, 'skipped') + '0')):
self.last_binary.skipped_cases += 1
def handle_text (self, node):
pass
def handle_testbinary (self, node):
path = node.attributes.get ('path', None).value
if self.binaries.get (path, -1) == -1:
self.binaries[path] = TestBinary (path)
self.binary_names += [ path ]
self.last_binary = self.binaries[path]
dn = find_child (node, 'duration')
dur = node_as_text (dn)
try: dur = float (dur)
except: dur = 0
if dur:
self.last_binary.duration += dur
bin = find_child (node, 'binary')
if bin:
self.last_binary.file = attribute_as_text (bin, 'file')
rseed = find_child (node, 'random-seed')
if rseed:
self.last_binary.random_seed = node_as_text (rseed)
self.process_children (node)
# HTML report generation class
class ReportWriter (TreeProcess):
# Javascript/CSS snippet to toggle element visibility
cssjs = r'''
<style type="text/css" media="screen">
.VisibleSection { }
.HiddenSection { display: none; }
</style>
<script language="javascript" type="text/javascript"><!--
function toggle_display (parentid, tagtype, idmatch, keymatch) {
ptag = document.getElementById (parentid);
tags = ptag.getElementsByTagName (tagtype);
for (var i = 0; i < tags.length; i++) {
tag = tags[i];
var key = tag.getAttribute ("keywords");
if (tag.id.indexOf (idmatch) == 0 && key && key.match (keymatch)) {
if (tag.className.indexOf ("HiddenSection") >= 0)
tag.className = "VisibleSection";
else
tag.className = "HiddenSection";
}
}
}
message_array = Array();
function view_testlog (wname, file, random_seed, tcase, msgtitle, msgid) {
txt = message_array[msgid];
var w = window.open ("", // URI
wname,
"resizable,scrollbars,status,width=790,height=400");
var doc = w.document;
doc.write ("<h2>File: " + file + "</h2>\n");
doc.write ("<h3>Case: " + tcase + "</h3>\n");
doc.write ("<strong>Random Seed:</strong> <code>" + random_seed + "</code> <br /><br />\n");
doc.write ("<strong>" + msgtitle + "</strong><br />\n");
doc.write ("<pre>");
doc.write (txt);
doc.write ("</pre>\n");
doc.write ("<a href=\'javascript:window.close()\'>Close Window</a>\n");
doc.close();
}
--></script>
'''
def __init__ (self, binary_list):
TreeProcess.__init__ (self)
self.binaries = binary_list
self.bcounter = 0
self.tcounter = 0
self.total_tcounter = 0
self.total_fcounter = 0
self.total_duration = 0
self.indent_depth = 0
self.lastchar = ''
def oprint (self, message):
sys.stdout.write (message)
if message:
self.lastchar = message[-1]
def handle_text (self, node):
self.oprint (node.nodeValue)
def handle_testcase (self, node, binary):
skipped = bool (int (attribute_as_text (node, 'skipped') + '0'))
if skipped:
return # skipped tests are uninteresting for HTML reports
path = attribute_as_text (node, 'path')
duration = node_as_text (node, 'duration')
result = attribute_as_text (node, 'result', 'status')
rcolor = {
'success': 'bgcolor="lightgreen"',
'failed': 'bgcolor="red"',
}.get (result, '')
if result != 'success':
duration = '-' # ignore bogus durations
self.oprint ('<tr id="b%u_t%u_" keywords="%s all" class="HiddenSection">\n' % (self.bcounter, self.tcounter, result))
self.oprint ('<td>%s %s</td> <td align="right">%s</td> \n' % (html_indent_string (4), path, duration))
perflist = list_children (node, 'performance')
if result != 'success':
rlist = list_children (node, 'error')
txt = ''
for enode in rlist:
txt += node_as_text (enode)
if txt and txt[-1] != '\n':
txt += '\n'
txt = re.sub (r'"', r'\\"', txt)
txt = re.sub (r'\n', r'\\n', txt)
txt = re.sub (r'&', r'&', txt)
txt = re.sub (r'<', r'<', txt)
self.oprint ('<script language="javascript" type="text/javascript">message_array["b%u_t%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, txt))
self.oprint ('<td align="center"><a href="javascript:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Output:\', \'b%u_t%u_\')">Details</a></td>\n' %
('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
elif perflist:
presults = []
for perf in perflist:
pmin = bool (int (attribute_as_text (perf, 'minimize')))
pmax = bool (int (attribute_as_text (perf, 'maximize')))
pval = float (attribute_as_text (perf, 'value'))
txt = node_as_text (perf)
txt = re.sub (r'&', r'&', txt)
txt = re.sub (r'<', r'>', txt)
txt = '<strong>Performace(' + (pmin and '<em>minimized</em>' or '<em>maximized</em>') + '):</strong> ' + txt.strip() + '<br />\n'
txt = re.sub (r'"', r'\\"', txt)
txt = re.sub (r'\n', r'\\n', txt)
presults += [ (pval, txt) ]
presults.sort()
ptxt = ''.join ([e[1] for e in presults])
self.oprint ('<script language="javascript" type="text/javascript">message_array["b%u_t%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, ptxt))
self.oprint ('<td align="center"><a href="javascript:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Test Results:\', \'b%u_t%u_\')">Details</a></td>\n' %
('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
else:
self.oprint ('<td align="center">-</td>\n')
self.oprint ('<td align="right" %s>%s</td>\n' % (rcolor, result))
self.oprint ('</tr>\n')
self.tcounter += 1
self.total_tcounter += 1
self.total_fcounter += result != 'success'
def handle_binary (self, binary):
self.tcounter = 1
self.bcounter += 1
self.total_duration += binary.duration
self.oprint ('<tr><td><strong>%s</strong></td><td align="right">%f</td> <td align="center">\n' % (binary.name, binary.duration))
erlink, oklink = ('', '')
real_cases = len (binary.testcases) - binary.skipped_cases
if binary.success_cases < real_cases:
erlink = 'href="javascript:toggle_display (\'ResultTable\', \'tr\', \'b%u_\', \'failed\')"' % self.bcounter
if binary.success_cases:
oklink = 'href="javascript:toggle_display (\'ResultTable\', \'tr\', \'b%u_\', \'success\')"' % self.bcounter
self.oprint ('<a %s>ER</a>\n' % erlink)
self.oprint ('<a %s>OK</a>\n' % oklink)
self.oprint ('</td>\n')
perc = binary.success_cases * 100.0 / real_cases
pcolor = {
100 : 'bgcolor="lightgreen"',
0 : 'bgcolor="red"',
}.get (int (perc), 'bgcolor="yellow"')
self.oprint ('<td align="right" %s>%.2f%%</td>\n' % (pcolor, perc))
self.oprint ('</tr>\n')
for tc in binary.testcases:
self.handle_testcase (tc, binary)
def handle_totals (self):
self.oprint ('<tr>')
self.oprint ('<td><strong>Totals:</strong> %u Binaries, %u Tests, %u Failed, %u Succeeded</td>' %
(self.bcounter, self.total_tcounter, self.total_fcounter, self.total_tcounter - self.total_fcounter))
self.oprint ('<td align="right">%f</td>\n' % self.total_duration)
self.oprint ('<td align="center">-</td>\n')
perc = (self.total_tcounter - self.total_fcounter) * 100.0 / self.total_tcounter
pcolor = {
100 : 'bgcolor="lightgreen"',
0 : 'bgcolor="red"',
}.get (int (perc), 'bgcolor="yellow"')
self.oprint ('<td align="right" %s>%.2f%%</td>\n' % (pcolor, perc))
self.oprint ('</tr>\n')
def printout (self):
self.oprint ('<html><head>\n')
self.oprint ('<title>GTester Unit Test Report</title>\n')
self.oprint (self.cssjs)
self.oprint ('</head>\n')
self.oprint ('<body>\n')
self.oprint ('<h2>GTester Unit Test Report</h2>\n')
self.oprint ('<table id="ResultTable" width="100%" border="1">\n<tr>\n')
self.oprint ('<th>Program / Testcase </th>\n')
self.oprint ('<th style="width:8em">Duration (sec)</th>\n')
self.oprint ('<th style="width:5em">View</th>\n')
self.oprint ('<th style="width:5em">Result</th>\n')
self.oprint ('</tr>\n')
for tb in self.binaries:
self.handle_binary (tb)
self.handle_totals()
self.oprint ('</table>\n')
self.oprint ('</body>\n')
self.oprint ('</html>\n')
# main program handling
def parse_files_and_args ():
from sys import argv, stdin
files = []
arg_iter = sys.argv[1:].__iter__()
rest = len (sys.argv) - 1
for arg in arg_iter:
rest -= 1
if arg == '--help' or arg == '-h':
print_help ()
sys.exit (0)
elif arg == '--version' or arg == '-v':
print_help (False)
sys.exit (0)
else:
files = files + [ arg ]
return files
def print_help (with_help = True):
import os
print "gtester-report (GLib utils) version", pkginstall_configvars.get ('glib-version', '0.0-uninstalled')
if not with_help:
return
print "Usage: %s [OPTIONS] <gtester-log.xml>" % os.path.basename (sys.argv[0])
print "Generate HTML reports from the XML log files generated by gtester."
print "Options:"
print " --help, -h print this help message"
print " --version, -v print version info"
def main():
from sys import argv, stdin
files = parse_files_and_args()
if len (files) != 1:
print_help (True)
sys.exit (1)
xd = xml.dom.minidom.parse (files[0])
rr = ReportReader()
rr.trampoline (xd)
rw = ReportWriter (rr.binary_list())
rw.printout()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
import commands
import getopt
import sys
SSH_USER = 'bot'
SSH_HOST = 'localhost'
SSH_PORT = 29418
SSH_COMMAND = 'ssh %s@%s -p %d gerrit approve ' % (SSH_USER, SSH_HOST, SSH_PORT)
FAILURE_SCORE = '--code-review=-2'
FAILURE_MESSAGE = 'This commit message does not match the standard.' \
+ ' Please correct the commit message and upload a replacement patch.'
PASS_SCORE = '--code-review=0'
PASS_MESSAGE = ''
def main():
change = None
project = None
branch = None
commit = None
patchset = None
try:
opts, args = getopt.getopt(sys.argv[1:], '', \
['change=', 'project=', 'branch=', 'commit=', 'patchset='])
except getopt.GetoptError, err:
print 'Error: %s' % (err)
usage()
sys.exit(-1)
for arg, value in opts:
if arg == '--change':
change = value
elif arg == '--project':
project = value
elif arg == '--branch':
branch = value
elif arg == '--commit':
commit = value
elif arg == '--patchset':
patchset = value
else:
print 'Error: option %s not recognized' % (arg)
usage()
sys.exit(-1)
if change == None or project == None or branch == None \
or commit == None or patchset == None:
usage()
sys.exit(-1)
command = 'git cat-file commit %s' % (commit)
status, output = commands.getstatusoutput(command)
if status != 0:
print 'Error running \'%s\'. status: %s, output:\n\n%s' % \
(command, status, output)
sys.exit(-1)
commitMessage = output[(output.find('\n\n')+2):]
commitLines = commitMessage.split('\n')
if len(commitLines) > 1 and len(commitLines[1]) != 0:
fail(commit, 'Invalid commit summary. The summary must be ' \
+ 'one line followed by a blank line.')
i = 0
for line in commitLines:
i = i + 1
if len(line) > 80:
fail(commit, 'Line %d is over 80 characters.' % i)
passes(commit)
def usage():
print 'Usage:\n'
print sys.argv[0] + ' --change <change id> --project <project name> ' \
+ '--branch <branch> --commit <sha1> --patchset <patchset id>'
def fail( commit, message ):
command = SSH_COMMAND + FAILURE_SCORE + ' -m \\\"' \
+ _shell_escape( FAILURE_MESSAGE + '\n\n' + message) \
+ '\\\" ' + commit
commands.getstatusoutput(command)
sys.exit(1)
def passes( commit ):
command = SSH_COMMAND + PASS_SCORE + ' -m \\\"' \
+ _shell_escape(PASS_MESSAGE) + ' \\\" ' + commit
commands.getstatusoutput(command)
def _shell_escape(x):
s = ''
for c in x:
if c in '\n':
s = s + '\\\"$\'\\n\'\\\"'
else:
s = s + c
return s
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python2.6
# Copyright (c) 2010, Code Aurora Forum. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# # Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# # Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# # Neither the name of Code Aurora Forum, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# This script is designed to detect when a patchset uploaded to Gerrit is
# 'identical' (determined via git-patch-id) and reapply reviews onto the new
# patchset from the previous patchset.
# Get usage and help info by running: ./trivial_rebase.py --help
# Documentation is available here: https://www.codeaurora.org/xwiki/bin/QAEP/Gerrit
import json
from optparse import OptionParser
import subprocess
from sys import exit
class CheckCallError(OSError):
"""CheckCall() returned non-0."""
def __init__(self, command, cwd, retcode, stdout, stderr=None):
OSError.__init__(self, command, cwd, retcode, stdout, stderr)
self.command = command
self.cwd = cwd
self.retcode = retcode
self.stdout = stdout
self.stderr = stderr
def CheckCall(command, cwd=None):
"""Like subprocess.check_call() but returns stdout.
Works on python 2.4
"""
try:
process = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE)
std_out, std_err = process.communicate()
except OSError, e:
raise CheckCallError(command, cwd, e.errno, None)
if process.returncode:
raise CheckCallError(command, cwd, process.returncode, std_out, std_err)
return std_out, std_err
def GsqlQuery(sql_query, server, port):
"""Runs a gerrit gsql query and returns the result"""
gsql_cmd = ['ssh', '-p', port, server, 'gerrit', 'gsql', '--format',
'JSON', '-c', sql_query]
try:
(gsql_out, gsql_stderr) = CheckCall(gsql_cmd)
except CheckCallError, e:
print "return code is %s" % e.retcode
print "stdout and stderr is\n%s%s" % (e.stdout, e.stderr)
raise
new_out = gsql_out.replace('}}\n', '}}\nsplit here\n')
return new_out.split('split here\n')
def FindPrevRev(changeId, patchset, server, port):
"""Finds the revision of the previous patch set on the change"""
sql_query = ("\"SELECT revision FROM patch_sets,changes WHERE "
"patch_sets.change_id = changes.change_id AND "
"patch_sets.patch_set_id = %s AND "
"changes.change_key = \'%s\'\"" % ((patchset - 1), changeId))
revisions = GsqlQuery(sql_query, server, port)
json_dict = json.loads(revisions[0], strict=False)
return json_dict["columns"]["revision"]
def GetApprovals(changeId, patchset, server, port):
"""Get all the approvals on a specific patch set
Returns a list of approval dicts"""
sql_query = ("\"SELECT value,account_id,category_id FROM patch_set_approvals "
"WHERE patch_set_id = %s AND change_id = (SELECT change_id FROM "
"changes WHERE change_key = \'%s\') AND value <> 0\""
% ((patchset - 1), changeId))
gsql_out = GsqlQuery(sql_query, server, port)
approvals = []
for json_str in gsql_out:
dict = json.loads(json_str, strict=False)
if dict["type"] == "row":
approvals.append(dict["columns"])
return approvals
def GetEmailFromAcctId(account_id, server, port):
"""Returns the preferred email address associated with the account_id"""
sql_query = ("\"SELECT preferred_email FROM accounts WHERE account_id = %s\""
% account_id)
email_addr = GsqlQuery(sql_query, server, port)
json_dict = json.loads(email_addr[0], strict=False)
return json_dict["columns"]["preferred_email"]
def GetPatchId(revision):
git_show_cmd = ['git', 'show', revision]
patch_id_cmd = ['git', 'patch-id']
patch_id_process = subprocess.Popen(patch_id_cmd, stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
git_show_process = subprocess.Popen(git_show_cmd, stdout=subprocess.PIPE)
return patch_id_process.communicate(git_show_process.communicate()[0])[0]
def SuExec(server, port, private_key, as_user, cmd):
suexec_cmd = ['ssh', '-l', "Gerrit Code Review", '-p', port, server, '-i',
private_key, 'suexec', '--as', as_user, '--', cmd]
CheckCall(suexec_cmd)
def DiffCommitMessages(commit1, commit2):
log_cmd1 = ['git', 'log', '--pretty=format:"%an %ae%n%s%n%b"',
commit1 + '^!']
commit1_log = CheckCall(log_cmd1)
log_cmd2 = ['git', 'log', '--pretty=format:"%an %ae%n%s%n%b"',
commit2 + '^!']
commit2_log = CheckCall(log_cmd2)
if commit1_log != commit2_log:
return True
return False
def Main():
server = 'localhost'
usage = "usage: %prog <required options> [--server-port=PORT]"
parser = OptionParser(usage=usage)
parser.add_option("--change", dest="changeId", help="Change identifier")
parser.add_option("--project", help="Project path in Gerrit")
parser.add_option("--commit", help="Git commit-ish for this patchset")
parser.add_option("--patchset", type="int", help="The patchset number")
parser.add_option("--private-key-path", dest="private_key_path",
help="Full path to Gerrit SSH daemon's private host key")
parser.add_option("--server-port", dest="port", default='29418',
help="Port to connect to Gerrit's SSH daemon "
"[default: %default]")
(options, args) = parser.parse_args()
if not options.changeId:
parser.print_help()
exit(0)
if options.patchset == 1:
# Nothing to detect on first patchset
exit(0)
prev_revision = None
prev_revision = FindPrevRev(options.changeId, options.patchset, server,
options.port)
if not prev_revision:
# Couldn't find a previous revision
exit(0)
prev_patch_id = GetPatchId(prev_revision)
cur_patch_id = GetPatchId(options.commit)
if cur_patch_id.split()[0] != prev_patch_id.split()[0]:
# patch-ids don't match
exit(0)
# Patch ids match. This is a trivial rebase.
# In addition to patch-id we should check if the commit message changed. Most
# approvers would want to re-review changes when the commit message changes.
changed = DiffCommitMessages(prev_revision, options.commit)
if changed:
# Insert a comment into the change letting the approvers know only the
# commit message changed
comment_msg = ("\'--message=New patchset patch-id matches previous patchset"
", but commit message has changed.'")
comment_cmd = ['ssh', '-p', options.port, server, 'gerrit', 'approve',
'--project', options.project, comment_msg, options.commit]
CheckCall(comment_cmd)
exit(0)
# Need to get all approvals on prior patch set, then suexec them onto
# this patchset.
approvals = GetApprovals(options.changeId, options.patchset, server,
options.port)
gerrit_approve_msg = ("\'Automatically re-added by Gerrit trivial rebase "
"detection script.\'")
for approval in approvals:
# Note: Sites with different 'copy_min_score' values in the
# approval_categories DB table might want different behavior here.
# Additional categories should also be added if desired.
if approval["category_id"] == "CRVW":
approve_category = '--code-review'
elif approval["category_id"] == "VRIF":
# Don't re-add verifies
#approve_category = '--verified'
continue
elif approval["category_id"] == "SUBM":
# We don't care about previous submit attempts
continue
else:
print "Unsupported category: %s" % approval
exit(0)
score = approval["value"]
gerrit_approve_cmd = ['gerrit', 'approve', '--project', options.project,
'--message', gerrit_approve_msg, approve_category,
score, options.commit]
email_addr = GetEmailFromAcctId(approval["account_id"], server,
options.port)
SuExec(server, options.port, options.private_key_path, email_addr,
' '.join(gerrit_approve_cmd))
exit(0)
if __name__ == "__main__":
Main()
| Python |
#!/usr/bin/python
from optparse import OptionParser
import re
import subprocess
import sys
"""
This script generates a release note from the output of git log
between the specified tags.
Options:
--issues Show output the commits with issues associated with them.
--issue-numbers Show outputs issue numbers of the commits with issues
associated with them
Arguments:
since -- tag name
until -- tag name
Example Input:
* <commit subject>
+
<commit message>
Bug: issue 123
Change-Id: <change id>
Signed-off-by: <name>
Expected Output:
* issue 123 <commit subject>
+
<commit message>
"""
parser = OptionParser(usage='usage: %prog [options] <since> <until>')
parser.add_option('-i', '--issues', action='store_true',
dest='issues_only', default=False,
help='only output the commits with issues association')
parser.add_option('-n', '--issue-numbers', action='store_true',
dest='issue_numbers_only', default=False,
help='only outputs issue numbers of the commits with \
issues association')
(options, args) = parser.parse_args()
if len(args) != 2:
parser.error("wrong number of arguments")
issues_only = options.issues_only
issue_numbers_only = options.issue_numbers_only
since_until = args[0] + '..' + args[1]
proc = subprocess.Popen(['git', 'log', '--reverse', '--no-merges',
since_until, "--format=* %s%n+%n%b"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,)
stdout_value = proc.communicate()[0]
subject = ""
message = []
is_issue = False
# regex pattern to match following cases such as Bug: 123, Issue Bug: 123,
# Bug: GERRIT-123, Bug: issue 123, Bug issue: 123, issue: 123, issue: bug 123
p = re.compile('bug: GERRIT-|bug(:? issue)?:? |issue(:? bug)?:? ',
re.IGNORECASE)
if issue_numbers_only:
for line in stdout_value.splitlines(True):
if p.match(line):
sys.stdout.write(p.sub('', line))
else:
for line in stdout_value.splitlines(True):
# Move issue number to subject line
if p.match(line):
line = p.sub('issue ', line).replace('\n',' ')
subject = subject[:2] + line + subject[2:]
is_issue = True
elif line.startswith('* '):
# Write change log for a commit
if subject != "":
if (not issues_only or is_issue):
# Write subject
sys.stdout.write(subject)
# Write message lines
if message != []:
# Clear + from last line in commit message
message[-1] = '\n'
for m in message:
sys.stdout.write(m)
# Start new commit block
message = []
subject = line
is_issue = False
# Remove commit footers
elif re.match(r'((\w+-)+\w+:)', line):
continue
# Don't add extra blank line if last one is already blank
elif line == '\n' and message and message[-1] != '+\n':
message.append('+\n')
elif line != '\n':
message.append(line)
| Python |
#!/usr/bin/env python
#
# hanzim2dict
#
# Original version written by Michael Robinson (robinson@netrinsics.com)
# Version 0.0.2
# Copyright 2004
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Usage: Run hanzim2dict in a directory containing the "zidianf.gb",
# "cidianf.gb", and "sanzidianf.gb" files from the Hanzi Master distribution
# (available at http://zakros.ucsd.edu/~arobert/hanzim.html). The output
# will be a StarDict dictionary in 2.4.2 format: hanzim.dict, hanzim.idx,
# and hanzim.ifo
#
# The dictionary and index files may be compressed as follows:
# $ gzip -9 hanzim.idx
# $ dictzip hanzim.dict
#
from string import split
from codecs import getdecoder, getencoder
from struct import pack
class Word:
def __init__(self, code, definition):
self.code = code
self.definition = [definition]
def add(self, definition):
self.definition.append(definition)
wordmap = {}
fromGB = getdecoder("GB2312")
toUTF = getencoder("utf_8")
file = open("zidianf.gb", "r")
lines = map(lambda x: split(x[:-1], '\t'), file.readlines())
for line in lines:
code = toUTF(fromGB(line[0])[0])[0]
pinyin = line[2]
definition = '<'+pinyin+'> '+line[3]+' ['+line[1]+']'
if wordmap.has_key(code):
wordmap[code].add(definition)
else:
wordmap[code] = Word(code, definition)
for filename in ("cidianf.gb", "sanzicidianf.gb"):
file = open(filename, "r")
lines = map(lambda x: split(x[:-1], '\t'), file.readlines())
for line in lines:
if len(line) < 2:
print len(line)
continue
code = toUTF(fromGB(line[0][:-2])[0])[0]
definition = line[1]+' ['+line[0][-1:]+']'
if wordmap.has_key(code):
wordmap[code].add(definition)
else:
wordmap[code] = Word(code, definition)
dict = open("hanzim.dict", "wb")
idx = open("hanzim.idx", "wb")
ifo = open("hanzim.ifo", "wb")
offset = 0
count = 0
keylen = 0
keys = list(wordmap.keys())
keys.sort()
for key in keys:
word = wordmap[key]
deftext = ""
multi = False
for d in word.definition:
if multi:
deftext += '\n'
deftext += d
multi = True
dict.write(deftext)
idx.write(key+'\0')
idx.write(pack("!I", offset))
idx.write(pack("!I", len(deftext)))
offset += len(deftext)
count += 1
keylen += len(key)
dict.close()
idx.close()
ifo.write("StarDict's dict ifo file\n")
ifo.write("version=2.4.2\n")
ifo.write("bookname=Hanzi Master 1.3\n")
ifo.write("wordcount="+str(count)+"\n")
ifo.write("idxfilesize="+str(keylen+(count*9))+"\n")
ifo.write("author=Adrian Robert\n")
ifo.write("email=arobert@cogsci.ucsd.edu\n")
ifo.write("website=http://zakros.ucsd.edu/~arobert/hanzim.html\n")
ifo.write("sametypesequence=m\n")
ifo.close()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, os, string, re, glob
import libxml2dom
fencoding = 'utf-8'
whattoextract = u'康熙字典'
#def TextInNode(node):
# result = u''
# for child in node.childNodes:
# if child.nodeType == child.TEXT_NODE:
# result += child.nodeValue
# else:
# result += TextInNode(child)
# return result
filelist = glob.glob('*.htm')
filenum = len(filelist)
num = 0
errorfiles = []
for filename in filelist:
num += 1
print >> sys.stderr, filename, num, 'of', filenum
try:
fp = open(filename, 'r')
doc = libxml2dom.parseString(fp.read(), html=1)
fp.close()
style = doc.getElementsByTagName("style")[0].textContent
style = re.search(r'(?s)\s*\.(\S+)\s*{\s*display:\s*none', style)
displaynone = style.group(1)
tabpages = doc.getElementsByTagName("div")
tabpages = filter(lambda s: s.getAttribute("class") == "tab-page", tabpages)
for tabpage in tabpages:
found = False
for node in tabpage.childNodes:
if node.nodeType == node.ELEMENT_NODE and node.name == 'h2':
if node.textContent == whattoextract:
found = True
break
if found:
spans = tabpage.getElementsByTagName("span")
for span in spans:
if span.getAttribute("class") == "kszi":
character = span.textContent
paragraphs = tabpage.getElementsByTagName("p")
thisitem = character + u'\t'
for paragraph in paragraphs:
if paragraph.getAttribute("class") <> displaynone:
#print TextInNode(paragraph).encode(fencoding)
text = paragraph.textContent
#text = filter(lambda s: not s in u' \t\r\n', text)
text = re.sub(r'\s+', r' ', text)
thisitem += text + u'\\n'
print thisitem.encode(fencoding)
except:
print >> sys.stderr, 'error occured'
errorfiles += [filename]
continue
if errorfiles:
print >> sys.stderr, 'Error files:', '\n'.join(errorfiles)
| Python |
import sys, string
for line in sys.stdin.readlines():
words = string.split(line[:-1], '\t')
muci = words[1]
sheng = words[2]
deng = words[3]
hu = words[4]
yunbu = words[5]
diao = words[6]
fanqie= words[7]
she = words[8]
chars = words[9]
romazi= words[10]
beizhu= words[12]
pinyin= words[13]
psyun = words[22]
if beizhu == '':
print "%s\t%s %s%s%s%s%s%s %sQIE PINYIN%s PSYUN%s\\n%s" % (romazi, muci, sheng, yunbu, she, hu, deng, diao, fanqie, pinyin, psyun, chars)
else:
print "%s\t%s %s%s%s%s%s%s %sQIE PINYIN%s PSYUN%s\\n%s\\n%s" % (romazi, muci, sheng, yunbu, she, hu, deng, diao, fanqie, pinyin, psyun, chars, beizhu)
| Python |
# This tool convert KangXiZiDian djvu files to tiff files.
# Download djvu files: http://bbs.dartmouth.edu/~fangq/KangXi/KangXi.tar
# Character page info: http://wenq.org/unihan/Unihan.txt as kIRGKangXi field.
# Character seek position in Unihan.txt http://wenq.org/unihan/unihandata.txt
# DjVuLibre package provides the ddjvu tool.
# The 410 page is bad, but it should be blank page in fact. so just remove 410.tif
import os
if __name__ == "__main__":
os.system("mkdir tif")
pages = range(1, 1683+1)
for i in pages:
page = str(i)
print(page)
os.system("ddjvu -format=tiff -page="+ page + " -scale=100 -quality=150 KangXiZiDian.djvu"+ " tif/" + page + ".tif")
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gimpfu import *
import os
def prepare_image(image, visibleLayers, size, numColors = None):
"""prepare custom image
image - image object to change
size - size of the image in pixels
visibleLayers - a list of layers that must be visible
"""
for layer in image.layers:
if layer.name in visibleLayers:
layer.visible = True
else:
image.remove_layer(layer)
gimp.pdb.gimp_image_merge_visible_layers(image, CLIP_TO_IMAGE)
drawable=gimp.pdb.gimp_image_get_active_layer(image)
gimp.pdb.gimp_layer_scale_full(drawable, size, size, False, INTERPOLATION_CUBIC)
"""
image 670x670, all layers have the same dimensions
after applying gimp_image_scale_full functions with size=32,
image.width = 32, image.height = 32
layer.width = 27, layer.height = 31
gimp.pdb.gimp_image_scale_full(image, size, size, INTERPOLATION_CUBIC)
"""
#print 'width = {0}, height = {1}'.format(drawable.width, drawable.height)
#print 'width = {0}, height = {1}'.format(image.width, image.height)
if numColors != None:
gimp.pdb.gimp_image_convert_indexed(image, NO_DITHER, MAKE_PALETTE, numColors, False, False, "")
def save_image(image, dstFilePath):
dirPath = os.path.dirname(dstFilePath)
if not os.path.exists(dirPath):
os.makedirs(dirPath)
drawable=gimp.pdb.gimp_image_get_active_layer(image)
gimp.pdb.gimp_file_save(image, drawable, dstFilePath, dstFilePath)
gimp.delete(drawable)
gimp.delete(image)
def create_icon(origImage, visibleLayers, props):
"""visibleLayers - a list of layers that must be visible
props - tuple of image properties in format ((size, bpp), ...)
where:
size - size of the icon in pixels,
bpp - bits per pixel, None to leave by default
return value - new image
"""
iconImage = None
i = 0
for prop in props:
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, visibleLayers, prop[0], prop[1])
image.layers[0].name = 's{0}'.format(i)
if iconImage == None:
iconImage = image
else:
newLayer = gimp.pdb.gimp_layer_new_from_drawable(image.layers[0], iconImage)
gimp.pdb.gimp_image_add_layer(iconImage, newLayer, -1)
gimp.delete(image)
i += 1
return iconImage
def stardict_images(srcFilePath, rootDir):
if not rootDir:
# srcFilePath = rootDir + "/pixmaps/stardict.xcf"
if not srcFilePath.endswith("/pixmaps/stardict.xcf"):
print 'Unable to automatically detect StarDict root directory. Specify non-blank root directory parameter.'
return
dstDirPath = os.path.dirname(srcFilePath)
dstDirPath = os.path.dirname(dstDirPath)
else:
dstDirPath = rootDir
"""
print 'srcFilePath = {0}'.format(srcFilePath)
print 'rootDir = {0}'.format(rootDir)
print 'dstDirPath = {0}'.format(dstDirPath)
"""
dstStarDict_s128_FilePath=os.path.join(dstDirPath, "pixmaps/stardict_128.png")
dstStarDict_s32_FilePath=os.path.join(dstDirPath, "pixmaps/stardict_32.png")
dstStarDict_s16_FilePath=os.path.join(dstDirPath, "pixmaps/stardict_16.png")
dstStarDict_FilePath=os.path.join(dstDirPath, "pixmaps/stardict.png")
dstStarDictEditor_s128_FilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor_128.png")
dstStarDictEditor_s32_FilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor_32.png")
dstStarDictEditor_s16_FilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor_16.png")
dstStarDictIconFilePath=os.path.join(dstDirPath, "pixmaps/stardict.ico")
dstStarDictEditorIconFilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor.ico")
dstStarDictUninstIconFilePath=os.path.join(dstDirPath, "pixmaps/stardict-uninst.ico")
dstDockletNormalFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_normal.png")
dstDockletScanFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_scan.png")
dstDockletStopFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_stop.png")
dstDockletGPENormalFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_gpe_normal.png")
dstDockletGPEScanFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_gpe_scan.png")
dstDockletGPEStopFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_gpe_stop.png")
dstWordPickFilePath=os.path.join(dstDirPath, "src/win32/acrobat/win32/wordPick.bmp")
origImage=gimp.pdb.gimp_file_load(srcFilePath, srcFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 128)
save_image(image, dstStarDict_s128_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 32)
save_image(image, dstStarDict_s32_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 16)
save_image(image, dstStarDict_s16_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 64)
save_image(image, dstStarDict_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "edit"), 128)
save_image(image, dstStarDictEditor_s128_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "edit"), 32)
save_image(image, dstStarDictEditor_s32_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "edit"), 16)
save_image(image, dstStarDictEditor_s16_FilePath)
image = create_icon(origImage, ("book1", "book2"),
((16, None), (32, None), (48, None), (16, 256), (32, 256), (48, 256), (256, None))
)
save_image(image, dstStarDictIconFilePath)
image = create_icon(origImage, ("book1", "book2", "edit"),
((16, None), (32, None), (48, None), (16, 256), (32, 256), (48, 256), (256, None))
)
save_image(image, dstStarDictEditorIconFilePath)
image = create_icon(origImage, ("book1", "book2", "cross"),
((16, None), (32, None), (48, None), (16, 256), (32, 256), (48, 256), (256, None))
)
save_image(image, dstStarDictUninstIconFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 32)
save_image(image, dstDockletNormalFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "search"), 32)
save_image(image, dstDockletScanFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "stop"), 32)
save_image(image, dstDockletStopFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 16)
save_image(image, dstDockletGPENormalFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "search"), 16)
save_image(image, dstDockletGPEScanFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "stop"), 16)
save_image(image, dstDockletGPEStopFilePath)
# See AVToolButtonNew function in PDF API Reference
# Recommended icon size is 18x18, but it looks too small...
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 22)
gimp.set_background(192, 192, 192)
gimp.pdb.gimp_layer_flatten(image.layers[0])
save_image(image, dstWordPickFilePath)
register(
"stardict_images",
"Create images for StarDict",
"Create images for StarDict",
"StarDict team",
"GPL",
"Mar 2011",
"<Toolbox>/Tools/stardict images",
"",
[
(PF_FILE, "src_image", "Multilayer image used as source for all other images in StarDict, "
+ "normally that is pixmaps/stardict.xcf is StarDict source tree.", None),
(PF_DIRNAME, "stardict_dir", "Root directory of StarDict source tree. New images will be saved here.", None)
],
[],
stardict_images)
main()
| Python |
#!/usr/bin/python
# WinVNKey Hannom Database to Stardict dictionary source Conversion Tool
# coded by wesnoth@ustc on 070804
# http://winvnkey.sourceforge.net
import sys, os, string, types, pprint
infileencoding = 'utf-16-le'
outfileencoding = 'utf-8'
def showhelp():
print "Usage: %s filename" % sys.argv[0]
def ishantu(str):
if len(str) > 0 and ord(str[0]) > 0x2e80:
return True
else:
return False
def mysplit(line):
status = 0 # 0: normal, 1: quote
i = 0
line = line.lstrip()
linelen = len(line)
while i < linelen:
if status == 0 and line[i].isspace():
break
if line[i] == u'"':
status = 1 - status
i += 1
#print 'mysplit: i=%d, line=%s' % (i, `line`)
if i == 0:
return []
else:
line = [line[:i], line[i:].strip()]
if line[1] == u'':
return [line[0]]
else:
return line
if __name__ == '__main__':
if len(sys.argv) <> 2:
showhelp()
else:
fp = open(sys.argv[1], 'r')
print 'Reading file...'
lines = unicode(fp.read(), infileencoding).split(u'\n')
lineno = 0
hugedict = {}
print 'Generating Han-Viet dict...'
for line in lines:
lineno += 1
if line.endswith(u'\r'):
line = line[:-1]
if line.startswith(u'\ufeff'):
line = line[1:]
ind = line.find(u'#')
if ind >= 0:
line = line[:ind]
line = mysplit(line)
if len(line) == 0:
continue
elif len(line) == 1:
continue # ignore this incomplete line
if line[0].startswith(u'"') and line[0].endswith(u'"'):
line[0] = line[0][1:-1]
if line[0].startswith(u'U+') or line[0].startswith(u'u+'):
line[0] = unichr(int(line[0][2:], 16))
if not ishantu(line[0]):
continue # invalid Han character
#print 'error occurred on line %d: %s' % (lineno, `line`)
if line[1].startswith(u'"') and line[1].endswith(u'"'):
line[1] = line[1][1:-1]
line[1] = filter(None, map(string.strip, line[1].split(u',')))
#hugedict[line[0]] = hugedict.get(line[0], []) + line[1]
for item in line[1]:
if not hugedict.has_key(line[0]):
hugedict[line[0]] = [item]
elif not item in hugedict[line[0]]:
hugedict[line[0]] += [item]
#print lineno, `line`
#for hantu, quocngu in hugedict.iteritems():
# print hantu.encode('utf-8'), ':',
# for viettu in quocngu:
# print viettu.encode('utf-8'), ',',
# print
fp.close()
print 'Generating Viet-Han dict...'
dicthuge = {}
for hantu, quocngu in hugedict.iteritems():
for viettu in quocngu:
if not dicthuge.has_key(viettu):
dicthuge[viettu] = [hantu]
elif not hantu in dicthuge[viettu]:
dicthuge[viettu] += [hantu]
print 'Writing Han-Viet dict...'
gp = open('hanviet.txt', 'w')
for hantu, quocngu in hugedict.iteritems():
gp.write(hantu.encode('utf-8'))
gp.write('\t')
gp.write((u', '.join(quocngu)).encode('utf-8'))
gp.write('\n')
gp.close()
print 'Writing Viet-Han dict...'
gp = open('viethan.txt', 'w')
for quocngu,hantu in dicthuge.iteritems():
gp.write(quocngu.encode('utf-8'))
gp.write('\t')
gp.write((u' '.join(hantu)).encode('utf-8'))
gp.write('\n')
gp.close()
| Python |
#!/usr/bin/env python
#
# uyghur2dict
# By Abdisalam (anatilim@gmail.com), inspired by Michael Robinson's hanzim2dict converter.
#
# Original version, hanzim2dict, written by Michael Robinson (robinson@netrinsics.com)
# Version 0.0.2
# Copyright 2004
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Usage: Run hanzim2dict in a directory containing the "zidianf.gb",
# "cidianf.gb", and "sanzidianf.gb" files from the Hanzi Master distribution
# (available at http://zakros.ucsd.edu/~arobert/hanzim.html). The output
# will be a StarDict dictionary in 2.4.2 format: hanzim.dict, hanzim.idx,
# and hanzim.ifo
#
# The dictionary and index files may be compressed as follows:
# $ gzip -9 hanzim.idx
# $ dictzip hanzim.dict
#
from string import split
from struct import pack
class Word:
def __init__(self, code, definition):
self.code = code
self.definition = [definition]
def add(self, definition):
self.definition.append(definition)
wordmap = {}
file = open("ChineseUyghurStarDict.txt", "r")
lines = map(lambda x: split(x[:-1], '\t\t'), file.readlines())
for line in lines:
code = line[0]
definition = line[1]
if wordmap.has_key(code):
wordmap[code].add(definition)
else:
wordmap[code] = Word(code, definition)
dict = open("Anatilim_Chinese_Uyghur.dict", "wb")
idx = open("Anatilim_Chinese_Uyghur.idx", "wb")
ifo = open("Anatilim_Chinese_Uyghur.ifo", "wb")
offset = 0
count = 0
keylen = 0
keys = list(wordmap.keys())
keys.sort()
for key in keys:
word = wordmap[key]
deftext = ""
for d in word.definition:
deftext=d
deftext += '\0'
dict.write(deftext)
idx.write(key+'\0')
idx.write(pack("!I", offset))
idx.write(pack("!I", len(deftext)))
offset += len(deftext)
count += 1
keylen += len(key)
dict.close()
idx.close()
ifo.write("StarDict's dict ifo file\n")
ifo.write("version=2.4.2\n")
ifo.write("bookname=Anatilim 《汉维词典》-- Anatilim Chinese Uyghur Dictionary\n")
ifo.write("wordcount="+str(count)+"\n")
ifo.write("idxfilesize="+str(keylen+(count*9))+"\n")
ifo.write("author=Abdisalam\n")
ifo.write("email=anatilim@gmail.com\n")
ifo.write("description=感谢新疆维吾尔自治区语委会、新疆青少年出版社为我们提供《汉维词典》的词库\n")
ifo.write("sametypesequence=m\n")
ifo.close() | Python |
#!/usr/bin/env python2
#
# converts XML JMDict to Stardict idx/dict format
# JMDict website: http://www.csse.monash.edu.au/~jwb/j_jmdict.html
#
# Date: 3rd July 2003
# Author: Alastair Tse <acnt2@cam.ac.uk>
# License: BSD (http://www.opensource.org/licenses/bsd-license.php)
#
# Usage: jm2stardict expects the file JMdict.gz in the current working
# directory and outputs to files jmdict-ja-en and jmdict-en-ja
#
# To compress the resulting files, use:
#
# gzip -9 jmdict-en-ja.idx
# gzip -9 jmdict-ja-en.idx
# dictzip jmdict-en-ja.dict
# dictzip jmdict-ja-en.dict
#
# note - dictzip is from www.dict.org
#
import xml.sax
from xml.sax.handler import *
import gzip
import struct, sys, string, codecs,os
def text(nodes):
label = ""
textnodes = filter(lambda x: x.nodeName == "#text", nodes)
for t in textnodes:
label += t.data
return label
def strcasecmp(a, b):
result = 0
# to ascii
#str_a = string.join(filter(lambda x: ord(x) < 128, a[0]), "").lower()
#str_b = string.join(filter(lambda x: ord(x) < 128, b[0]), "").lower()
#result = cmp(str_a, str_b)
# if result == 0:
result = cmp(a[0].lower() , b[0].lower())
return result
def merge_dup(list):
newlist = []
lastkey = ""
for x in list:
if x[0] == lastkey:
newlist[-1] = (newlist[-1][0], newlist[-1][1] + "\n" + x[1])
else:
newlist.append(x)
lastkey = x[0]
return newlist
class JMDictHandler(ContentHandler):
def __init__(self):
self.mapping = []
self.state = ""
self.buffer = ""
def startElement(self, name, attrs):
if name == "entry":
self.kanji = []
self.chars = []
self.gloss = []
self.state = ""
self.buffer = ""
elif name == "keb":
self.state = "keb"
elif name == "reb":
self.state = "reb"
elif name == "gloss" and not attrs:
self.state = "gloss"
elif name == "xref":
self.state = "xref"
def endElement(self, name):
if name == "entry":
self.mapping.append((self.kanji, self.chars, self.gloss))
elif name == "keb":
self.kanji.append(self.buffer)
elif name == "reb":
self.chars.append(self.buffer)
elif name == "gloss" and self.buffer:
self.gloss.append(self.buffer)
elif name == "xref":
self.gloss.append(self.buffer)
self.buffer = ""
self.state = ""
def characters(self, ch):
if self.state in ["keb", "reb", "gloss", "xref"]:
self.buffer = self.buffer + ch
def map_to_file(dictmap, filename):
dict = open(filename + ".dict","wb")
idx = open(filename + ".idx","wb")
offset = 0
idx.write("StarDict's idx file\nversion=2.1.0\n");
idx.write("bookname=" + filename + "\nauthor=Jim Breen\nemail=j.breen@csse.monash.edu.au\nwebsite=http://www.csse.monash.edu.au/~jwb/j_jmdict.html\ndescription=Convert to stardict by Alastair Tse <liquidx@gentoo.org>, http://www-lce.eng.cam.ac.uk/~acnt2/code/\ndate=2003.07.01\n")
idx.write("sametypesequence=m\n")
idx.write("BEGIN:\n")
idx.write(struct.pack("!I",len(dictmap)))
for k,v in dictmap:
k_utf8 = k.encode("utf-8")
v_utf8 = v.encode("utf-8")
idx.write(k_utf8 + "\0")
idx.write(struct.pack("!I",offset))
idx.write(struct.pack("!I",len(v_utf8)))
offset += len(v_utf8)
dict.write(v_utf8)
dict.close()
idx.close()
if __name__ == "__main__":
print "opening xml dict .."
f = gzip.open("JMdict.gz")
#f = open("jmdict_sample.xml")
print "parsing xml file .."
parser = xml.sax.make_parser()
handler = JMDictHandler()
parser.setContentHandler(handler)
parser.parse(f)
f.close()
print "creating dictionary .."
# create a japanese -> english mappings
jap_to_eng = []
for kanji,chars,gloss in handler.mapping:
for k in kanji:
key = k
value = string.join(chars + gloss, "\n")
jap_to_eng.append((key,value))
for c in chars:
key = c
value = string.join(kanji + gloss, "\n")
jap_to_eng.append((key,value))
eng_to_jap = []
for kanji,chars,gloss in handler.mapping:
for k in gloss:
key = k
value = string.join(kanji + chars, "\n")
eng_to_jap.append((key,value))
print "sorting dictionary .."
jap_to_eng.sort(strcasecmp)
eng_to_jap.sort(strcasecmp)
print "merging and pruning dups.."
jap_to_eng = merge_dup(jap_to_eng)
eng_to_jap = merge_dup(eng_to_jap)
print "writing to files.."
# create dict and idx file
map_to_file(jap_to_eng, "jmdict-ja-en")
map_to_file(eng_to_jap, "jmdict-en-ja")
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Script for decoding Lingea Dictionary (.trd) file
# Result is <header>\t<definition> file, convertable easily
# by stardict-editor from package stardict-tools into native
# Stardict dictionary (stardict.sf.net and www.stardict.org)
#
# Copyright (C) 2007 - Klokan Petr Přidal (www.klokan.cz)
#
# Based on script CobuildConv.rb by Nomad
# http://hp.vector.co.jp/authors/VA005784/cobuild/cobuildconv.html
#
# Version history:
# 0.4 (30.10.2007) Patch by Petr Dlouhy, optional HTML generation
# 0.3 (28.10.2007) Patch by Petr Dlouhy, cleanup, bugfix. More dictionaries.
# 0.2 (19.7.2007) Changes, documentation, first 100% dictionary
# 0.1 (20.5.2006) Initial version based on Nomad specs
#
# Supported dictionaries:
# - Lingea Německý Kapesní slovník
# - Lingea Anglický Kapesní slovník
# - Lingea 2002 series (theoretically)
#
# Modified by:
# - Petr Dlouhy (petr.dlouhy | email.cz)
# Generalization of data block rules, sampleFlag 0x04, sound out fix, data phrase prefix with comment (0x04)
# HTML output, debugging patch, options on command line
#
# <write your name here>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
# VERSION
VERSION = "0.4"
import getopt, sys
def usage():
print "Lingea Dictionary Decoder"
print "-------------------------"
print "Version: %s" % VERSION
print "Copyright (C) 2007 - Klokan Petr Pridal, Petr Dlouhy"
print
print "Usage: python lingea-trd-decoder.py DICTIONARY.trd > DICTIONARY.tab"
print "Result convertion by stardict-tools: /usr/lib/stardict-tools/tabfile"
print
print " -o <num> --out-style : Output style"
print " 0 no tags"
print " 1 \\n tags"
print " 2 html tags"
print " -h --help : Print this message"
print " -d --debug : Degub"
print " -r --debug-header : Degub - print headers"
print " -a --debug-all : Degub - print all records"
print " -l --debug-limit : Degub limit"
print
print "For HTML support in StarDict dictionary .ifo has to contain:"
print "sametypesequence=g"
print "!!! Change the .ifo file after generation by tabfile !!!"
print
try:
opts, args = getopt.getopt(sys.argv[1:], "hdo:ral:", ["help", "debug", "out-style=", "debug-header", "debug-all", "debug-limit="])
except getopt.GetoptError:
usage()
print "ERROR: Bad option"
sys.exit(2)
import locale
DEBUG = False
OUTSTYLE = 2
DEBUGHEADER = False
DEBUGALL = False
DEBUGLIMIT = 1
for o, a in opts:
if o in ("-d", "-debug"):
# DEBUGING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
DEBUG = True
if o in ("-o", "--out-style"):
# output style
OUTSTYLE = locale.atoi(a)
if OUTSTYLE > 2:
usage()
print "ERROR: Output style not specified"
if o in ("-r", "--debug-header"):
# If DEBUG and DEBUGHEADER, then print just all header records
DEBUGHEADER = True
if o in ("-a", "--debug-all"):
# If DEBUG and DEBUGALL then print debug info for all records
DEBUGALL = True
if o in ("-h", "--help"):
usage()
sys.exit(0)
if o in ("-l", "--debug-limit"):
# Number of wrong records for printing to stop during debugging
DEBUGLIMIT = locale.atoi(a)
# FILENAME is a first parameter on the commandline now
if len(args) == 1:
FILENAME = args[0]
else:
usage()
print "ERROR: You have to specify .trd file to decode"
sys.exit(2)
from struct import *
import re
alpha = ['\x00', 'a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z','#AL27#','#AL28#','#AL29#',
'#AL30#','#AL31#', ' ', '.', '<', '>', ',', ';', '-', '#AL39#',
'#GRAVE#', '#ACUTE#', '#CIRC#', '#TILDE#', '#UML#', '#AL45#', '#AL46#', '#CARON#', '#AL48#', '#CEDIL#',
'#AL50#', '#AL51#', '#GREEK#', '#AL53#', '#AL54#', '#AL55#', '#AL56#', '#AL57#', '#AL58#', '#SYMBOL#',
'#AL60#', '#UPCASE#', '#SPECIAL#', '#UNICODE#'] # 4 bytes after unicode
upcase = ['#UP0#','#UP1#','#UP2#','#UP3#','#UP4#','#UP5#','#UP6#','#UP7#','#UP8#','#UP9#',
'#UP10#','#UP11#','#UP12#','#UP13#','#UP14#','#UP15#','#UP16#','#UP17#','#UP18#','#UP19#',
'#UP20#','#UP21#','#UP22#','#UP23#','#UP24#','#UP25#','#UP26#','#UP27#','#UP28#','#UP29#',
'#UP30#','#UP31#','A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P','Q','R',
'S','T','U','V','W','X','Y','Z','#UP58#','#UP59#',
'#UP60#','#UP61#','#UP62#','#UP63#']
upcase_pron = ['#pr0#', '#pr1#','#pr2#','#pr3#','#pr4#','#pr5#','#pr6#','#pr7#','#pr8#','#pr9#',
'#pr10#', '#pr11#','#pr12#','#pr13#','#pr14#','#pr15#','#pr16#','#pr17#','#pr18#','#pr19#',
'#pr20#', '#pr21#','#pr22#','#pr23#','#pr24#','#pr25#','#pr26#','#pr27#','#pr28#','#pr29#',
'#pr30#', '#pr31#','ɑ','#pr33#','ʧ','ð','ə','ɜ','#pr38#','æ',
'ɪ', 'ɭ','#pr42#','ŋ','#pr44#','ɳ','ɔ','#pr47#','ɒ','ɽ',
'ʃ', 'θ','ʊ','ʌ','#pr54#','#pr55#','#pr56#','ʒ','#pr58#','#pr59#',
'#pr60#', '#pr61#','#pr62#','#pr63#']
symbol = ['#SY0#', '#SY1#','#SY2#','#SY3#','§','#SY5#','#SY6#','#SY7#','#SY8#','#SY9#',
'#SY10#', '#SY11#','#SY12#','#SY13#','#SY14#','™','#SY16#','#SY17#','¢','£',
'#SY20#', '#SY21#','#SY22#','#SY23#','©','#SY25#','#SY26#','#SY27#','®','°',
'#SY30#', '²','³','#SY33#','#SY34#','#SY35#','¹','#SY37#','#SY38#','#SY39#',
'½', '#SY41#','#SY42#','×','÷','#SY45#','#SY46#','#SY47#','#SY48#','#SY49#',
'#SY50#', '#SY51#','#SY52#','#SY53#','#SY54#','#SY55#','#SY56#','#SY57#','#SY58#','#SY59#',
'#SY60#', '#SY61#','#SY62#','#SY63#']
special = ['#SP0#', '!','"','#','$','%','&','\'','(',')',
'*', '+','#SP12#','#SP13#','#SP14#','/','0','1','2','3',
'4', '5','6','7','8','9',':',';','<','=',
'>', '?','@','[','\\',']','^','_','`','{',
'|', '}','~','#SP43#','#SP44#','#SP45#','#SP46#','#SP47#','#SP48#','#SP49#',
'#SP50#', '#SP51#','#SP52#','#SP53#','#SP54#','#SP55#','#SP56#','#SP57#','#SP58#','#SP59#',
'#SP60#', '#SP61#','#SP62#','#SP63#']
wordclass = ('#0#','n:','adj:','pron:','#4#','v:','adv:','prep:','#8#','#9#',
'intr:','phr:','#12#','#13#','#14#','#15#','#16#','#17#','#18#','#19#',
'#20#','#21#','#22#','#23#','#24#','#25#','#26#','#27#','#28#','#29#',
'#30#','#31#')
if OUTSTYLE == 0:
tag = {
'db':('' ,''), #Data begining
'rn':('' ,'\t'), #Record name
'va':('' ,' '), #Header variant
'wc':('(' ,')'), #WordClass
'pa':('' ,' '), #Header parts
'fo':('(' ,') '), #Header forms
'on':('(' ,')' ), #Header origin note
'pr':('[' ,']'), #Header pronunciation
'dv':('{' ,'} '), #Header dataVariant
'sa':('`' ,'`' ), #Data sample
'sw':('' ,''), #Data sample wordclass; is no printed by Lingea
'do':('`' ,'`' ), #Data origin note
'df':('' ,' '), #Data definition
'ps':('"' ,'" '), #Data phrase short form
'pg':('"' ,' = '), #Data phrase green
'pc':('`' ,'`'), #Data phrase comment; this comment is not printed by Lingea), but it seems useful
'p1':('"' ,' = '), #Data phrase 1
'p2':('' ,'" ' ), #Data phrase 2
'sp':('"' ,' = ' ),#Data simple phrase
'b1':('"' ,' = '), #Data phrase (block) 1
'b2':('" ' ,''), #Data phrase (block) 2
}
if OUTSTYLE == 1:
tag = {
'db':('•' ,''), #Data begining
'rn':('' ,'\t'), #Record name
'va':('' ,' '), #Header variant
'wc':('' ,'\\n'), #WordClass
'pa':('' ,':\\n'), #Header parts
'fo':('(' ,') '), #Header forms
'on':('(' ,')\\n' ), #Header origin note
'pr':('[' ,']\\n'), #Header pronunciation
'dv':('{' ,'} '), #Header dataVariant
'sa':(' ' ,'\\n' ), #Data sample
'sw':('' ,''), #Data sample wordclass; is not printed by Lingea
'do':(' ' ,' ' ), #Data origin note
'df':(' ' ,'\\n'), #Data definition
'ps':(' ' ,'\\n'), #Data phrase short form
'pg':(' ' ,' '), #Data phrase green
'pc':(' ' ,' '), #Data phrase comment; this comment is not printed by Lingea), but it seems useful
'p1':(' ' ,' '), #Data phrase 1
'p2':(' ' ,'\\n' ), #Data phrase 2
'sp':('' ,'\\n' ), #Data simple phrase
'b1':('"' ,' = '), #Data phrase (block) 1
'b2':('" ' ,''), #Data phrase (block) 2
}
if OUTSTYLE == 2:
tag = {
'db':('•' ,''), #Data begining
'rn':('' ,'\t'), #Record name
'va':('' ,' '), #Header variant
'wc':('<span size="larger" color="darkred" weight="bold">','</span>\\n'), #WordClass
'pa':('<span size="larger" color="darkred" weight="bold">',':</span>\\n'), #Header parts
'fo':('(' ,') '), #Header forms
'on':('<span color="blue">(' ,')</span>\\n' ), #Header origin note
'pr':('[' ,']\\n'), #Header pronunciation
'dv':('{' ,'} '), #Header dataVariant
'sa':(' <span color="darkred" weight="bold">' ,'</span>\\n' ), #Data sample
'sw':('' ,''), #Data sample wordclass; is not printed by Lingea
'do':(' <span color="darkred" weight="bold">' ,'</span> ' ), #Data origin note
'df':(' <span weight="bold">' ,'</span>\\n'), #Data definition
'ps':(' <span color="dimgray" weight="bold">' ,'</span>\\n'), #Data phrase short form
'pg':(' <span color="darkgreen" style="italic">' ,'</span> '), #Data phrase green
'pc':(' <span color="darkgreen" style="italic">' ,'</span> '), #Data phrase comment; this comment is not printed by Lingea), but it seems useful
'p1':(' <span color="dimgray" style="italic">' ,'</span> '), #Data phrase 1
'p2':(' ' ,'\\n' ), #Data phrase 2
'sp':('<span color="cyan">' ,'</span>\\n' ), #Data simple phrase
'b1':('"' ,' = '), #Data phrase (block) 1
'b2':('" ' ,''), #Data phrase (block) 2
}
# Print color debug functions
purple = lambda c: '\x1b[1;35m'+c+'\x1b[0m'
blue = lambda c: '\x1b[1;34m'+c+'\x1b[0m'
cyan = lambda c: '\x1b[36m'+c+'\x1b[0m'
gray = lambda c: '\x1b[1m'+c+'\x1b[0m'
def getRec(n):
"""Get data stream for record of given number"""
if n >= 0 and n < entryCount:
f.seek(index[n])
return f.read(index[n+1] - index[n])
else:
return ''
def decode_alpha( stream, nullstop=True):
"""Decode 6-bit encoding data stream from the begining untit first NULL"""
offset = 0
triple = 0
result = []
while triple < len( stream ):
if offset % 4 == 0:
c = stream[triple] >> 2
triple += 1
if offset % 4 == 1:
c = (stream[triple-1] & 3) << 4 | stream[triple] >> 4
triple += 1
if offset % 4 == 2:
c = (stream[triple-1] & 15) << 2 | (stream[triple] & 192) >> 6
triple += 1
if offset % 4 == 3:
c = stream[triple-1] & 63
if c == 0 and nullstop:
break
offset += 1
# TODO: ENCODE UNICODE 4 BYTE STREAM!!! and but it after #UNICODE# as unichr()
result.append(c)
return decode_alpha_postprocessing(result), triple - 1
def decode_alpha_postprocessing( input ):
"""Lowlevel alphabet decoding postprocessing, combines tuples into one character"""
result = ""
input.extend([0x00]*5)
# UPCASE, UPCASE_PRON, SYMBOL, SPECIAL
skip = False
for i in range(0,len(input)-1):
if skip:
skip = False
continue
bc = input[i]
c = alpha[bc]
bc1 = input[i+1]
c1 = alpha[bc1]
if bc < 40:
result += c
else:
if c == "#GRAVE#":
if c1 == 'a': result += 'à'
else: result += '#GRAVE%s#' % c1
elif c == "#UML#":
if c1 == 'o': result += 'ö'
elif c1 == 'u': result += 'ü'
elif c1 == 'a': result += 'ä'
elif c1 == ' ': result += 'Ä'
elif c1 == '#AL46#': result += 'Ö'
elif c1 == '#GREEK#': result += 'Ü'
else: result += '#UML%s#' % c1
elif c == "#ACUTE#":
if c1 == 'a': result += 'á'
elif c1 == 'e': result += 'é'
elif c1 == 'i': result += 'í'
elif c1 == 'o': result += 'ó'
elif c1 == 'u': result += 'ú'
elif c1 == 'y': result += 'ý'
elif c1 == ' ': result += 'Á'
elif c1 == '#GRAVE#': result += 'Í'
else: result += '#ACUTE%s#' % c1
elif c == "#CARON#":
if c1 == 'r': result += 'ř'
elif c1 == 'c': result += 'č'
elif c1 == 's': result += 'š'
elif c1 == 'z': result += 'ž'
elif c1 == 'e': result += 'ě'
elif c1 == 'd': result += 'ď'
elif c1 == 't': result += 'ť'
elif c1 == 'a': result += 'å'
elif c1 == 'u': result += 'ů'
elif c1 == 'n': result += 'ň'
elif c1 == '<': result += 'Č'
elif c1 == '#CEDIL#': result += 'Ř'
elif c1 == '#AL50#': result += 'Š'
elif c1 == '#AL57#': result += 'Ž'
else: result += '#CARON%s#' % c1
elif c == "#UPCASE#":
result += upcase[bc1]
elif c == "#SYMBOL#":
result += symbol[bc1]
elif c == "#AL51#":
if c1 == 's': result += 'ß'
elif c == "#AL48#":
result += "#AL48#%s" % c1
elif c == "#SPECIAL#":
result += special[bc1]
elif c == "#UNICODE#":
result += '#UNICODE%s#' % bc1
elif c == "#CIRC#":
if c1 == 'a': result += 'â'
else: result += '#CARON%s#' % c1
else:
result += '%sX%s#' % (c[:-1], bc1)
skip = True
return result
def pronunciation_encode(s):
"""Encode pronunciation upcase symbols into IPA symbols"""
for i in range(0, 64):
s = s.replace(upcase[i], upcase_pron[i])
return s
re_d = re.compile(r'<d(.*?)>')
re_w = re.compile(r'<w(.*?)>')
re_y = re.compile(r'<y(.*?)>')
re_c = re.compile(r'<c(.*?)>')
def decode_tag_postprocessing(input):
"""Decode and replace tags used in lingea dictionaries; decode internal tags"""
s = input
# General information in http://www.david-zbiral.cz/El-slovniky-plnaverze.htm#_Toc151656799
# TODO: Better output handling
if OUTSTYLE == 0:
# ?? <d...>
s = re_d.sub(r'(\1)',s)
# ?? <w...>
s = re_w.sub(r'(\1)',s)
# ?? <y...>
s = re_y.sub(r'(\1)',s)
# ?? <c...>
s = re_c.sub(r'(\1)',s)
# ...
if OUTSTYLE == 1:
# ?? <d...>
s = re_d.sub(r'(\1)',s)
# ?? <w...>
s = re_w.sub(r'(\1)',s)
# ?? <y...>
s = re_y.sub(r'(\1)',s)
# ?? <c...>
s = re_c.sub(r'(\1)',s)
# ...
if OUTSTYLE == 2:
# ?? <d...>
s = re_d.sub(r'<span size="small" color="blue">(\1)</span>',s)
# ?? <w...>
s = re_w.sub(r'<span size="small" color="blue" style="italic">\1</span>',s)
# ?? <y...>
s = re_y.sub(r'<span size="small" color="blue" style="italic">\1</span>',s)
# ?? <c...>
s = re_c.sub(r'<span size="small" color="blue" style="italic">\1</span>',s)
# ...
return s
def toBin( b ):
"""Prettify debug output format: hex(bin)dec"""
original = b
r = 0;
i = 1;
while b > 0:
if b & 0x01 != 0: r += i
i *= 10
b = b >> 1
return "0x%02X(%08d)%03d" % (original, r, original)
def out( comment = "", skip = False):
"""Read next byte or string (with skip=True) and output DEBUG info"""
global bs, pos
s, triple = decode_alpha(bs[pos:])
s = s.split('\x00')[0] # give me string until first NULL
if (comment.find('%') != -1):
if skip:
comment = comment % s
else:
comment = comment % bs[pos]
if DEBUG: print "%03d %s %s | %s | %03d" % (pos, toBin(bs[pos]),comment, s, (triple + pos))
if skip:
pos += triple + 1
return s.replace('`','') # Remove '`' character from words
else:
pos += 1
return bs[pos-1]
outInt = lambda c: out(c)
outStr = lambda c: out(c, True)
def decode(stream):
"""Decode byte stream of one record, return decoded string with formatting in utf"""
result = ""
global bs, pos
# stream - data byte stream for one record
bs = unpack("<%sB" % len(stream), stream)
# bs - list of bytes from stream
pos = 0
itemCount = outInt("ItemCount: %s") # Number of blocks in the record
mainFlag = outInt("MainFlag: %s")
# HEADER BLOCK
# ------------
if mainFlag & 0x01:
headerFlag = outInt("HeaderFlag: %s") # Blocks in header
if headerFlag & 0x01:
result += tag['rn'][0] + outStr("Header record name: %s").replace('_','') + tag['rn'][1] # Remove character '_' from index
if headerFlag & 0x02:
result += tag['va'][0] + outStr("Header variant: %s") + tag['va'][1]
if headerFlag & 0x04:
s = outInt("Header wordclass: %s")
if s < 32:
result += tag['wc'][0] + wordclass[s] + tag['wc'][1]
else:
raise "Header wordclass out of range in: %s" % result
if headerFlag & 0x08:
result += tag['pa'][0] + outStr("Header parts: %s") + tag['pa'][1]
if headerFlag & 0x10:
result += tag['fo'][0] + outStr("Header forms: %s") + tag['fo'][1]
if headerFlag & 0x20:
result += tag['on'][0] + outStr("Header origin note: %s") + tag['on'][1]
if headerFlag & 0x80:
result += tag['pr'][0] + pronunciation_encode(outStr("Header pronunciation: %s")) + tag['pr'][1]
# Header data block
if mainFlag & 0x02:
headerFlag = outInt("Header dataFlag: %s") # Blocks in header
if headerFlag & 0x02:
result += tag['dv'][0] + outStr("Header dataVariant: %s")+ tag['dv'][1]
# ??? Link elsewhere
pass
# SOUND DATA REFERENCE
if mainFlag & 0x80:
outInt("Sound reference byte #1: %s")
outInt("Sound reference byte #2: %s")
outInt("Sound reference byte #3: %s")
outInt("Sound reference byte #4: %s")
outInt("Sound reference byte #5: %s")
#out("Sound data reference (5 bytes)", 6)
# TODO: Test all mainFlags in header!!!!
#result += ': '
li = 0
#print just every first word class identifier
# TODO: this is not systematic (should be handled by output)
global lastWordClass
lastWordClass = 0
# DATA BLOCK(S)
# -------------
for i in range(0, itemCount):
item = tag['db'][0] + tag['db'][1]
ol = False
dataFlag = outInt("DataFlag: %s -----------------------------")
if dataFlag & 0x01: # small index
sampleFlag = outInt("Data sampleFlag: %s")
if sampleFlag & 0x01:
result += tag['sa'][0] + outStr("Data sample: %s") + tag['sa'][1]
if sampleFlag & 0x04:
s = outInt("Data wordclass: %s")
if s != lastWordClass:
if s < 32:
result += tag['wc'][0] + wordclass[s] + tag['wc'][1]
else:
raise "Header wordclass out of range in: %s" % result
lastWordClass = s
if sampleFlag & 0x08:
result += tag['sw'][0] + outStr("Data sample wordclass: %s") + tag['sw'][1]
if sampleFlag & 0x10:
outInt("Data sample Int: %s")
outInt("Data sample Int: %s")
outInt("Data sample Int: %s")
if sampleFlag & 0x20:
item += tag['do'][0] + outStr("Data origin note: %s") + tag['do'][1]
if sampleFlag & 0x80:
item += " "
result += tag['pr'][0] + pronunciation_encode(outStr("Data sample pronunciation: %s")) + tag['pr'][1]
if dataFlag & 0x02:
item += " "
subFlag = outInt("Data subFlag: %s")
if subFlag == 0x80:
outStr("Data sub prefix: %s")
# It seams that data sub prefix content is ignored and there is a generated number for the whole block instead.
li += 1
ol = True
if dataFlag & 0x04: # chart
pass # ???
if dataFlag & 0x08: # reference
item += tag['df'][0] + outStr("Data definition: %s") + tag['df'][1]
if dataFlag & 0x10:
pass # ???
if dataFlag & 0x20: # phrase
phraseFlag1 = outInt("Data phraseFlag1: %s")
if phraseFlag1 & 0x01:
item += tag['ps'][0] + outStr("Data phrase short form: %s") + tag['ps'][1]
if phraseFlag1 & 0x02:
phraseCount = outInt("Data phraseCount: %s")
for i in range(0, phraseCount):
phraseComment = outInt("Data phrase prefix")
if phraseComment & 0x04:
item += tag['pc'][0] + outStr("Data phrase comment: %s") + tag['pc'][1]
item += tag['p1'][0] + outStr("Data phrase 1: %s") + tag['p1'][1]
item += tag['p2'][0] + outStr("Data phrase 2: %s") + tag['p2'][1]
if phraseFlag1 & 0x04:
phraseCount = outInt("Data phraseCount: %s")
for i in range(0, phraseCount):
phraseComment = outInt("Data phrase prefix")
if phraseComment & 0x04:
item += tag['pc'][0] + outStr("Data phrase 1: %s") + tag['pc'][1]
item += tag['pg'][0] + outStr("Data phrase comment: %s") + tag['pg'][1]
item += tag['p2'][0] + outStr("Data phrase 2: %s") + tag['p2'][1]
if phraseFlag1 & 0x08:
phraseCount = outInt("Data simple phraseCount: %s")
for i in range(0, phraseCount):
item += " "
item += tag['sp'][0] + outStr("Data simple phrase: %s") + tag['sp'][1]
if phraseFlag1 & 0x40:
item += tag['ps'][0] + outStr("Data phrase short form: %s") + tag['ps'][1]
# TODO: be careful in changing the rules, to have back compatibility!
if dataFlag & 0x40: # reference, related language
#0x01 synonym ?
#0x02 antonym ?
pass
if dataFlag & 0x80: # Phrase block
flags = [
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s")]
if flags == [0x80,0x80,0xF9,0xDF,0x9D,0x00,0x0B,0x01]:
result += "\\nphr: "
li = 1
ol = True
item += tag['b1'][0]+outStr("Data phrase 1: %s") + tag['b1'][1]
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
item += tag['ds'][0] + outStr("Data phrase 2: %s") + tag['ds'][1]
if flags == [0x80,0x80,0xF9,0xDF,0x9D,0x00,0x23,0x01]:
result += "\\nphr: "
li = 1
ol = True
item += tag['b1'][0]+outStr("Data phrase 1: %s") + tag['b1'][1]
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
item += tag['ds'][0] + outStr("Data phrase 2: %s") + tag['ds'][1]
if ol:
result += "\\n%d. %s" % (li, item)
else:
result += item
ok = True
while pos < len(stream):
ok = (out() == 0x00) and ok
if ok:
result += '\n'
return decode_tag_postprocessing(result)
################################################################
# MAIN
################################################################
f = open(FILENAME,'rb')
# DECODE HEADER OF FILE
copyright = unpack("<64s",f.read(64))[0]
a = unpack("<16L",f.read(64))
entryCount = a[4]
indexBaseCount = a[6]
indexOffsetCount = a[7]
pos1 = a[8]
indexPos = a[9]
bodyPos = a[10]
smallIndex = (a[3] == 2052)
# DECODE INDEX STRUCTURE OF FILE
index = []
f.seek(indexPos)
bases = unpack("<%sL" % indexBaseCount, f.read(indexBaseCount * 4))
if smallIndex: # In small dictionaries every base is used 4-times
bases4 = []
for i in bases:
bases4.extend([i,i,i,i])
bases = bases4
for b in bases:
offsets = unpack("<64H", f.read(64*2))
for o in offsets:
if len(index) < indexOffsetCount:
#print "Index %s: %s + %s + %s * 4 = %s" % (len(index), bodyPos, b, o, toBin(bodyPos + b + o * 4))
index.append(bodyPos + b + o * 4)
# DECODE RECORDS
if DEBUG:
# PRINTOUT DEBUG OF FIRST <DEBUGLIMIT> WRONG RECORDS:
for i in range(1,entryCount):
if not DEBUGALL:
DEBUG = False
s = decode(getRec(i))
if DEBUGHEADER:
# print s.split('\t')[0]
print s
if DEBUGLIMIT > 0 and not s.endswith('\n'):
DEBUG = True
print "-"*80
print "%s) at address %s" % (i, toBin(index[i]))
print
s = decode(getRec(i))
print s
DEBUGLIMIT -= 1
DEBUG = True
else:
# DECODE EACH RECORD AND PRINT IT IN FORMAT FOR stardict-editor <term>\t<definition>
for i in range(1,entryCount):
s = decode(getRec(i))
if s.endswith('\n'):
print s,
else:
print s
print "!!! RECORD STRUCTURE DECODING ERROR !!!"
print "Please run this script in DEBUG mode and repair DATA BLOCK(S) section in function decode()"
print "If you succeed with whole dictionary send report (name of the dictionary and source code of script) to slovniky@googlegroups.com"
break
| Python |
import sys, string
base = {}
for line in sys.stdin.readlines():
words = string.split(line[:-1], '\t')
if len(words) != 2:
print "Error!"
exit
if base.has_key(words[0]):
base[words[0]] += [words[1]]
else:
base[words[0]] = [words[1]]
keys = base.keys()
keys.sort()
for key in keys:
print key,'\t',
for val in base[key]:
print val,',',
print
| Python |
#!/usr/bin/env python
#
# hanzim2dict
#
# Original version written by Michael Robinson (robinson@netrinsics.com)
# Version 0.0.2
# Copyright 2004
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Usage: Run hanzim2dict in a directory containing the "zidianf.gb",
# "cidianf.gb", and "sanzidianf.gb" files from the Hanzi Master distribution
# (available at http://zakros.ucsd.edu/~arobert/hanzim.html). The output
# will be a StarDict dictionary in 2.4.2 format: hanzim.dict, hanzim.idx,
# and hanzim.ifo
#
# The dictionary and index files may be compressed as follows:
# $ gzip -9 hanzim.idx
# $ dictzip hanzim.dict
#
from string import split
from codecs import getdecoder, getencoder
from struct import pack
class Word:
def __init__(self, code, definition):
self.code = code
self.definition = [definition]
def add(self, definition):
self.definition.append(definition)
wordmap = {}
fromGB = getdecoder("GB2312")
toUTF = getencoder("utf_8")
file = open("zidianf.gb", "r")
lines = map(lambda x: split(x[:-1], '\t'), file.readlines())
for line in lines:
code = toUTF(fromGB(line[0])[0])[0]
pinyin = line[2]
definition = '<'+pinyin+'> '+line[3]+' ['+line[1]+']'
if wordmap.has_key(code):
wordmap[code].add(definition)
else:
wordmap[code] = Word(code, definition)
for filename in ("cidianf.gb", "sanzicidianf.gb"):
file = open(filename, "r")
lines = map(lambda x: split(x[:-1], '\t'), file.readlines())
for line in lines:
if len(line) < 2:
print len(line)
continue
code = toUTF(fromGB(line[0][:-2])[0])[0]
definition = line[1]+' ['+line[0][-1:]+']'
if wordmap.has_key(code):
wordmap[code].add(definition)
else:
wordmap[code] = Word(code, definition)
dict = open("hanzim.dict", "wb")
idx = open("hanzim.idx", "wb")
ifo = open("hanzim.ifo", "wb")
offset = 0
count = 0
keylen = 0
keys = list(wordmap.keys())
keys.sort()
for key in keys:
word = wordmap[key]
deftext = ""
multi = False
for d in word.definition:
if multi:
deftext += '\n'
deftext += d
multi = True
dict.write(deftext)
idx.write(key+'\0')
idx.write(pack("!I", offset))
idx.write(pack("!I", len(deftext)))
offset += len(deftext)
count += 1
keylen += len(key)
dict.close()
idx.close()
ifo.write("StarDict's dict ifo file\n")
ifo.write("version=2.4.2\n")
ifo.write("bookname=Hanzi Master 1.3\n")
ifo.write("wordcount="+str(count)+"\n")
ifo.write("idxfilesize="+str(keylen+(count*9))+"\n")
ifo.write("author=Adrian Robert\n")
ifo.write("email=arobert@cogsci.ucsd.edu\n")
ifo.write("website=http://zakros.ucsd.edu/~arobert/hanzim.html\n")
ifo.write("sametypesequence=m\n")
ifo.close()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, os, string, re, glob
import libxml2dom
fencoding = 'utf-8'
whattoextract = u'康熙字典'
#def TextInNode(node):
# result = u''
# for child in node.childNodes:
# if child.nodeType == child.TEXT_NODE:
# result += child.nodeValue
# else:
# result += TextInNode(child)
# return result
filelist = glob.glob('*.htm')
filenum = len(filelist)
num = 0
errorfiles = []
for filename in filelist:
num += 1
print >> sys.stderr, filename, num, 'of', filenum
try:
fp = open(filename, 'r')
doc = libxml2dom.parseString(fp.read(), html=1)
fp.close()
style = doc.getElementsByTagName("style")[0].textContent
style = re.search(r'(?s)\s*\.(\S+)\s*{\s*display:\s*none', style)
displaynone = style.group(1)
tabpages = doc.getElementsByTagName("div")
tabpages = filter(lambda s: s.getAttribute("class") == "tab-page", tabpages)
for tabpage in tabpages:
found = False
for node in tabpage.childNodes:
if node.nodeType == node.ELEMENT_NODE and node.name == 'h2':
if node.textContent == whattoextract:
found = True
break
if found:
spans = tabpage.getElementsByTagName("span")
for span in spans:
if span.getAttribute("class") == "kszi":
character = span.textContent
paragraphs = tabpage.getElementsByTagName("p")
thisitem = character + u'\t'
for paragraph in paragraphs:
if paragraph.getAttribute("class") <> displaynone:
#print TextInNode(paragraph).encode(fencoding)
text = paragraph.textContent
#text = filter(lambda s: not s in u' \t\r\n', text)
text = re.sub(r'\s+', r' ', text)
thisitem += text + u'\\n'
print thisitem.encode(fencoding)
except:
print >> sys.stderr, 'error occured'
errorfiles += [filename]
continue
if errorfiles:
print >> sys.stderr, 'Error files:', '\n'.join(errorfiles)
| Python |
import sys, string
for line in sys.stdin.readlines():
words = string.split(line[:-1], '\t')
muci = words[1]
sheng = words[2]
deng = words[3]
hu = words[4]
yunbu = words[5]
diao = words[6]
fanqie= words[7]
she = words[8]
chars = words[9]
romazi= words[10]
beizhu= words[12]
pinyin= words[13]
psyun = words[22]
if beizhu == '':
print "%s\t%s %s%s%s%s%s%s %sQIE PINYIN%s PSYUN%s\\n%s" % (romazi, muci, sheng, yunbu, she, hu, deng, diao, fanqie, pinyin, psyun, chars)
else:
print "%s\t%s %s%s%s%s%s%s %sQIE PINYIN%s PSYUN%s\\n%s\\n%s" % (romazi, muci, sheng, yunbu, she, hu, deng, diao, fanqie, pinyin, psyun, chars, beizhu)
| Python |
# This tool convert KangXiZiDian djvu files to tiff files.
# Download djvu files: http://bbs.dartmouth.edu/~fangq/KangXi/KangXi.tar
# Character page info: http://wenq.org/unihan/Unihan.txt as kIRGKangXi field.
# Character seek position in Unihan.txt http://wenq.org/unihan/unihandata.txt
# DjVuLibre package provides the ddjvu tool.
# The 410 page is bad, but it should be blank page in fact. so just remove 410.tif
import os
if __name__ == "__main__":
os.system("mkdir tif")
pages = range(1, 1683+1)
for i in pages:
page = str(i)
print(page)
os.system("ddjvu -format=tiff -page="+ page + " -scale=100 -quality=150 KangXiZiDian.djvu"+ " tif/" + page + ".tif")
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gimpfu import *
import os
def prepare_image(image, visibleLayers, size, numColors = None):
"""prepare custom image
image - image object to change
size - size of the image in pixels
visibleLayers - a list of layers that must be visible
"""
for layer in image.layers:
if layer.name in visibleLayers:
layer.visible = True
else:
image.remove_layer(layer)
gimp.pdb.gimp_image_merge_visible_layers(image, CLIP_TO_IMAGE)
drawable=gimp.pdb.gimp_image_get_active_layer(image)
gimp.pdb.gimp_layer_scale_full(drawable, size, size, False, INTERPOLATION_CUBIC)
"""
image 670x670, all layers have the same dimensions
after applying gimp_image_scale_full functions with size=32,
image.width = 32, image.height = 32
layer.width = 27, layer.height = 31
gimp.pdb.gimp_image_scale_full(image, size, size, INTERPOLATION_CUBIC)
"""
#print 'width = {0}, height = {1}'.format(drawable.width, drawable.height)
#print 'width = {0}, height = {1}'.format(image.width, image.height)
if numColors != None:
gimp.pdb.gimp_image_convert_indexed(image, NO_DITHER, MAKE_PALETTE, numColors, False, False, "")
def save_image(image, dstFilePath):
dirPath = os.path.dirname(dstFilePath)
if not os.path.exists(dirPath):
os.makedirs(dirPath)
drawable=gimp.pdb.gimp_image_get_active_layer(image)
gimp.pdb.gimp_file_save(image, drawable, dstFilePath, dstFilePath)
gimp.delete(drawable)
gimp.delete(image)
def create_icon(origImage, visibleLayers, props):
"""visibleLayers - a list of layers that must be visible
props - tuple of image properties in format ((size, bpp), ...)
where:
size - size of the icon in pixels,
bpp - bits per pixel, None to leave by default
return value - new image
"""
iconImage = None
i = 0
for prop in props:
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, visibleLayers, prop[0], prop[1])
image.layers[0].name = 's{0}'.format(i)
if iconImage == None:
iconImage = image
else:
newLayer = gimp.pdb.gimp_layer_new_from_drawable(image.layers[0], iconImage)
gimp.pdb.gimp_image_add_layer(iconImage, newLayer, -1)
gimp.delete(image)
i += 1
return iconImage
def stardict_images(srcFilePath, rootDir):
if not rootDir:
# srcFilePath = rootDir + "/pixmaps/stardict.xcf"
if not srcFilePath.endswith("/pixmaps/stardict.xcf"):
print 'Unable to automatically detect StarDict root directory. Specify non-blank root directory parameter.'
return
dstDirPath = os.path.dirname(srcFilePath)
dstDirPath = os.path.dirname(dstDirPath)
else:
dstDirPath = rootDir
"""
print 'srcFilePath = {0}'.format(srcFilePath)
print 'rootDir = {0}'.format(rootDir)
print 'dstDirPath = {0}'.format(dstDirPath)
"""
dstStarDict_s128_FilePath=os.path.join(dstDirPath, "pixmaps/stardict_128.png")
dstStarDict_s32_FilePath=os.path.join(dstDirPath, "pixmaps/stardict_32.png")
dstStarDict_s16_FilePath=os.path.join(dstDirPath, "pixmaps/stardict_16.png")
dstStarDict_FilePath=os.path.join(dstDirPath, "pixmaps/stardict.png")
dstStarDictEditor_s128_FilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor_128.png")
dstStarDictEditor_s32_FilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor_32.png")
dstStarDictEditor_s16_FilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor_16.png")
dstStarDictIconFilePath=os.path.join(dstDirPath, "pixmaps/stardict.ico")
dstStarDictEditorIconFilePath=os.path.join(dstDirPath, "pixmaps/stardict-editor.ico")
dstStarDictUninstIconFilePath=os.path.join(dstDirPath, "pixmaps/stardict-uninst.ico")
dstDockletNormalFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_normal.png")
dstDockletScanFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_scan.png")
dstDockletStopFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_stop.png")
dstDockletGPENormalFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_gpe_normal.png")
dstDockletGPEScanFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_gpe_scan.png")
dstDockletGPEStopFilePath=os.path.join(dstDirPath, "src/pixmaps/docklet_gpe_stop.png")
dstWordPickFilePath=os.path.join(dstDirPath, "src/win32/acrobat/win32/wordPick.bmp")
origImage=gimp.pdb.gimp_file_load(srcFilePath, srcFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 128)
save_image(image, dstStarDict_s128_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 32)
save_image(image, dstStarDict_s32_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 16)
save_image(image, dstStarDict_s16_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 64)
save_image(image, dstStarDict_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "edit"), 128)
save_image(image, dstStarDictEditor_s128_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "edit"), 32)
save_image(image, dstStarDictEditor_s32_FilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "edit"), 16)
save_image(image, dstStarDictEditor_s16_FilePath)
image = create_icon(origImage, ("book1", "book2"),
((16, None), (32, None), (48, None), (16, 256), (32, 256), (48, 256), (256, None))
)
save_image(image, dstStarDictIconFilePath)
image = create_icon(origImage, ("book1", "book2", "edit"),
((16, None), (32, None), (48, None), (16, 256), (32, 256), (48, 256), (256, None))
)
save_image(image, dstStarDictEditorIconFilePath)
image = create_icon(origImage, ("book1", "book2", "cross"),
((16, None), (32, None), (48, None), (16, 256), (32, 256), (48, 256), (256, None))
)
save_image(image, dstStarDictUninstIconFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 32)
save_image(image, dstDockletNormalFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "search"), 32)
save_image(image, dstDockletScanFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "stop"), 32)
save_image(image, dstDockletStopFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 16)
save_image(image, dstDockletGPENormalFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "search"), 16)
save_image(image, dstDockletGPEScanFilePath)
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2", "stop"), 16)
save_image(image, dstDockletGPEStopFilePath)
# See AVToolButtonNew function in PDF API Reference
# Recommended icon size is 18x18, but it looks too small...
image = gimp.pdb.gimp_image_duplicate(origImage)
prepare_image(image, ("book1", "book2"), 22)
gimp.set_background(192, 192, 192)
gimp.pdb.gimp_layer_flatten(image.layers[0])
save_image(image, dstWordPickFilePath)
register(
"stardict_images",
"Create images for StarDict",
"Create images for StarDict",
"StarDict team",
"GPL",
"Mar 2011",
"<Toolbox>/Tools/stardict images",
"",
[
(PF_FILE, "src_image", "Multilayer image used as source for all other images in StarDict, "
+ "normally that is pixmaps/stardict.xcf is StarDict source tree.", None),
(PF_DIRNAME, "stardict_dir", "Root directory of StarDict source tree. New images will be saved here.", None)
],
[],
stardict_images)
main()
| Python |
#!/usr/bin/python
# WinVNKey Hannom Database to Stardict dictionary source Conversion Tool
# coded by wesnoth@ustc on 070804
# http://winvnkey.sourceforge.net
import sys, os, string, types, pprint
infileencoding = 'utf-16-le'
outfileencoding = 'utf-8'
def showhelp():
print "Usage: %s filename" % sys.argv[0]
def ishantu(str):
if len(str) > 0 and ord(str[0]) > 0x2e80:
return True
else:
return False
def mysplit(line):
status = 0 # 0: normal, 1: quote
i = 0
line = line.lstrip()
linelen = len(line)
while i < linelen:
if status == 0 and line[i].isspace():
break
if line[i] == u'"':
status = 1 - status
i += 1
#print 'mysplit: i=%d, line=%s' % (i, `line`)
if i == 0:
return []
else:
line = [line[:i], line[i:].strip()]
if line[1] == u'':
return [line[0]]
else:
return line
if __name__ == '__main__':
if len(sys.argv) <> 2:
showhelp()
else:
fp = open(sys.argv[1], 'r')
print 'Reading file...'
lines = unicode(fp.read(), infileencoding).split(u'\n')
lineno = 0
hugedict = {}
print 'Generating Han-Viet dict...'
for line in lines:
lineno += 1
if line.endswith(u'\r'):
line = line[:-1]
if line.startswith(u'\ufeff'):
line = line[1:]
ind = line.find(u'#')
if ind >= 0:
line = line[:ind]
line = mysplit(line)
if len(line) == 0:
continue
elif len(line) == 1:
continue # ignore this incomplete line
if line[0].startswith(u'"') and line[0].endswith(u'"'):
line[0] = line[0][1:-1]
if line[0].startswith(u'U+') or line[0].startswith(u'u+'):
line[0] = unichr(int(line[0][2:], 16))
if not ishantu(line[0]):
continue # invalid Han character
#print 'error occurred on line %d: %s' % (lineno, `line`)
if line[1].startswith(u'"') and line[1].endswith(u'"'):
line[1] = line[1][1:-1]
line[1] = filter(None, map(string.strip, line[1].split(u',')))
#hugedict[line[0]] = hugedict.get(line[0], []) + line[1]
for item in line[1]:
if not hugedict.has_key(line[0]):
hugedict[line[0]] = [item]
elif not item in hugedict[line[0]]:
hugedict[line[0]] += [item]
#print lineno, `line`
#for hantu, quocngu in hugedict.iteritems():
# print hantu.encode('utf-8'), ':',
# for viettu in quocngu:
# print viettu.encode('utf-8'), ',',
# print
fp.close()
print 'Generating Viet-Han dict...'
dicthuge = {}
for hantu, quocngu in hugedict.iteritems():
for viettu in quocngu:
if not dicthuge.has_key(viettu):
dicthuge[viettu] = [hantu]
elif not hantu in dicthuge[viettu]:
dicthuge[viettu] += [hantu]
print 'Writing Han-Viet dict...'
gp = open('hanviet.txt', 'w')
for hantu, quocngu in hugedict.iteritems():
gp.write(hantu.encode('utf-8'))
gp.write('\t')
gp.write((u', '.join(quocngu)).encode('utf-8'))
gp.write('\n')
gp.close()
print 'Writing Viet-Han dict...'
gp = open('viethan.txt', 'w')
for quocngu,hantu in dicthuge.iteritems():
gp.write(quocngu.encode('utf-8'))
gp.write('\t')
gp.write((u' '.join(hantu)).encode('utf-8'))
gp.write('\n')
gp.close()
| Python |
#!/usr/bin/env python
#
# uyghur2dict
# By Abdisalam (anatilim@gmail.com), inspired by Michael Robinson's hanzim2dict converter.
#
# Original version, hanzim2dict, written by Michael Robinson (robinson@netrinsics.com)
# Version 0.0.2
# Copyright 2004
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Usage: Run hanzim2dict in a directory containing the "zidianf.gb",
# "cidianf.gb", and "sanzidianf.gb" files from the Hanzi Master distribution
# (available at http://zakros.ucsd.edu/~arobert/hanzim.html). The output
# will be a StarDict dictionary in 2.4.2 format: hanzim.dict, hanzim.idx,
# and hanzim.ifo
#
# The dictionary and index files may be compressed as follows:
# $ gzip -9 hanzim.idx
# $ dictzip hanzim.dict
#
from string import split
from struct import pack
class Word:
def __init__(self, code, definition):
self.code = code
self.definition = [definition]
def add(self, definition):
self.definition.append(definition)
wordmap = {}
file = open("ChineseUyghurStarDict.txt", "r")
lines = map(lambda x: split(x[:-1], '\t\t'), file.readlines())
for line in lines:
code = line[0]
definition = line[1]
if wordmap.has_key(code):
wordmap[code].add(definition)
else:
wordmap[code] = Word(code, definition)
dict = open("Anatilim_Chinese_Uyghur.dict", "wb")
idx = open("Anatilim_Chinese_Uyghur.idx", "wb")
ifo = open("Anatilim_Chinese_Uyghur.ifo", "wb")
offset = 0
count = 0
keylen = 0
keys = list(wordmap.keys())
keys.sort()
for key in keys:
word = wordmap[key]
deftext = ""
for d in word.definition:
deftext=d
deftext += '\0'
dict.write(deftext)
idx.write(key+'\0')
idx.write(pack("!I", offset))
idx.write(pack("!I", len(deftext)))
offset += len(deftext)
count += 1
keylen += len(key)
dict.close()
idx.close()
ifo.write("StarDict's dict ifo file\n")
ifo.write("version=2.4.2\n")
ifo.write("bookname=Anatilim 《汉维词典》-- Anatilim Chinese Uyghur Dictionary\n")
ifo.write("wordcount="+str(count)+"\n")
ifo.write("idxfilesize="+str(keylen+(count*9))+"\n")
ifo.write("author=Abdisalam\n")
ifo.write("email=anatilim@gmail.com\n")
ifo.write("description=感谢新疆维吾尔自治区语委会、新疆青少年出版社为我们提供《汉维词典》的词库\n")
ifo.write("sametypesequence=m\n")
ifo.close() | Python |
#!/usr/bin/env python2
#
# converts XML JMDict to Stardict idx/dict format
# JMDict website: http://www.csse.monash.edu.au/~jwb/j_jmdict.html
#
# Date: 3rd July 2003
# Author: Alastair Tse <acnt2@cam.ac.uk>
# License: BSD (http://www.opensource.org/licenses/bsd-license.php)
#
# Usage: jm2stardict expects the file JMdict.gz in the current working
# directory and outputs to files jmdict-ja-en and jmdict-en-ja
#
# To compress the resulting files, use:
#
# gzip -9 jmdict-en-ja.idx
# gzip -9 jmdict-ja-en.idx
# dictzip jmdict-en-ja.dict
# dictzip jmdict-ja-en.dict
#
# note - dictzip is from www.dict.org
#
import xml.sax
from xml.sax.handler import *
import gzip
import struct, sys, string, codecs,os
def text(nodes):
label = ""
textnodes = filter(lambda x: x.nodeName == "#text", nodes)
for t in textnodes:
label += t.data
return label
def strcasecmp(a, b):
result = 0
# to ascii
#str_a = string.join(filter(lambda x: ord(x) < 128, a[0]), "").lower()
#str_b = string.join(filter(lambda x: ord(x) < 128, b[0]), "").lower()
#result = cmp(str_a, str_b)
# if result == 0:
result = cmp(a[0].lower() , b[0].lower())
return result
def merge_dup(list):
newlist = []
lastkey = ""
for x in list:
if x[0] == lastkey:
newlist[-1] = (newlist[-1][0], newlist[-1][1] + "\n" + x[1])
else:
newlist.append(x)
lastkey = x[0]
return newlist
class JMDictHandler(ContentHandler):
def __init__(self):
self.mapping = []
self.state = ""
self.buffer = ""
def startElement(self, name, attrs):
if name == "entry":
self.kanji = []
self.chars = []
self.gloss = []
self.state = ""
self.buffer = ""
elif name == "keb":
self.state = "keb"
elif name == "reb":
self.state = "reb"
elif name == "gloss" and not attrs:
self.state = "gloss"
elif name == "xref":
self.state = "xref"
def endElement(self, name):
if name == "entry":
self.mapping.append((self.kanji, self.chars, self.gloss))
elif name == "keb":
self.kanji.append(self.buffer)
elif name == "reb":
self.chars.append(self.buffer)
elif name == "gloss" and self.buffer:
self.gloss.append(self.buffer)
elif name == "xref":
self.gloss.append(self.buffer)
self.buffer = ""
self.state = ""
def characters(self, ch):
if self.state in ["keb", "reb", "gloss", "xref"]:
self.buffer = self.buffer + ch
def map_to_file(dictmap, filename):
dict = open(filename + ".dict","wb")
idx = open(filename + ".idx","wb")
offset = 0
idx.write("StarDict's idx file\nversion=2.1.0\n");
idx.write("bookname=" + filename + "\nauthor=Jim Breen\nemail=j.breen@csse.monash.edu.au\nwebsite=http://www.csse.monash.edu.au/~jwb/j_jmdict.html\ndescription=Convert to stardict by Alastair Tse <liquidx@gentoo.org>, http://www-lce.eng.cam.ac.uk/~acnt2/code/\ndate=2003.07.01\n")
idx.write("sametypesequence=m\n")
idx.write("BEGIN:\n")
idx.write(struct.pack("!I",len(dictmap)))
for k,v in dictmap:
k_utf8 = k.encode("utf-8")
v_utf8 = v.encode("utf-8")
idx.write(k_utf8 + "\0")
idx.write(struct.pack("!I",offset))
idx.write(struct.pack("!I",len(v_utf8)))
offset += len(v_utf8)
dict.write(v_utf8)
dict.close()
idx.close()
if __name__ == "__main__":
print "opening xml dict .."
f = gzip.open("JMdict.gz")
#f = open("jmdict_sample.xml")
print "parsing xml file .."
parser = xml.sax.make_parser()
handler = JMDictHandler()
parser.setContentHandler(handler)
parser.parse(f)
f.close()
print "creating dictionary .."
# create a japanese -> english mappings
jap_to_eng = []
for kanji,chars,gloss in handler.mapping:
for k in kanji:
key = k
value = string.join(chars + gloss, "\n")
jap_to_eng.append((key,value))
for c in chars:
key = c
value = string.join(kanji + gloss, "\n")
jap_to_eng.append((key,value))
eng_to_jap = []
for kanji,chars,gloss in handler.mapping:
for k in gloss:
key = k
value = string.join(kanji + chars, "\n")
eng_to_jap.append((key,value))
print "sorting dictionary .."
jap_to_eng.sort(strcasecmp)
eng_to_jap.sort(strcasecmp)
print "merging and pruning dups.."
jap_to_eng = merge_dup(jap_to_eng)
eng_to_jap = merge_dup(eng_to_jap)
print "writing to files.."
# create dict and idx file
map_to_file(jap_to_eng, "jmdict-ja-en")
map_to_file(eng_to_jap, "jmdict-en-ja")
| Python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Script for decoding Lingea Dictionary (.trd) file
# Result is <header>\t<definition> file, convertable easily
# by stardict-editor from package stardict-tools into native
# Stardict dictionary (stardict.sf.net and www.stardict.org)
#
# Copyright (C) 2007 - Klokan Petr Přidal (www.klokan.cz)
#
# Based on script CobuildConv.rb by Nomad
# http://hp.vector.co.jp/authors/VA005784/cobuild/cobuildconv.html
#
# Version history:
# 0.4 (30.10.2007) Patch by Petr Dlouhy, optional HTML generation
# 0.3 (28.10.2007) Patch by Petr Dlouhy, cleanup, bugfix. More dictionaries.
# 0.2 (19.7.2007) Changes, documentation, first 100% dictionary
# 0.1 (20.5.2006) Initial version based on Nomad specs
#
# Supported dictionaries:
# - Lingea Německý Kapesní slovník
# - Lingea Anglický Kapesní slovník
# - Lingea 2002 series (theoretically)
#
# Modified by:
# - Petr Dlouhy (petr.dlouhy | email.cz)
# Generalization of data block rules, sampleFlag 0x04, sound out fix, data phrase prefix with comment (0x04)
# HTML output, debugging patch, options on command line
#
# <write your name here>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
# VERSION
VERSION = "0.4"
import getopt, sys
def usage():
print "Lingea Dictionary Decoder"
print "-------------------------"
print "Version: %s" % VERSION
print "Copyright (C) 2007 - Klokan Petr Pridal, Petr Dlouhy"
print
print "Usage: python lingea-trd-decoder.py DICTIONARY.trd > DICTIONARY.tab"
print "Result convertion by stardict-tools: /usr/lib/stardict-tools/tabfile"
print
print " -o <num> --out-style : Output style"
print " 0 no tags"
print " 1 \\n tags"
print " 2 html tags"
print " -h --help : Print this message"
print " -d --debug : Degub"
print " -r --debug-header : Degub - print headers"
print " -a --debug-all : Degub - print all records"
print " -l --debug-limit : Degub limit"
print
print "For HTML support in StarDict dictionary .ifo has to contain:"
print "sametypesequence=g"
print "!!! Change the .ifo file after generation by tabfile !!!"
print
try:
opts, args = getopt.getopt(sys.argv[1:], "hdo:ral:", ["help", "debug", "out-style=", "debug-header", "debug-all", "debug-limit="])
except getopt.GetoptError:
usage()
print "ERROR: Bad option"
sys.exit(2)
import locale
DEBUG = False
OUTSTYLE = 2
DEBUGHEADER = False
DEBUGALL = False
DEBUGLIMIT = 1
for o, a in opts:
if o in ("-d", "-debug"):
# DEBUGING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
DEBUG = True
if o in ("-o", "--out-style"):
# output style
OUTSTYLE = locale.atoi(a)
if OUTSTYLE > 2:
usage()
print "ERROR: Output style not specified"
if o in ("-r", "--debug-header"):
# If DEBUG and DEBUGHEADER, then print just all header records
DEBUGHEADER = True
if o in ("-a", "--debug-all"):
# If DEBUG and DEBUGALL then print debug info for all records
DEBUGALL = True
if o in ("-h", "--help"):
usage()
sys.exit(0)
if o in ("-l", "--debug-limit"):
# Number of wrong records for printing to stop during debugging
DEBUGLIMIT = locale.atoi(a)
# FILENAME is a first parameter on the commandline now
if len(args) == 1:
FILENAME = args[0]
else:
usage()
print "ERROR: You have to specify .trd file to decode"
sys.exit(2)
from struct import *
import re
alpha = ['\x00', 'a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z','#AL27#','#AL28#','#AL29#',
'#AL30#','#AL31#', ' ', '.', '<', '>', ',', ';', '-', '#AL39#',
'#GRAVE#', '#ACUTE#', '#CIRC#', '#TILDE#', '#UML#', '#AL45#', '#AL46#', '#CARON#', '#AL48#', '#CEDIL#',
'#AL50#', '#AL51#', '#GREEK#', '#AL53#', '#AL54#', '#AL55#', '#AL56#', '#AL57#', '#AL58#', '#SYMBOL#',
'#AL60#', '#UPCASE#', '#SPECIAL#', '#UNICODE#'] # 4 bytes after unicode
upcase = ['#UP0#','#UP1#','#UP2#','#UP3#','#UP4#','#UP5#','#UP6#','#UP7#','#UP8#','#UP9#',
'#UP10#','#UP11#','#UP12#','#UP13#','#UP14#','#UP15#','#UP16#','#UP17#','#UP18#','#UP19#',
'#UP20#','#UP21#','#UP22#','#UP23#','#UP24#','#UP25#','#UP26#','#UP27#','#UP28#','#UP29#',
'#UP30#','#UP31#','A','B','C','D','E','F','G','H',
'I','J','K','L','M','N','O','P','Q','R',
'S','T','U','V','W','X','Y','Z','#UP58#','#UP59#',
'#UP60#','#UP61#','#UP62#','#UP63#']
upcase_pron = ['#pr0#', '#pr1#','#pr2#','#pr3#','#pr4#','#pr5#','#pr6#','#pr7#','#pr8#','#pr9#',
'#pr10#', '#pr11#','#pr12#','#pr13#','#pr14#','#pr15#','#pr16#','#pr17#','#pr18#','#pr19#',
'#pr20#', '#pr21#','#pr22#','#pr23#','#pr24#','#pr25#','#pr26#','#pr27#','#pr28#','#pr29#',
'#pr30#', '#pr31#','ɑ','#pr33#','ʧ','ð','ə','ɜ','#pr38#','æ',
'ɪ', 'ɭ','#pr42#','ŋ','#pr44#','ɳ','ɔ','#pr47#','ɒ','ɽ',
'ʃ', 'θ','ʊ','ʌ','#pr54#','#pr55#','#pr56#','ʒ','#pr58#','#pr59#',
'#pr60#', '#pr61#','#pr62#','#pr63#']
symbol = ['#SY0#', '#SY1#','#SY2#','#SY3#','§','#SY5#','#SY6#','#SY7#','#SY8#','#SY9#',
'#SY10#', '#SY11#','#SY12#','#SY13#','#SY14#','™','#SY16#','#SY17#','¢','£',
'#SY20#', '#SY21#','#SY22#','#SY23#','©','#SY25#','#SY26#','#SY27#','®','°',
'#SY30#', '²','³','#SY33#','#SY34#','#SY35#','¹','#SY37#','#SY38#','#SY39#',
'½', '#SY41#','#SY42#','×','÷','#SY45#','#SY46#','#SY47#','#SY48#','#SY49#',
'#SY50#', '#SY51#','#SY52#','#SY53#','#SY54#','#SY55#','#SY56#','#SY57#','#SY58#','#SY59#',
'#SY60#', '#SY61#','#SY62#','#SY63#']
special = ['#SP0#', '!','"','#','$','%','&','\'','(',')',
'*', '+','#SP12#','#SP13#','#SP14#','/','0','1','2','3',
'4', '5','6','7','8','9',':',';','<','=',
'>', '?','@','[','\\',']','^','_','`','{',
'|', '}','~','#SP43#','#SP44#','#SP45#','#SP46#','#SP47#','#SP48#','#SP49#',
'#SP50#', '#SP51#','#SP52#','#SP53#','#SP54#','#SP55#','#SP56#','#SP57#','#SP58#','#SP59#',
'#SP60#', '#SP61#','#SP62#','#SP63#']
wordclass = ('#0#','n:','adj:','pron:','#4#','v:','adv:','prep:','#8#','#9#',
'intr:','phr:','#12#','#13#','#14#','#15#','#16#','#17#','#18#','#19#',
'#20#','#21#','#22#','#23#','#24#','#25#','#26#','#27#','#28#','#29#',
'#30#','#31#')
if OUTSTYLE == 0:
tag = {
'db':('' ,''), #Data begining
'rn':('' ,'\t'), #Record name
'va':('' ,' '), #Header variant
'wc':('(' ,')'), #WordClass
'pa':('' ,' '), #Header parts
'fo':('(' ,') '), #Header forms
'on':('(' ,')' ), #Header origin note
'pr':('[' ,']'), #Header pronunciation
'dv':('{' ,'} '), #Header dataVariant
'sa':('`' ,'`' ), #Data sample
'sw':('' ,''), #Data sample wordclass; is no printed by Lingea
'do':('`' ,'`' ), #Data origin note
'df':('' ,' '), #Data definition
'ps':('"' ,'" '), #Data phrase short form
'pg':('"' ,' = '), #Data phrase green
'pc':('`' ,'`'), #Data phrase comment; this comment is not printed by Lingea), but it seems useful
'p1':('"' ,' = '), #Data phrase 1
'p2':('' ,'" ' ), #Data phrase 2
'sp':('"' ,' = ' ),#Data simple phrase
'b1':('"' ,' = '), #Data phrase (block) 1
'b2':('" ' ,''), #Data phrase (block) 2
}
if OUTSTYLE == 1:
tag = {
'db':('•' ,''), #Data begining
'rn':('' ,'\t'), #Record name
'va':('' ,' '), #Header variant
'wc':('' ,'\\n'), #WordClass
'pa':('' ,':\\n'), #Header parts
'fo':('(' ,') '), #Header forms
'on':('(' ,')\\n' ), #Header origin note
'pr':('[' ,']\\n'), #Header pronunciation
'dv':('{' ,'} '), #Header dataVariant
'sa':(' ' ,'\\n' ), #Data sample
'sw':('' ,''), #Data sample wordclass; is not printed by Lingea
'do':(' ' ,' ' ), #Data origin note
'df':(' ' ,'\\n'), #Data definition
'ps':(' ' ,'\\n'), #Data phrase short form
'pg':(' ' ,' '), #Data phrase green
'pc':(' ' ,' '), #Data phrase comment; this comment is not printed by Lingea), but it seems useful
'p1':(' ' ,' '), #Data phrase 1
'p2':(' ' ,'\\n' ), #Data phrase 2
'sp':('' ,'\\n' ), #Data simple phrase
'b1':('"' ,' = '), #Data phrase (block) 1
'b2':('" ' ,''), #Data phrase (block) 2
}
if OUTSTYLE == 2:
tag = {
'db':('•' ,''), #Data begining
'rn':('' ,'\t'), #Record name
'va':('' ,' '), #Header variant
'wc':('<span size="larger" color="darkred" weight="bold">','</span>\\n'), #WordClass
'pa':('<span size="larger" color="darkred" weight="bold">',':</span>\\n'), #Header parts
'fo':('(' ,') '), #Header forms
'on':('<span color="blue">(' ,')</span>\\n' ), #Header origin note
'pr':('[' ,']\\n'), #Header pronunciation
'dv':('{' ,'} '), #Header dataVariant
'sa':(' <span color="darkred" weight="bold">' ,'</span>\\n' ), #Data sample
'sw':('' ,''), #Data sample wordclass; is not printed by Lingea
'do':(' <span color="darkred" weight="bold">' ,'</span> ' ), #Data origin note
'df':(' <span weight="bold">' ,'</span>\\n'), #Data definition
'ps':(' <span color="dimgray" weight="bold">' ,'</span>\\n'), #Data phrase short form
'pg':(' <span color="darkgreen" style="italic">' ,'</span> '), #Data phrase green
'pc':(' <span color="darkgreen" style="italic">' ,'</span> '), #Data phrase comment; this comment is not printed by Lingea), but it seems useful
'p1':(' <span color="dimgray" style="italic">' ,'</span> '), #Data phrase 1
'p2':(' ' ,'\\n' ), #Data phrase 2
'sp':('<span color="cyan">' ,'</span>\\n' ), #Data simple phrase
'b1':('"' ,' = '), #Data phrase (block) 1
'b2':('" ' ,''), #Data phrase (block) 2
}
# Print color debug functions
purple = lambda c: '\x1b[1;35m'+c+'\x1b[0m'
blue = lambda c: '\x1b[1;34m'+c+'\x1b[0m'
cyan = lambda c: '\x1b[36m'+c+'\x1b[0m'
gray = lambda c: '\x1b[1m'+c+'\x1b[0m'
def getRec(n):
"""Get data stream for record of given number"""
if n >= 0 and n < entryCount:
f.seek(index[n])
return f.read(index[n+1] - index[n])
else:
return ''
def decode_alpha( stream, nullstop=True):
"""Decode 6-bit encoding data stream from the begining untit first NULL"""
offset = 0
triple = 0
result = []
while triple < len( stream ):
if offset % 4 == 0:
c = stream[triple] >> 2
triple += 1
if offset % 4 == 1:
c = (stream[triple-1] & 3) << 4 | stream[triple] >> 4
triple += 1
if offset % 4 == 2:
c = (stream[triple-1] & 15) << 2 | (stream[triple] & 192) >> 6
triple += 1
if offset % 4 == 3:
c = stream[triple-1] & 63
if c == 0 and nullstop:
break
offset += 1
# TODO: ENCODE UNICODE 4 BYTE STREAM!!! and but it after #UNICODE# as unichr()
result.append(c)
return decode_alpha_postprocessing(result), triple - 1
def decode_alpha_postprocessing( input ):
"""Lowlevel alphabet decoding postprocessing, combines tuples into one character"""
result = ""
input.extend([0x00]*5)
# UPCASE, UPCASE_PRON, SYMBOL, SPECIAL
skip = False
for i in range(0,len(input)-1):
if skip:
skip = False
continue
bc = input[i]
c = alpha[bc]
bc1 = input[i+1]
c1 = alpha[bc1]
if bc < 40:
result += c
else:
if c == "#GRAVE#":
if c1 == 'a': result += 'à'
else: result += '#GRAVE%s#' % c1
elif c == "#UML#":
if c1 == 'o': result += 'ö'
elif c1 == 'u': result += 'ü'
elif c1 == 'a': result += 'ä'
elif c1 == ' ': result += 'Ä'
elif c1 == '#AL46#': result += 'Ö'
elif c1 == '#GREEK#': result += 'Ü'
else: result += '#UML%s#' % c1
elif c == "#ACUTE#":
if c1 == 'a': result += 'á'
elif c1 == 'e': result += 'é'
elif c1 == 'i': result += 'í'
elif c1 == 'o': result += 'ó'
elif c1 == 'u': result += 'ú'
elif c1 == 'y': result += 'ý'
elif c1 == ' ': result += 'Á'
elif c1 == '#GRAVE#': result += 'Í'
else: result += '#ACUTE%s#' % c1
elif c == "#CARON#":
if c1 == 'r': result += 'ř'
elif c1 == 'c': result += 'č'
elif c1 == 's': result += 'š'
elif c1 == 'z': result += 'ž'
elif c1 == 'e': result += 'ě'
elif c1 == 'd': result += 'ď'
elif c1 == 't': result += 'ť'
elif c1 == 'a': result += 'å'
elif c1 == 'u': result += 'ů'
elif c1 == 'n': result += 'ň'
elif c1 == '<': result += 'Č'
elif c1 == '#CEDIL#': result += 'Ř'
elif c1 == '#AL50#': result += 'Š'
elif c1 == '#AL57#': result += 'Ž'
else: result += '#CARON%s#' % c1
elif c == "#UPCASE#":
result += upcase[bc1]
elif c == "#SYMBOL#":
result += symbol[bc1]
elif c == "#AL51#":
if c1 == 's': result += 'ß'
elif c == "#AL48#":
result += "#AL48#%s" % c1
elif c == "#SPECIAL#":
result += special[bc1]
elif c == "#UNICODE#":
result += '#UNICODE%s#' % bc1
elif c == "#CIRC#":
if c1 == 'a': result += 'â'
else: result += '#CARON%s#' % c1
else:
result += '%sX%s#' % (c[:-1], bc1)
skip = True
return result
def pronunciation_encode(s):
"""Encode pronunciation upcase symbols into IPA symbols"""
for i in range(0, 64):
s = s.replace(upcase[i], upcase_pron[i])
return s
re_d = re.compile(r'<d(.*?)>')
re_w = re.compile(r'<w(.*?)>')
re_y = re.compile(r'<y(.*?)>')
re_c = re.compile(r'<c(.*?)>')
def decode_tag_postprocessing(input):
"""Decode and replace tags used in lingea dictionaries; decode internal tags"""
s = input
# General information in http://www.david-zbiral.cz/El-slovniky-plnaverze.htm#_Toc151656799
# TODO: Better output handling
if OUTSTYLE == 0:
# ?? <d...>
s = re_d.sub(r'(\1)',s)
# ?? <w...>
s = re_w.sub(r'(\1)',s)
# ?? <y...>
s = re_y.sub(r'(\1)',s)
# ?? <c...>
s = re_c.sub(r'(\1)',s)
# ...
if OUTSTYLE == 1:
# ?? <d...>
s = re_d.sub(r'(\1)',s)
# ?? <w...>
s = re_w.sub(r'(\1)',s)
# ?? <y...>
s = re_y.sub(r'(\1)',s)
# ?? <c...>
s = re_c.sub(r'(\1)',s)
# ...
if OUTSTYLE == 2:
# ?? <d...>
s = re_d.sub(r'<span size="small" color="blue">(\1)</span>',s)
# ?? <w...>
s = re_w.sub(r'<span size="small" color="blue" style="italic">\1</span>',s)
# ?? <y...>
s = re_y.sub(r'<span size="small" color="blue" style="italic">\1</span>',s)
# ?? <c...>
s = re_c.sub(r'<span size="small" color="blue" style="italic">\1</span>',s)
# ...
return s
def toBin( b ):
"""Prettify debug output format: hex(bin)dec"""
original = b
r = 0;
i = 1;
while b > 0:
if b & 0x01 != 0: r += i
i *= 10
b = b >> 1
return "0x%02X(%08d)%03d" % (original, r, original)
def out( comment = "", skip = False):
"""Read next byte or string (with skip=True) and output DEBUG info"""
global bs, pos
s, triple = decode_alpha(bs[pos:])
s = s.split('\x00')[0] # give me string until first NULL
if (comment.find('%') != -1):
if skip:
comment = comment % s
else:
comment = comment % bs[pos]
if DEBUG: print "%03d %s %s | %s | %03d" % (pos, toBin(bs[pos]),comment, s, (triple + pos))
if skip:
pos += triple + 1
return s.replace('`','') # Remove '`' character from words
else:
pos += 1
return bs[pos-1]
outInt = lambda c: out(c)
outStr = lambda c: out(c, True)
def decode(stream):
"""Decode byte stream of one record, return decoded string with formatting in utf"""
result = ""
global bs, pos
# stream - data byte stream for one record
bs = unpack("<%sB" % len(stream), stream)
# bs - list of bytes from stream
pos = 0
itemCount = outInt("ItemCount: %s") # Number of blocks in the record
mainFlag = outInt("MainFlag: %s")
# HEADER BLOCK
# ------------
if mainFlag & 0x01:
headerFlag = outInt("HeaderFlag: %s") # Blocks in header
if headerFlag & 0x01:
result += tag['rn'][0] + outStr("Header record name: %s").replace('_','') + tag['rn'][1] # Remove character '_' from index
if headerFlag & 0x02:
result += tag['va'][0] + outStr("Header variant: %s") + tag['va'][1]
if headerFlag & 0x04:
s = outInt("Header wordclass: %s")
if s < 32:
result += tag['wc'][0] + wordclass[s] + tag['wc'][1]
else:
raise "Header wordclass out of range in: %s" % result
if headerFlag & 0x08:
result += tag['pa'][0] + outStr("Header parts: %s") + tag['pa'][1]
if headerFlag & 0x10:
result += tag['fo'][0] + outStr("Header forms: %s") + tag['fo'][1]
if headerFlag & 0x20:
result += tag['on'][0] + outStr("Header origin note: %s") + tag['on'][1]
if headerFlag & 0x80:
result += tag['pr'][0] + pronunciation_encode(outStr("Header pronunciation: %s")) + tag['pr'][1]
# Header data block
if mainFlag & 0x02:
headerFlag = outInt("Header dataFlag: %s") # Blocks in header
if headerFlag & 0x02:
result += tag['dv'][0] + outStr("Header dataVariant: %s")+ tag['dv'][1]
# ??? Link elsewhere
pass
# SOUND DATA REFERENCE
if mainFlag & 0x80:
outInt("Sound reference byte #1: %s")
outInt("Sound reference byte #2: %s")
outInt("Sound reference byte #3: %s")
outInt("Sound reference byte #4: %s")
outInt("Sound reference byte #5: %s")
#out("Sound data reference (5 bytes)", 6)
# TODO: Test all mainFlags in header!!!!
#result += ': '
li = 0
#print just every first word class identifier
# TODO: this is not systematic (should be handled by output)
global lastWordClass
lastWordClass = 0
# DATA BLOCK(S)
# -------------
for i in range(0, itemCount):
item = tag['db'][0] + tag['db'][1]
ol = False
dataFlag = outInt("DataFlag: %s -----------------------------")
if dataFlag & 0x01: # small index
sampleFlag = outInt("Data sampleFlag: %s")
if sampleFlag & 0x01:
result += tag['sa'][0] + outStr("Data sample: %s") + tag['sa'][1]
if sampleFlag & 0x04:
s = outInt("Data wordclass: %s")
if s != lastWordClass:
if s < 32:
result += tag['wc'][0] + wordclass[s] + tag['wc'][1]
else:
raise "Header wordclass out of range in: %s" % result
lastWordClass = s
if sampleFlag & 0x08:
result += tag['sw'][0] + outStr("Data sample wordclass: %s") + tag['sw'][1]
if sampleFlag & 0x10:
outInt("Data sample Int: %s")
outInt("Data sample Int: %s")
outInt("Data sample Int: %s")
if sampleFlag & 0x20:
item += tag['do'][0] + outStr("Data origin note: %s") + tag['do'][1]
if sampleFlag & 0x80:
item += " "
result += tag['pr'][0] + pronunciation_encode(outStr("Data sample pronunciation: %s")) + tag['pr'][1]
if dataFlag & 0x02:
item += " "
subFlag = outInt("Data subFlag: %s")
if subFlag == 0x80:
outStr("Data sub prefix: %s")
# It seams that data sub prefix content is ignored and there is a generated number for the whole block instead.
li += 1
ol = True
if dataFlag & 0x04: # chart
pass # ???
if dataFlag & 0x08: # reference
item += tag['df'][0] + outStr("Data definition: %s") + tag['df'][1]
if dataFlag & 0x10:
pass # ???
if dataFlag & 0x20: # phrase
phraseFlag1 = outInt("Data phraseFlag1: %s")
if phraseFlag1 & 0x01:
item += tag['ps'][0] + outStr("Data phrase short form: %s") + tag['ps'][1]
if phraseFlag1 & 0x02:
phraseCount = outInt("Data phraseCount: %s")
for i in range(0, phraseCount):
phraseComment = outInt("Data phrase prefix")
if phraseComment & 0x04:
item += tag['pc'][0] + outStr("Data phrase comment: %s") + tag['pc'][1]
item += tag['p1'][0] + outStr("Data phrase 1: %s") + tag['p1'][1]
item += tag['p2'][0] + outStr("Data phrase 2: %s") + tag['p2'][1]
if phraseFlag1 & 0x04:
phraseCount = outInt("Data phraseCount: %s")
for i in range(0, phraseCount):
phraseComment = outInt("Data phrase prefix")
if phraseComment & 0x04:
item += tag['pc'][0] + outStr("Data phrase 1: %s") + tag['pc'][1]
item += tag['pg'][0] + outStr("Data phrase comment: %s") + tag['pg'][1]
item += tag['p2'][0] + outStr("Data phrase 2: %s") + tag['p2'][1]
if phraseFlag1 & 0x08:
phraseCount = outInt("Data simple phraseCount: %s")
for i in range(0, phraseCount):
item += " "
item += tag['sp'][0] + outStr("Data simple phrase: %s") + tag['sp'][1]
if phraseFlag1 & 0x40:
item += tag['ps'][0] + outStr("Data phrase short form: %s") + tag['ps'][1]
# TODO: be careful in changing the rules, to have back compatibility!
if dataFlag & 0x40: # reference, related language
#0x01 synonym ?
#0x02 antonym ?
pass
if dataFlag & 0x80: # Phrase block
flags = [
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s"),
out("Data phrase block: %s")]
if flags == [0x80,0x80,0xF9,0xDF,0x9D,0x00,0x0B,0x01]:
result += "\\nphr: "
li = 1
ol = True
item += tag['b1'][0]+outStr("Data phrase 1: %s") + tag['b1'][1]
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
item += tag['ds'][0] + outStr("Data phrase 2: %s") + tag['ds'][1]
if flags == [0x80,0x80,0xF9,0xDF,0x9D,0x00,0x23,0x01]:
result += "\\nphr: "
li = 1
ol = True
item += tag['b1'][0]+outStr("Data phrase 1: %s") + tag['b1'][1]
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
out("Data phrase block: %s")
item += tag['ds'][0] + outStr("Data phrase 2: %s") + tag['ds'][1]
if ol:
result += "\\n%d. %s" % (li, item)
else:
result += item
ok = True
while pos < len(stream):
ok = (out() == 0x00) and ok
if ok:
result += '\n'
return decode_tag_postprocessing(result)
################################################################
# MAIN
################################################################
f = open(FILENAME,'rb')
# DECODE HEADER OF FILE
copyright = unpack("<64s",f.read(64))[0]
a = unpack("<16L",f.read(64))
entryCount = a[4]
indexBaseCount = a[6]
indexOffsetCount = a[7]
pos1 = a[8]
indexPos = a[9]
bodyPos = a[10]
smallIndex = (a[3] == 2052)
# DECODE INDEX STRUCTURE OF FILE
index = []
f.seek(indexPos)
bases = unpack("<%sL" % indexBaseCount, f.read(indexBaseCount * 4))
if smallIndex: # In small dictionaries every base is used 4-times
bases4 = []
for i in bases:
bases4.extend([i,i,i,i])
bases = bases4
for b in bases:
offsets = unpack("<64H", f.read(64*2))
for o in offsets:
if len(index) < indexOffsetCount:
#print "Index %s: %s + %s + %s * 4 = %s" % (len(index), bodyPos, b, o, toBin(bodyPos + b + o * 4))
index.append(bodyPos + b + o * 4)
# DECODE RECORDS
if DEBUG:
# PRINTOUT DEBUG OF FIRST <DEBUGLIMIT> WRONG RECORDS:
for i in range(1,entryCount):
if not DEBUGALL:
DEBUG = False
s = decode(getRec(i))
if DEBUGHEADER:
# print s.split('\t')[0]
print s
if DEBUGLIMIT > 0 and not s.endswith('\n'):
DEBUG = True
print "-"*80
print "%s) at address %s" % (i, toBin(index[i]))
print
s = decode(getRec(i))
print s
DEBUGLIMIT -= 1
DEBUG = True
else:
# DECODE EACH RECORD AND PRINT IT IN FORMAT FOR stardict-editor <term>\t<definition>
for i in range(1,entryCount):
s = decode(getRec(i))
if s.endswith('\n'):
print s,
else:
print s
print "!!! RECORD STRUCTURE DECODING ERROR !!!"
print "Please run this script in DEBUG mode and repair DATA BLOCK(S) section in function decode()"
print "If you succeed with whole dictionary send report (name of the dictionary and source code of script) to slovniky@googlegroups.com"
break
| Python |
import sys, string
base = {}
for line in sys.stdin.readlines():
words = string.split(line[:-1], '\t')
if len(words) != 2:
print "Error!"
exit
if base.has_key(words[0]):
base[words[0]] += [words[1]]
else:
base[words[0]] = [words[1]]
keys = base.keys()
keys.sort()
for key in keys:
print key,'\t',
for val in base[key]:
print val,',',
print
| Python |
"""
Compute the difference between two data sets. The data sets can
include an arbitrary number of fields and/or partitions. Some
diagnostics are also printed.
"""
# Get the keys from the first block of the first data set
keys = inputs[0].__iter__().next().PointData.keys()
# Initialize the maximum value dictionary
dmax = dict(zip(keys,[-1.0]*len(keys)))
vmax = dmax.copy()
# Loop on the blocks of the two input data sets
for BLOCK in zip(inputs[0],inputs[1],output):
b_in = BLOCK[0:2] # block inputs
b_out = BLOCK[2] # block output
# Loop on the variables
for k in b_in[0].PointData.keys(): # field loop
delta = b_in[0].PointData[k] - b_in[1].PointData[k]
# delta is either a 1d array (scalar filed) or a 2d one
dm = max(max(abs(delta)))
# compute also a normalization constant
vm = max(max(abs(b_in[0].PointData[k])))
if(dm>dmax[k]):
dmax[k] = dm
if(vm>vmax[k]):
vmax[k] = vm
b_out.PointData.append(delta,'Delta_'+k)
print('Maximum differences:')
print(dmax)
print('Maximum relative differences:')
for k in vmax.keys():
vmax[k] = dmax[k]/vmax[k]
print(vmax)
| Python |
# We assume here that the model results have been interpolated on a
# structured grid and saved in a mat file.
import scipy.io
data = scipy.io.loadmat('data.mat')
X = data['X']
Y = data['Y']
Z = data['Z']
import numpy as np
import pylab as pl
pl.figure()
# this is useful to get a tight bounding box
pl.axes([0.11,0.05,0.875,0.9])
font = {'family' : 'normal',
'weight' : 'normal',
'size' : 18}
pl.rc('font', **font)
# Display the mountain
x = np.linspace(X.min(),X.max(),1000)
h_m = 2000.0
x0 = 100.0e3
a = 10.0e3
pl.fill(x, h_m/(1.0+((x-x0)/a)**2) , 'k')
# Contour plot of the potential temperature
theta = np.reshape(Z[6,:],np.shape(X)).transpose()
print('theta min = %f'%theta.min())
print('theta max = %f'%theta.max())
levels = np.linspace(280.0,700.0,60)
c_theta = pl.contour(X,Y,theta,levels,linewidths=1.5,cmap=pl.cm.RdBu_r)
# Now the inflow wind field
step = 2
xpos = 1
u = np.reshape(Z[2,:],np.shape(X)).transpose()
w = np.reshape(Z[3,:],np.shape(X)).transpose()
q_wind = pl.quiver(X[::step,xpos],Y[::step,xpos], \
u[::step,xpos],w[::step,xpos], \
zorder=2,color='#0B3B0B',width=0.004)
# Finally, the regions where the flow is convectively unstable
Ri = np.reshape(3.0*Z[8,:]-Z[11,:]**2,np.shape(X)).transpose()
c_Ri = pl.contourf(X,Y,Ri,(-10.0,0.0),zorder=-1)
pl.ylim((-100.0,25.0e3))
pl.show()
| Python |
# Copyright (C) 2009,2010,2011,2012 Marco Restelli
#
# This file is part of:
# FEMilaro -- Finite Element Method toolkit
#
# FEMilaro is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# FEMilaro is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with FEMilaro; If not, see <http://www.gnu.org/licenses/>.
#
# author: Marco Restelli <marco.restelli@gmail.com>
"""
Compute the "exact" solution of the linear inertia-gravity wave
problem for the nonhydrostatic case.
Notice that the horizontal direction is treated by Fourier series:
this is exact if the domain is periodic, while it is an approximation
if the domain is infinite - in this latter case one should take the
domain as large as possible.
Notice that minor modifications would be required to handle the
Boussinesq and the hydrostatic cases.
"""
import time
import mpmath as mpm
# Set the working precision
mpm.mp.dps = 25 # decimal digits
# Define the problem constants
N = mpm.mpf('0.01') # Brunt-Vaisalla freq.
T = mpm.mpf('224.0') # temperature
g = mpm.mpf('9.80616')
cp = mpm.mpf('1004.67')
R = mpm.mpf('287.17')
cv = cp-R
gamma = cp/cv
kappa = R/cp
p_s = mpm.mpf('1.0e5') # sea level reference pressure
a = mpm.sqrt(gamma*R*T)
Lx = mpm.mpf('300e3') # domain horizontal size
Lz = mpm.mpf('10e3') # domain vertical size
xc = mpm.mpf('100e3') # perturbation center
aa = mpm.mpf('5e3') # perturbation width
dtheta = mpm.mpf('0.01') # perturbation amplitude
U = mpm.mpf('20.0') # mean flow velocity
t = mpm.mpf('3000.0') # time
z = mpm.mpf('4.5e3') # height
Nx = 12000 # number of points in x direction
Nk = 6000 # number of Fourier modes
r1 = mpm.mpf(1)
r2 = mpm.mpf(2)
r4 = mpm.mpf(4)
l = mpm.pi/Lz
I = [-Lx/r2,Lx/r2] # x interval
# Define the sampling points
x = [ Lx*(-r1/r2+mpm.mpf(i)/mpm.mpf(Nx-1)) for i in range(Nx) ]
# Simplified version of mpm.fourier (see
# mpmath/calculus/approximation.py): Fourier coefficients are
# evaluated with 2N equally spaced nodes.
def Fourier(N,f):
k1 = r2*mpm.pi
x = [-r1/r2+mpm.mpf(i)/mpm.mpf(2*N) for i in xrange(2*N)]
fx = [f(Lx*xi) for xi in x]
F = []
for ki in xrange(N):
kx = k1*mpm.mpf(ki)
F.append( mpm.fsum( fi*mpm.cos(kx*xi) for xi,fi in zip(x,fx) ) )
F[-1] /= mpm.mpf(N)
F[0] /= r2 # scale the first coefficient (mean value)
return F
# Simplified version of mpm.fourierval (see
# mpmath/calculus/approximation.py): Fourier series is evaluated on
# arbitrary points following the definition.
def invFourier(x,F):
k1 = r2*mpm.pi
f = []
for xi in x:
kx = k1*(xi/Lx)
f.append( mpm.fsum( F[ki]*mpm.cos(kx*mpm.mpf(ki)) \
for ki in xrange(len(F)) ) )
return f
T0 = time.clock()
# Fourier coefficients of the initial condition (these could be
# obtained analytically, but then one should pay attention to various
# normalization constants; moreover, a small error would be introduced
# because the domain is limited and periodic, while the analytic
# coefficients are computed for an infinite domain). Notice as well
# that these syntax only captures the cosine coefficients, which is
# correct for the standard initial condition.
def agnesi(x):
return dtheta/((x/aa)**2+r1)*mpm.sin(l*z)
THk0 = Fourier( Nk , agnesi )
T1 = time.clock(); print('Fourier time: %f'%(T1-T0))
# Preliminary check: compare the initial datum with its Fourier
# series.
TH0 = invFourier(x,THk0)
print('Inverse Fourier time: %f'%(time.clock()-T1))
err0 = [ mpm.fabs(agnesi(x[i])-TH0[i]) for i in xrange(len(x)) ]
T1 = time.clock(); print('Total setup time: %f'%(T1-T0))
print('Maximum initial error: %e' % max( float(ei) for ei in err0 ))
import pylab as py
py.figure(1)
py.plot([float(xi) for xi in x],[float(ei) for ei in err0],'go-')
py.title("Initial error")
py.figure(2)
py.title("Initial datum and Fourier series")
py.plot( \
[float(xi) for xi in x] , \
[float(ti) for ti in TH0], \
'mo-', label='Fourier series')
py.plot( \
[float(xi) for xi in x] , \
[float(agnesi(x[i])) for i in xrange(len(x))] , \
'k-', label='initial datum')
py.legend(loc='upper right')
# Now the real computations
T0 = time.clock()
THk = []
N2 , a2 = N**2 , a**2
k1 = r2*mpm.pi/Lx
for ki in range(Nk):
k = k1*mpm.mpf(ki)
k2 = k**2
PHI = a2*(k2+l**2) + N2
tmp = mpm.sqrt(PHI**2 - r4*a2*k2*N2)
PSIs2 = PHI + tmp
PSIg2 = PHI - tmp
den = r2*tmp
Os = mpm.sqrt(PSIs2/r2)
Og = mpm.sqrt(PSIg2/r2)
theta = THk0[ki] \
* ( (mpm.mpf(2)*N2-PSIg2)/den * mpm.cos(Os*t) \
+(PSIs2-mpm.mpf(2)*N2)/den * mpm.cos(Og*t) )
THk.append(theta)
TH = invFourier((xi-U*t+(Lx/r2-xc) for xi in x),THk)
T1 = time.clock()
print('Computation time: %f'%(T1-T0))
py.figure(3)
py.plot( \
[float(xi+xc) for xi in x] , \
[float(ti) for ti in TH0], \
'k-', label='initial condition')
py.plot( \
[float(xi+Lx/r2) for xi in x] , \
[float(ti) for ti in TH], \
'r-', label='time %4.0fs'%t)
py.legend(loc='upper right')
py.show()
| Python |
#! /usr/bin/env python
# encoding: utf-8
# waf 1.6.10
VERSION='0.3.3'
import sys
APPNAME='p2t'
top = '.'
out = 'build'
CPP_SOURCES = ['poly2tri/common/shapes.cc',
'poly2tri/sweep/cdt.cc',
'poly2tri/sweep/advancing_front.cc',
'poly2tri/sweep/sweep_context.cc',
'poly2tri/sweep/sweep.cc',
'testbed/main.cc']
from waflib.Tools.compiler_cxx import cxx_compiler
cxx_compiler['win32'] = ['g++']
#Platform specific libs
if sys.platform == 'win32':
# MS Windows
sys_libs = ['glfw', 'opengl32']
elif sys.platform == 'darwin':
# Apple OSX
sys_libs = ['glfw', 'OpenGL']
else:
# GNU/Linux, BSD, etc
sys_libs = ['glfw', 'GL']
def options(opt):
print(' set_options')
opt.load('compiler_cxx')
def configure(conf):
print(' calling the configuration')
conf.load('compiler_cxx')
conf.env.CXXFLAGS = ['-O3', '-ffast-math']
conf.env.DEFINES_P2T = ['P2T']
conf.env.LIB_P2T = sys_libs
def build(bld):
print(' building')
bld.program(features = 'cxx cxxprogram', source=CPP_SOURCES, target = 'p2t', uselib = 'P2T')
| Python |
# coding=utf-8
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generates test.py from ../../internal/cld2_unittest.cc and ../../internal/unittest_data.h
import re
# NOTE: this generates just a starting point; I had to fixup a few
# tests by hand for silly diffs like Korean vs KOREAN
r = re.compile(r'const char\* (.*?) = "(.*?)";')
testData = {}
f = open('../../internal/unittest_data.h')
for line in f.readlines():
if line.find('#else') != -1:
break
m = r.search(line)
if m is not None:
testData[m.group(1).strip()] = m.group(2)
f.close()
# Carried over from ../../internal/cld2_unittest.cc:
testData['kTeststr_en'] = 'confiscation of goods is assigned as the penalty part most of the courts consist of members and when it is necessary to bring public cases before a jury of members two courts combine for the purpose the most important cases of all are brought jurors or'
#testData['kTeststr_ks'] = 'नेपाल एसिया मंज अख मुलुक राजधानी काठ माडौं नेपाल अधिराज्य पेरेग्वाय दक्षिण अमेरिका महाद्वीपे मध् यक्षेत्रे एक देश अस् ति फणीश्वर नाथ रेणु फिजी छु दक्षिण प्रशान् त महासागर मंज अख देश बहामास छु केरेबियन मंज अख मुलुख राजधानी नसौ सम् बद्घ विषय बुरुंडी अफ्रीका महाद्वीपे मध् यक्षेत्रे देश अस् ति सम् बद्घ विषय'
# Manually extracted from ../../internal/unittest_data.h:
#testData['kTeststr_fr_en_Latn'] = 'A acc\xC3\xA8s aux chiens et aux frontaux qui lui ont \xC3\xA9t\xC3\xA9 il peut consulter et modifier ses collections et exporter This article is about the country. France is the largest country in Western Europe and the third-largest in Europe as a whole. Cet article concerne le pays europ\xC3\xA9\x65n aujourd\xE2\x80\x99hui appel\xC3\xA9 R\xC3\xA9publique fran\xC3\xA7\x61ise. Pour d\xE2\x80\x99\x61utres usages du nom France, Motoring events began soon after the construction of the first successful gasoline-fueled automobiles. The quick brown fox jumped over the lazy dog'
testData['kTeststr_fr_en_Latn'] = "France is the largest country in Western Europe and the third-largest in Europe as a whole. " + \
"A accès aux chiens et aux frontaux qui lui ont été il peut consulter et modifier ses collections et exporter " + \
"Cet article concerne le pays européen aujourd’hui appelé République française. Pour d’autres usages du nom France, " + \
"Motoring events began soon after the construction of the first successful gasoline-fueled automobiles. The quick brown fox jumped over the lazy dog";
r = re.compile(r'\{(.*?), (.*?)\},')
count = 0
doFull = True
if doFull:
f = open('../../internal/cld2_unittest_full.cc')
else:
f = open('../../internal/cld2_unittest.cc')
import test
small = set()
for lang, data in test.testData:
small.add((lang, data))
langs = set()
for line in f.readlines():
m = r.search(line)
if m is not None and not line.strip().startswith('//'):
lang = m.group(1)
if lang == 'UNKNOWN_LANGUAGE':
break
if lang == 'CHINESE':
lang = 'Chinese'
elif lang == 'CHINESE_T':
lang = 'ChineseT'
elif lang == 'JAPANESE':
lang = 'Japanese'
elif lang == 'KOREAN':
lang = 'Korean'
testDataVar = m.group(2).strip()
s = testData[testDataVar].replace('\'', '\\\'')
if not doFull or (lang, s) not in small:
print(' (\'%s\', \'%s\'),' % (lang, s))
count += 1
langs.add(lang)
if False:
print('')
print(' def test_%s(self):' % testDataVar[9:])
print(' self.runOne(\'%s\', \'%s\')' % (lang, testData[testDataVar].replace('\'', '\\\'')))
print('%d langs, %d cases' % (len(langs), count))
| Python |
#!/usr/bin/env python
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from distutils.core import setup, Extension
import distutils.core
import platform
import subprocess
import sys
import os
# NOTE: change this to point to where you checked out the CLD2
# sources:
CLD2_PATH = '../cld2'
# Test suite
class cldtest(distutils.core.Command):
# user_options, initialize_options and finalize_options must be overriden.
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, 'tests/cld_test.py'])
raise SystemExit(errno)
module = Extension('cld2',
language='c++',
include_dirs = ['%s/public' % CLD2_PATH, '%s/internal' % CLD2_PATH],
libraries = ['cld2'],
sources=['pycldmodule.cc', 'encodings.cc'],
)
setup(name='chromium_compact_language_detector',
version='2.0',
author='Michael McCandless',
author_email='mail@mikemccandless.com',
description='Python bindings around Google Chromium\'s embedded compact language detection library (CLD2)',
ext_modules = [module],
license = 'Apache2',
url = 'http://code.google.com/p/chromium-compact-language-detector/',
classifiers = [
'License :: OSI Approved :: BSD License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: C++',
'Programming Language :: Python',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Text Processing :: Linguistic'
],
)
| Python |
#!/usr/bin/env python
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from distutils.core import setup, Extension
import distutils.core
import platform
import subprocess
import sys
import os
# NOTE: change this to point to where you checked out the CLD2
# sources:
CLD2_PATH = '../cld2'
# Test suite
class cldtest(distutils.core.Command):
# user_options, initialize_options and finalize_options must be overriden.
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, 'tests/cld_test.py'])
raise SystemExit(errno)
module = Extension('cld2full',
language='c++',
extra_compile_args = ['-DCLD2_FULL'],
include_dirs = ['%s/public' % CLD2_PATH, '%s/internal' % CLD2_PATH],
libraries = ['cld2_full'],
sources=['pycldmodule.cc', 'encodings.cc'],
)
setup(name='chromium_compact_language_detector',
version='2.0',
author='Michael McCandless',
author_email='mail@mikemccandless.com',
description='Python bindings around Google Chromium\'s embedded compact language detection library (CLD2)',
ext_modules = [module],
license = 'Apache2',
url = 'http://code.google.com/p/chromium-compact-language-detector/',
classifiers = [
'License :: OSI Approved :: BSD License',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: C++',
'Programming Language :: Python',
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Text Processing :: Linguistic'
],
)
| Python |
# coding=utf-8
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import os
import sys
import stat
import unittest
import traceback
# Get just major.minor version of currently running Python, ie 3.2.3
# -> 3.2:
version = sys.version.split()[0]
version = version[:version.rfind('.')]
# Find right .so under build:
moduleDir = None
for dir, subDirs, files in os.walk('build'):
if dir.endswith(version) and dir.find('/lib') != -1:
for file in files:
if file.endswith('.so'):
moduleDir = dir
break
if moduleDir is None:
raise RuntimeError('could not find built libcld.so or cld.cpython-32mu.so; be sure to first run python setup.py build')
sys.path.insert(0, moduleDir)
import cld2full
import cld2
VERBOSE = False
fr_en_Latn = 'France is the largest country in Western Europe and the third-largest in Europe as a whole. A accès aux chiens et aux frontaux qui lui ont été il peut consulter et modifier ses collections et exporter Cet article concerne le pays européen aujourd’hui appelé République française. Pour d’autres usages du nom France, Motoring events began soon after the construction of the first successful gasoline-fueled automobiles. The quick brown fox jumped over the lazy dog'
testData = (
('ENGLISH', 'confiscation of goods is assigned as the penalty part most of the courts consist of members and when it is necessary to bring public cases before a jury of members two courts combine for the purpose the most important cases of all are brought jurors or'),
('ARMENIAN', ' ա յ եվ նա հիացած աչքերով նայում է հինգհարկանի շենքի տարօրինակ փոքրիկ քառակուսի պատուհաններին դեռ մենք շատ ենք հետամնաց ասում է նա այսպես է'),
('CHEROKEE', 'ᎠᎢᏍᎩ ᎠᏟᎶᏍᏗ ᏥᏄᏍᏛᎩ ᎦᎫᏍᏛᏅᎯ ᎾᎥᎢ'),
('DHIVEHI', ' ހިންދީ ބަހުން ވާހަކަ ދައްކާއިރު ދެވަނަ ބަހެއްގެ ގޮތުގައާއި އެނޫން ގޮތްގޮތުން ހިންދީ ބަހުން ވާހަކަ ދައްކާ މީހުންގެ އަދަދު މިލިއަނަށް'),
('GEORGIAN', ' ა ბირთვიდან მიღებული ელემენტი მენდელეევის პერიოდულ სიტემაში გადაინაცვლებს ორი უჯრით'),
('GREEK', ' ή αρνητική αναζήτηση λέξης κλειδιού καταστήστε τις μεμονωμένες λέξεις κλειδιά περισσότερο στοχοθετημένες με τη μετατροπή τους σε'),
('GUJARATI', ' આના પરિણામ પ્રમાણસર ફોન્ટ અવતરણ ચિન્હવાળા પાઠને છુપાવો બધા સમૂહો શોધાયા હાલનો જ સંદેશ વિષયની'),
('INUKTITUT', 'ᐃᑯᒪᒻᒪᑦ ᕿᓈᖏᓐᓇᓲᖑᒻᒪᑦ ᑎᑎᖅᑕᓕᒫᖅᓃᕕᑦ ᑎᑦᕆᐊᑐᓐᖏᑦᑕᑎᑦ ᑎᑎᖅᑕᑉᐱᑦ ᓯᕗᓂᖓᓂ ᑎᑎᖅᖃᖅ ᑎᑎᕆᐊᑐᓐᖏᑕᐃᑦ ᕿᓂᓲᖑᔪᒍᑦ ᑎᑎᖅᑕᓕᒫᖅᓃᕕᑦ'),
('KANNADA', ' ಂಠಯ್ಯನವರು ತುಮಕೂರು ಜಿಲ್ಲೆಯ ಚಿಕ್ಕನಾಯಕನಹಳ್ಳಿ ತಾಲ್ಲೂಕಿನ ತೀರ್ಥಪುರ ವೆಂಬ ಸಾಧಾರಣ ಹಳ್ಳಿಯ ಶ್ಯಾನುಭೋಗರ'),
('KHMER', ' ក ខ គ ឃ ង ច ឆ ជ ឈ ញ ដ ឋ ឌ ឍ ណ ត ថ ទ ធ ន ប ផ ព ភ ម យ រ ល វ ស ហ ឡ អ ឥ ឦ ឧ ឪ ឫ ឬ ឯ ឱ ទាំងអស់'),
('LAOTHIAN', ' ກຫາທົ່ວທັງເວັບ ແລະໃນເວັບໄຮ້ສາຍ ທຳອິດໃຫ້ທຳການຊອກຫາກ່ອນ ຈາກນັ້ນ ໃຫ້ກົດປຸ່ມເມນູ ໃນໜ້າຜົນໄດ້'),
('LIMBU', 'ᤁᤡᤖᤠᤳ ᤕᤠᤰᤌᤢᤱ ᤆᤢᤶᤗᤢᤱᤖᤧ ᤛᤥᤎᤢᤱᤃᤧᤴ ᤀᤡᤔᤠᤴᤛᤡᤱ ᤆᤧᤶᤈᤱᤗᤧ ᤁᤢᤔᤡᤱᤅᤥ ᤏᤠᤈᤡᤖᤡ ᤋᤱᤒᤣ ᥈᥆᥆᥉ ᤒᤠ ᤈᤏᤘᤖᤡ ᤗᤠᤏᤢᤀᤠᤱ ᤁ᤹ᤏᤠ ᤋᤱᤒᤣ ᤁᤠᤰ ᤏᤠ᤺ᤳᤋᤢ ᤕᤢᤖᤢᤒᤠ ᤀᤡᤔᤠᤴᤛᤡᤱ ᤋᤱᤃᤡᤵᤛᤡᤱ ᤌᤡᤶᤒᤣᤴ ᤂᤠᤃᤴ ᤛᤡᤛᤣ᤺ᤰᤗᤠ ᥇᥍ ᤂᤧᤴ ᤀᤡᤛᤡᤰ ᥇ ᤈᤏᤘᤖᤡ ᥈᥆᥆᥊ ᤀᤥ ᤏᤠᤛᤢᤵ ᤆᤥ᤺ᤰᤔᤠ ᤌᤡᤶᤒᤣ ᤋᤱᤃᤠᤶᤛᤡᤱᤗ ᤐᤳᤐᤠ ᤀᤡᤱᤄᤱ ᤘᤠ᤹'),
('MALAYALAM', ' ം അങ്ങനെ ഞങ്ങള് അവരുടെ മുമ്പില് നിന്നു ഔടും ഉടനെ നിങ്ങള് പതിയിരിപ്പില് നിന്നു എഴുന്നേറ്റു'),
('ORIYA', 'ଅକ୍ଟୋବର ଡିସେମ୍ବର'),
('PUNJABI', ' ਂ ਦਿਨਾਂ ਵਿਚ ਭਾਈ ਸਾਹਿਬ ਦੀ ਬੁੱਚੜ ਗੋਬਿੰਦ ਰਾਮ ਨਾਲ ਅੜਫਸ ਚੱਲ ਰਹੀ ਸੀ ਗੋਬਿੰਦ ਰਾਮ ਨੇ ਭਾਈ ਸਾਹਿਬ ਦੀਆਂ ਭੈਣਾ'),
('SINHALESE', ' අනුරාධ මිහිඳුකුල නමින් සකුරා ට ලිපියක් තැපෑලෙන් එවා තිබුණා කි ් රස්ටි ෂෙල්ටන් ප ් රනාන්දු ද'),
('SYRIAC', 'ܐܕܪܝܣ ܓܛܘ ܫܘܪܝܐ ܡܢ ܦܪܢܣܐ ܡܢ ܐܣܦܢܝܐ ܚܐܪܘܬܐ ܒܐܕܪ ܒܢܝܣܢ ܫܛܝܚܘܬܐ ܟܠܢܝܐ ܡܝ̈ܐ ܒܥܠܡܐ'),
('TAGALOG', ' ᜋᜇ᜔ ᜐᜓᜎᜆ᜔ ᜃ ᜈᜅ᜔ ᜊᜌ᜔ᜊᜌᜒᜈ᜔ ᜂᜉᜅ᜔᜔ ᜋᜐᜈᜌ᜔ ᜎᜅ᜔ ᜁᜐ ᜉᜅ᜔ ᜀᜃ᜔ᜎᜆ᜔ ᜆᜓᜅ᜔ᜃᜓᜎ᜔ ᜐ ᜊᜌ᜔ᜊᜌᜒᜈ᜔ ᜐ ᜆᜒᜅᜒᜈ᜔ ᜃᜓ'),
('TAMIL', ' அங்கு ராஜேந்திர சோழனால் கட்டப்பட்ட பிரம்மாண்டமான சிவன் கோவில் ஒன்றும் உள்ளது தொகு'),
('TELUGU', ' ఁ దనర జయించిన తత్వ మరసి చూడఁ దాన యగును రాజయోగి యిట్లు తేజరిల్లుచు నుండు విశ్వదాభిరామ వినర వేమ'),
('THAI', ' กฏในการค้นหา หรือหน้าเนื้อหา หากท่านเลือกลงโฆษณา ท่านอาจจะปรับต้องเพิ่มงบประมาณรายวันตา'),
('Chinese', '产品的简报和公告 提交该申请后无法进行更改 请确认您的选择是正确的 对于要提交的图书 我确认 我是版权所有者或已得到版权所有者的授权 要更改您的国家 地区 请在此表的最上端更改您的'),
('ChineseT', ' 之前為 帳單交易作業區 已變更 廣告內容 之前為 銷售代表 之前為 張貼日期為 百分比之前為 合約 為 目標對象條件已刪除 結束日期之前為'),
('Japanese', ' このペ ジでは アカウントに指定された予算の履歴を一覧にしています それぞれの項目には 予算額と特定期間のステ タスが表示されます 現在または今後の予算を設定するには'),
('Korean', ' 개별적으로 리포트 액세스 권한을 부여할 수 있습니다 액세스 권한 부여사용자에게 프로필 리포트에 액세스할 수 있는 권한을 부여하시려면 가용 프로필 상자에서 프로필 이름을 선택한 다음'),
('AFRIKAANS', ' aam skukuza die naam beteken hy wat skoonvee of hy wat alles onderstebo keer wysig bosveldkampe boskampe is kleiner afgeleë ruskampe wat oor min fasiliteite beskik daar is geen restaurante of winkels nie en slegs oornagbesoekers word toegelaat bateleur'),
('ALBANIAN', ' a do të kërkoni nga beogradi që të njohë pavarësinë e kosovës zoti thaçi prishtina është gati ta njoh pavarësinë e serbisë ndërsa natyrisht se do të kërkohet një gjë e tillë që edhe beogradi ta njoh shtetin e pavarur dhe sovran të'),
('ARABIC', 'احتيالية بيع أي حساب'),
('AZERBAIJANI', ' a az qalıb breyn rinq intellektual oyunu üzrə yarışın zona mərhələləri keçirilib miq un qalıqlarının dənizdən çıxarılması davam edir məhəmməd peyğəmbərin karikaturalarını çap edən qəzetin baş redaktoru iş otağında ölüb'),
('BASQUE', ' a den eraso bat honen kontra hortaz eragiketa bakarrik behar dituen eraso batek aes apurtuko luke nahiz eta oraingoz eraso bideraezina izan gaur egungo teknologiaren mugak direla eta oraingoz kezka hauek alde batera utzi daitezke orain arteko indar'),
('BELARUSIAN', ' а друкаваць іх не было тэхнічна магчыма бліжэй за вільню тым самым часам нямецкае кіраўніцтва прапаноўвала апроч ўвядзення лацінкі яе'),
('BENGALI', ' ংখ্যা নমুনায়ন বিন্যাস পরিসংখ্যানিক মডেল পরিসংখ্যানিক সিদ্ধান্ত ফাংশন পরিসংখ্যানিক'),
('BIHARI', ' विकिपीडिया इंटरनेट आधारित एक मुक्त ज्ञानकोष परियोजना ह ई विकि के रुप मेँ बा यानी एगो अईसन जाल पृष्ठ जे सभन के संपादन करे के छूट देवेला विकिपीडिया शब्द विकि अउर इनसाइक्लोपीडिया ज्ञानकोष शब्दन के मिला के बनल बा विकिपीडिया एक बहुभाषीय प्रकल्प ह अउर स्वयंसेवकन के सहकार से निर्मित बा जेहु के भी इंटरनेट तक पहुँच बा ऊ विकिपीडिया पर लिख सकत बा अउर लेखन के संपादन कर सकत बा'),
('BULGARIAN', ' а дума попада в състояние на изпитание ключовите думи с предсказана малко под то изискване на страниците за търсене в'),
('CATALAN', 'al final en un únic lloc nhorabona l correu electrònic està concebut com a eina de productivitat aleshores per què perdre el temps arxivant missatges per després intentar recordar on els veu desar i per què heu d eliminar missatges importants per l'),
('CEBUANO', 'Ang Sugbo usa sa mga labing ugmad nga lalawigan sa nasod. Kini ang sentro sa komersyo, edukasyon ug industriya sa sentral ug habagatang dapit sa kapupod-an. Ang mipadayag sa Sugbo isip ikapito nga labing nindot nga pulo sa , ang nag-inusarang pulo sa Pilipinas nga napasidunggan sa maong magasin sukad pa sa tuig'),
('CROATIAN', 'Posljednja dva vladara su Kijaksar (Κυαξαρης; 625-585 prije Krista), fraortov sin koji će proširiti teritorij Medije i Astijag. Kijaksar je imao kćer ili unuku koja se zvala Amitis a postala je ženom Nabukodonosora II. kojoj je ovaj izgradio Viseće vrtove Babilona. Kijaksar je modernizirao svoju vojsku i uništio Ninivu 612. prije Krista. Naslijedio ga je njegov sin, posljednji medijski kralj, Astijag, kojega je detronizirao (srušio sa vlasti) njegov unuk Kir Veliki. Zemljom su zavladali Perzijanci.'),
('CZECH', ' a akci opakujte film uložen vykreslit gmail tokio smazat obsah adresáře nelze načíst systémový profil jednotky smoot okud používáte pro určení polokoule značky z západ nebo v východ používejte nezáporné hodnoty zeměpisné délky nelze'),
('DANISH', ' a z tallene og punktummer der er tilladte log ud angiv den ønskede adgangskode igen november gem personlige oplysninger kontrolspørgsmål det sidste tegn i dit brugernavn skal være et bogstav a z eller tal skriv de tegn du kan se i billedet nedenfor'),
('DUTCH', ' a als volgt te werk om een configuratiebestand te maken sitemap gen py ebruik filters om de s op te geven die moeten worden toegevoegd of uitgesloten op basis van de opmaaktaal elke sitemap mag alleen de s bevatten voor een bepaalde opmaaktaal dit'),
('ENGLISH', ' a backup credit card by visiting your billing preferences page or visit the adwords help centre for more details https adwords google com support bin answer py answer hl en we were unable to process the payment of for your outstanding google adwords'),
('ESTONIAN', ' a niipea kui sinu maksimaalne igakuine krediidi limiit on meie poolt heaks kiidetud on sinu kohustuseks see krediidilimiit'),
('FINNISH', ' a joilla olet käynyt tämä kerro meille kuka ä olet ei tunnistettavia käyttötietoja kuten virheraportteja käytetään google desktopin parantamiseen etsi näyttää mukautettuja uutisia google desktop keskivaihto leikkaa voit kaksoisnapsauttaa'),
('FRENCH', ' a accès aux collections et aux frontaux qui lui ont été attribués il peut consulter et modifier ses collections et exporter des configurations de collection toutefois il ne peut pas créer ni supprimer des collections enfin il a accès aux fonctions'),
('GALICIAN', ' debe ser como mínimo taranto tendas de venda polo miúdo cociñas servizos bordado canadá viaxes parques de vehículos de recreo hotel oriental habitación recibir unha postal no enderezo indicado anteriormente'),
('GANDA', ' abaana ba bani lukaaga mu ana mu babiri abaana ba bebayi lukaaga mu abiri mu basatu abaana ba azugaadi lukumi mu ebikumi bibiri mu abiri mu babiri abaana ba adonikamu lukaaga mu nltaaga mu mukaaga abaana ba biguvaayi enkumi bbiri mu ataano mu mukaaga'),
('GERMAN', ' abschnitt ordner aktivieren werden die ordnereinstellungen im farbabschnitt deaktiviert öchten sie wirklich fortfahren eldtypen angeben optional n diesem schritt geben sie für jedesfeld aus dem datenset den typ an ieser schritt ist optional eldtypen'),
('HAITIAN_CREOLE', ' ak pitit tout sosyete a chita se pou sa leta dwe pwoteje yo nimewo leta fèt pou li pwoteje tout paran ak pitit nan peyi a menm jan kit paran yo marye kit yo pa marye tout manman ki fè pitit leta fèt pou ba yo konkoul menm jan tou pou timoun piti ak pou'),
('HEBREW', ' או לערוך את העדפות ההפצה אנא עקוב אחרי השלבים הבאים כנס לחשבון האישי שלך ב'),
('HINDI', ' ं ऐडवर्ड्स विज्ञापनों के अनुभव पर आधारित हैं और इनकी मदद से आपको अपने विज्ञापनों का अधिकतम लाभ'),
('HMONG', ' Kuv hlub koj txawm lub ntuj yuav si ntshi nphaus los kuv tsis ua siab nkaug txawm ntiab teb yuav si ntshi nphaus los kuv tseem ua lon tsaug vim kuv hlub koj tag lub siab'),
('HUNGARIAN', ' a felhasználóim a google azonosító szöveget ikor látják a felhasználóim a google azonosító szöveget felhasználók a google azonosító szöveget fogják látni minden tranzakció után ha a vásárlását regisztrációját oldalunk'),
('ICELANDIC', ' a afköst leitarorða þinna leitarorð neikvæð leitarorð auglýsingahópa byggja upp aðallista yfir ný leitarorð fyrir auglýsingahópana og skoða ítarleg gögn um árangur leitarorða eins og samkeppni auglýsenda og leitarmagn er krafist notkun'),
('INDONESIAN', 'Geng: Pengembaraan Bermula adalah film animasi 3D CGI pertama yang diproduksi di Malaysia. Film ini dibuat oleh Les\' Copaque Production (LCP) dan dirilis di bioskop-bioskop seluruh Malaysia pada 12 Februari 2009. Film Geng pertama kali diluncurkan dalam sebuah acara peluncuran pada 11 September 2007 bersama dengan serial animasi pendek Upin & Ipin yang berhubungan dengan film tersebut. Pembuatan film ini didukung oleh berbagai pihak seperti Kementerian Sains, Teknologi dan Inovasi Malaysia (MOSTI) dengan memberi bantuan berupa dana sebesar RM1 juta.'),
('IRISH', ' a bhfuil na focail go léir i do cheist le fáil orthu ní gá ach focail breise a chur leis na cinn a cuardaíodh cheana chun an cuardach a bheachtú nó a chúngú má chuirtear focal breise isteach aimseofar fo aicme ar leith de na torthaí a fuarthas'),
('ITALIAN', ' a causa di un intervento di manutenzione del sistema fino alle ore circa ora legale costa del pacifico del novembre le campagne esistenti continueranno a essere pubblicate come di consueto anche durante questo breve periodo di inattività ci scusiamo per'),
('JAVANESE', ' account ten server niki kalian username meniko tanpo judul cacahe account nggonanmu wes pol pesen mu wes diguwak pesenan mu wes di simpen sante wae pesenan mu wes ke kirim mbuh tekan ora pesenan e ke kethok pesenan mu wes ke kirim mbuh tekan ora pesenan'),
('KINYARWANDA', ' dore ibyo ukeneye kumenya ukwo watubona ibibazo byinshi abandi babaza ububonero byibibina google onjela ho izina dyikyibina kyawe onjela ho yawe mulugo kulaho ibyandiko byawe shyilaho tegula yawe tulubaka tukongeraho iyanya mishya buliko tulambula'),
('LATVIAN', ' a gadskārtējā izpārdošana slēpošana jāņi atlaide izmaiņas trafikā kas saistītas ar sezonas izpārdošanu speciālajām atlaidēm u c ir parastas un atslēgvārdi kas ir populāri noteiktos laika posmos šajā laikā saņems lielāku klikšķu'),
('LITHUANIAN', ' a išsijungia mano idėja dėl geriausio laiko po pastarųjų savo santykių pasimokiau penki dalykai be kurių negaliu gyventi mano miegamajame tu surasi ideali pora išsilavinimas aukštoji mokykla koledžas universitetas pagrindinis laipsnis metai'),
('MACEDONIAN', ' гласовите коалицијата на вмро дпмне како партија со најмногу освоени гласови ќе добие евра а на сметката на коализијата за македонија'),
('MALAY', 'daripada dirinya hirako shinji seorang pemuda merujuk diri mereka sebagai vizard shinji telah cuba untuk menyakinkan ichigo untuk menyertai kumpulan mereka mengatakan bahawa hanya dia sahaja yang mampu mengajar ichigo teknik untuk mengawal hollow'),
('MALTESE', ' ata ikteb messaġġ lil indirizzi differenti billi tagħżilhom u tagħfas il buttuna ikteb żid numri tfittxijja tal kotba mur print home kotba minn pagni ghal pagna minn ghall ktieb ta aċċessa stieden habib iehor grazzi it tim tal gruppi google'),
('MARATHI', 'हैदराबाद उच्चार ऐका (सहाय्य·माहिती)तेलुगू: హైదరాబాదు , उर्दू: حیدر آباد हे भारतातील आंध्र प्रदेश राज्याच्या राजधानीचे शहर आहे. हैदराबादची लोकसंख्या ७७ लाख ४० हजार ३३४ आहे. मोत्यांचे शहर अशी एकेकाळी ओळख असलेल्या या शहराला ऐतिहासिक, सांस्कृतिक आणि स्थापत्यशास्त्रीय वारसा लाभला आहे. १९९० नंतर शिक्षण आणि माहिती तंत्रज्ञान त्याचप्रमाणे औषधनिर्मिती आणि जैवतंत्रज्ञान क्षेत्रातील उद्योगधंद्यांची वाढ शहरात झाली. दक्षिण मध्य भारतातील पर्यटन आणि तेलुगू चित्रपटनिर्मितीचे हैदराबाद हे केंद्र आहे'),
('NEPALI', 'अरू ठाऊँबाटपनि खुलेको छ यो खाता अर अरू ठाऊँबाटपनि खुलेको छ यो खाता अर ू'),
('NORWEGIAN', ' a er obligatorisk tidsforskyvning plassering av katalogsøk planinformasjon loggfilbane gruppenavn kontoinformasjon passord domene gruppeinformasjon alle kampanjesporing alternativ bruker grupper oppgaveplanlegger oppgavehistorikk kontosammendrag antall'),
('PERSIAN', ' آب خوردن عجله می کردند به جای باز ی کتک کاری می کردند و همه چيز مثل قبل بود فقط من ماندم و يک دنيا حرف و انتظار تا عاقبت رسيد احضاريه ی ای با'),
('POLISH', ' a australii będzie widział inne reklamy niż użytkownik z kanady kierowanie geograficzne sprawia że reklamy są lepiej dopasowane do użytkownika twojej strony oznacza to także że możesz nie zobaczyć wszystkich reklam które są wyświetlane na'),
('PORTUGUESE', ' a abit prevê que a entrada desses produtos estrangeiros no mercado têxtil e vestuário do brasil possa reduzir os preços em cerca de a partir de má notícia para os empresários que terão que lutar para garantir suas margens de lucro mas boa notícia'),
('ROMANIAN', ' a anunţurilor reţineţi nu plătiţi pentru clicuri sau impresii ci numai atunci când pe site ul dvs survine o acţiune dorită site urile negative nu pot avea uri de destinaţie daţi instrucţiuni societăţii dvs bancare sau constructoare să'),
('ROMANIAN', 'оперативэ а органелор ши институциилор екзекутиве ши а органелор жудичиаре але путерий де стат фиекэруй орган ал путерий де стат и се'),
('RUSSIAN', ' а неправильный формат идентификатора дн назад'),
('SCOTS_GAELIC', ' air son is gum bi casg air a h uile briosgaid no gum faigh thu brath nuair a tha briosgaid a tighinn gad rannsachadh ghoogle gu ceart mura bheil briosgaidean ceadaichte cuiridh google briosgaid dha do neach cleachdaidh fa leth tha google a cleachdadh'),
('SERBIAN', 'балчак балчак на мапи србије уреди демографија у насељу балчак живи пунолетна становника а просечна старост становништва износи година'),
('SERBIAN', ' autonomnih pokrajina saveznim zakonom može se propisati poseban sastav organizacija i delokrug saveta za poslove narodne odbrane članove saveta federacije bira na predlog predsedništva savezna skupština iz reda društveno političkih i drugih javnih'),
('SLOVAK', ' a aktivovať reklamnú kampaň ak chcete kampaň pred spustením ešte prispôsobiť uložte ju ako šablónu a pokračujte v úprave vyberte si jednu z možností nižšie a kliknite na tlačidlo uložiť kampaň nastavenia kampane môžete ľubovoľne'),
('SLOVENIAN', ' adsense stanje prijave za google adsense google adsense račun je bil začasno zamrznjen pozdravljeni hvala za vaše zanimanje v google adsense po pregledu vaše prijavnice so naši strokovnjaki ugotovili da spletna stran ki je trenutno povezana z vašim'),
('SPANISH', ' a continuación haz clic en el botón obtener ruta también puedes desplazarte hasta el final de la página para cambiar tus opciones de búsqueda gráfico y detalles ésta es una lista de los vídeos que te recomendamos nuestras recomendaciones se basan'),
('SWAHILI', ' a ujumbe mpya jumla unda tafuta na angalia vikundi vya kujadiliana na kushiriki mawazo iliyopangwa kwa tarehe watumiaji wapya futa orodha hizi lugha hoja vishikanisho vilivyo dhaminiwa ujumbe sanaa na tamasha toka udhibitisho wa neno kwa haraka fikia'),
('SWEDISH', ' a bort objekt från google desktop post äldst meny öretag dress etaljer alternativ för vad är inne yaste google skrivbord plugin program för nyheter google visa nyheter som är anpassade efter de artiklar som du läser om du till exempel läser'),
('TAGALOG', ' a na ugma sa google ay nakaka bantog sa gitna nang kliks na nangyayari sa pamamagitan nang ordinaryong paggagamit at sa kliks na likha nang pandaraya o hindi tunay na paggamit bunga nito nasasala namin ang mga kliks na hindi kailangan o hindi gusto nang'),
('TURKISH', ' a ayarlarınızı görmeniz ve yönetmeniz içindir eğer kampanyanız için günlük bütçenizi gözden geçirebileceğiniz yeri arıyorsanız kampanya yönetimi ne gidin kampanyanızı seçin ve kampanya ayarlarını düzenle yi tıklayın sunumu'),
('UKRAINIAN', ' а більший бюджет щоб забезпечити собі максимум прибутків від переходів відстежуйте свої об яви за датою географічним розташуванням'),
('URDU', ' آپ کو کم سے کم ممکنہ رقم چارج کرتا ہے اس کی مثال کے طور پر فرض کریں اگر آپ کی زیادہ سے زیادہ قیمت فی کلِک امریکی ڈالر اور کلِک کرنے کی شرح ہو تو'),
('VIETNAMESE', ' adsense cho nội dung nhà cung cấp dịch vụ di động xác minh tín dụng thay đổi nhãn kg các ô xem chi phí cho từ chối các đơn đặt hàng dạng cấp dữ liệu ác minh trang web của bạn để xem'),
('WELSH', ' a chofrestru eich cyfrif ymwelwch a unwaith i chi greu eich cyfrif mi fydd yn cael ei hysbysu o ch cyfeiriad ebost newydd fel eich bod yn gallu cadw mewn cysylltiad drwy gmail os nad ydych chi wedi clywed yn barod am gmail mae n gwasanaeth gwebost'),
('YIDDISH', 'און פאנטאזיע ער איז באקאנט צים מערסטן פאר זיינע באַלאַדעס ער האָט געוווינט אין ווארשע יעס פאריס ליווערפול און לאנדאן סוף כל סוף איז ער'),
('INDONESIAN', 'sukiyaki wikipedia indonesia ensiklopedia bebas berbahasa bebas berbahasa indonesia langsung ke navigasi cari untuk pengertian lain dari sukiyaki lihat sukiyaki irisan tipis daging sapi sayur sayuran dan tahu di dalam panci besi yang dimasak di atas meja makan dengan cara direbus sukiyaki dimakan dengan mence'),
('MALAY', 'sukiyaki wikipedia bahasa melayu ensiklopedia bebas sukiyaki dari wikipedia bahasa melayu ensiklopedia bebas lompat ke navigasi gelintar sukiyaki sukiyaki hirisan tipis daging lembu sayur sayuran dan tauhu di dalam periuk besi yang dimasak di atas meja makan dengan cara rebusan sukiyaki dimakan dengan mence'),
# NOTE: in cld_unittest.cpp, this test passes FRENCH, but that is
# using the "summary" language returned by
# ExtDetectLanguageSummary, which we now discard in Python.
# Technically English is the better answer (53.5% of the text is
# English):
('ENGLISH', fr_en_Latn),
# This is just the "version marker":
('WELSH', 'qpdbmrmxyzptlkuuddlrlrbas las les qpdbmrmxyzptlkuuddlrlrbas el la qpdbmrmxyzptlkuuddlrlrbas'),
)
fullTestData = testData[:-1] + (
('MONGOLIAN', 'ᠦᠭᠡ ᠵᠢᠨ ᠴᠢᠨᠭᠠ ᠬᠦᠨᠳᠡᠢ ᠵᠢ ᠢᠯᠭᠠᠬᠣ'),
('X_Buginese', 'ᨄᨛᨑᨊᨒ ᨑᨗ ᨔᨒᨗᨓᨛ ᨕᨗᨋᨗᨔᨗ ᨒᨛᨄ ᨑᨛᨔᨛᨆᨗᨊ'),
('X_Gothic', '𐌰 𐌰𐌱𐍂𐌰𐌷𐌰𐌼 𐌰𐌲𐌲𐌹𐌻𐌹𐍃𐌺𐍃 𐌸𐌹𐌿𐌳𐌹𐍃𐌺𐍃 𐍆𐍂𐌰𐌲𐌺𐌹𐍃𐌺𐍃'),
('ABKHAZIAN', ' а зуа абзиара дақәшәоит ан лыбзиабара ахә амаӡам ауаҩы игәы иҭоу ихы иҿы ианубаалоит аҧҳәыс ҧшӡа ахацәа лышьҭоуп аҿаасҭа лара дрышьҭоуп'),
('AFAR', ' nagay tanito nagay tanto nagayna naharsi nahrur nake nala nammay nammay haytu nanu narig ne ni num numu o obare obe obe obisse oggole ogli olloyta ongorowe orbise othoga r rabe rade ra e rage rakub rasitte rasu reyta rog ruddi ruga s sa al bada sa ala'),
('AKAN', 'Wɔwoo Hilla Limann Mumu-Ɔpɛnimba 12 afe 1934. Wɔwoo no wɔ Gwollu wɔ Sisala Mantaw mu Nna ne maame yɛ Mma Hayawah. Ne papa so nna ɔyɛ Babini Yomu. Ɔwarr Fulera Limann ? Ne mba yɛ esuon-- Lariba Montia [wɔwoo no Limann]; Baba Limann; Sibi Andan [wɔwoo no Limann]; Lida Limann; Danni Limann; Zilla Limann na Salma Limann. Ɔtenaa ase kɔpemm Sanda-Kwakwa da ɛtɔ so 23 wɔ afe 1998 wɔ ?.'),
('AMHARIC', ' ለመጠይቅ ወደ እስክንድርያ ላኩዋቸውና የእስክንድርያ ጳጳስ አቴናስዮስ ፍሬምንጦስን እራሳቸውን ሾመው ልከዋል ከዚያ እስከ ዓ ም ድረስ የኢትዮጵያ አቡነ'),
('ASSAMESE', 'অঞ্চল নতুন সদস্যবৃন্দ সকলোৱে ভৰ্তি হব পাৰে মুল পৃষ্ঠা জন লেখক গুগ ল দল সাৰাংশ ই পত্ৰ টা বাৰ্তা এজন'),
('AYMARA', ' aru wijar aru ispañula ukaran aru witanam aru kurti aru kalis aru warani aru malta aru yatiyawi niya jakitanaka isluwiñ aru lmir phuran aru masirunan aru purtukal aru kruwat aru jakira urtu aru inklisa pirsan aru suyku aru malay aru jisk aptayma thaya'),
('BASHKIR', ' арналђан бындай ђилми эш тіркињлњ тњјге тапєыр нњшер ителњ ғинуар бєхет именлектє етешлектє ауыл ўќмерџєре хеџмєт юлын ћайлаѓанда'),
('BISLAMA', ' king wantaem nomo hem i sakem setan mo ol rabis enjel blong hem oli aot long heven oli kamdaon long wol taswe ol samting oli kam nogud olgeta long wol ya stat long revelesen ol faet kakae i sot ol sik mo fasin blong brekem loa oli kam antap olgeta samting'),
('BRETON', ' a chom met leuskel a ra e blas da jack irons dilabour hag aet kuit eus what is this dibab a reont da c houde michael beinhorn evit produiñ an trede pladenn kavet e vez ar ganaouennoù buhan ha buhan ganto setu stummet ar bladenn adkavet e vez enni funk'),
('BURMESE', ' တက္ကသုိလ္ မ္ဟ ပ္ရန္ လာ္ရပီးေနာက္ န္ဟစ္ အရ္ဝယ္ ဦးသန္ ့သည္ ပန္ းတနော္ အမ္ယုိးသား ေက္ယာင္ း'),
('CORSICAN', ' a prupusitu di risultati for utilizà a scatula per ricercà ind issi risultati servore errore u servore ha incuntratu una errore pruvisoria é ùn ha pussutu compie a vostra dumanda per piacè acimenta dinò ind una minuta tuttu listessu ligami truvà i'),
('DZONGKHA', ' རྩིས བརྐྱབ ཚུལ ལྡན དང ངེས བདེན སྦ སྟོན ནིའི དོན ལུ ཁྱོད གུག ཤད ལག ལེན འཐབ དགོ ག དང ཨིན པུཊི གྲལ ཐིག གུ'),
('ESPERANTO', ' a jarcento refoje per enmetado de koncerna pastro tiam de reformita konfesio ekde refoje ekzistis luteranaj komunumanoj tamen tiuj fondis propran komunumon nur en ambaŭ apartenis ekde al la evangela eklezio en prusio resp ties rejnlanda provinceklezio en'),
('FAROESE', ' at verða átaluverdar óhóskandi ella áloypandi vit kunnu ikki garanterða at google leitanin ikki finnur naka sum er áloypandi óhóskandi ella átaluvert og google tekur onga ábyrgd yvir tær síður sum koma við í okkara leitiskipan fá tær ein'),
('FIJIAN', ' i kina na i iri ka duatani na matana main a meke wesi se meke mada na meke ni yaqona oqo na meke ka dau vakayagataki ena yaqona vakaturaga e dau caka toka ga kina na vucu ka dau lagati tiko kina na ka e yaco tiko na talo ni wai ni yaqona na lewai ni wai'),
('FRISIAN', ' adfertinsjes gewoan lytse adfertinsjes mei besibbe siden dy t fan belang binne foar de ynhâld fan jo berjochten wolle jo mear witte fan gmail foardat jo jo oanmelde gean dan nei wy wurkje eltse dei om gmail te ferbetterjen dêrta sille wy jo sa út en'),
('GREENLANDIC', ' at nittartakkalli uani toqqarsimasatta akornanni nittartakkanut allanut ingerlaqqittoqarsinnaavoq kanukoka tassaavoq kommuneqarfiit kattuffiat nuna tamakkerlugu kommunit nittartagaannut ingerlaqqiffiusinnaasoq kisitsiserpassuit nunatsinnut tunngasut'),
('GUARANI', ' aháta añe ë ne mbo ehára ndive ajeruréta chupe oporandujey haĝua peëme mba épa pekaru ha áĝa oporandúvo nde eréta avei re paraguaýpe kachíke he i leúpe ndépa re úma kure tatakuápe ha leu ombohovái héë ha ujepéma kachíke he ijey'),
('HAUSA', ' a cikin a kan sakamako daga sakwannin a kan sakamako daga sakwannin daga ranar zuwa a kan sakamako daga guda daga ranar zuwa a kan sakamako daga shafukan daga ranar zuwa a kan sakamako daga guda a cikin last hour a kan sakamako daga guda daga kafar'),
('HAWAIIAN', 'He puke noiʻi kūʻikena kūnoa ʻo Wikipikia. E ʻoluʻolu nō, e hāʻawi mai i kāu ʻike, kāu manaʻo, a me kou leo no ke kūkulu ʻana a me ke kākoʻo ʻana mai i ka Wikipikia Hawaiʻi. He kahua pūnaewele Hawaiʻi kēia no ka hoʻoulu ʻana i ka ʻike Hawaiʻi. Inā hiki iā ʻoe ke ʻōlelo Hawaiʻi, e ʻoluʻolu nō, e kōkua mai a e hoʻololi i nā ʻatikala ma ʻaneʻi, a pono e haʻi aku i kou mau hoa aloha e pili ana i ka Wikipikia Hawaiʻi. E ola mau nō ka ʻōlelo Hawaiʻi a mau loa aku.'),
('IGBO', 'Chineke bụ aha ọzọ ndï omenala Igbo kpọro Chukwu. Mgbe ndị bekee bịara, ha mee ya nke ndi Christian. N\'echiche ndi ekpere chi Omenala Ndi Igbo, Christianity, Judaism, ma Islam, Chineke nwere ọtụtụ utu aha, ma nwee nanị otu aha. Ụzọ abụọ e si akpọ aha ahụ bụ Jehovah ma Ọ bụ Yahweh. Na ọtụtụ Akwụkwọ Nsọ, e wepụla aha Chineke ma jiri utu aha bụ Onyenwe Anyị ma ọ bụ Chineke dochie ya. Ma mgbe e dere akwụkwọ nsọ, aha ahụ bụ Jehova pụtara n’ime ya, ihe dị ka ugboro pụkụ asaa(7,000).'),
('INDONESIAN', 'Geng: Pengembaraan Bermula adalah film animasi 3D CGI pertama yang diproduksi di Malaysia. Film ini dibuat oleh Les\' Copaque Production (LCP) dan dirilis di bioskop-bioskop seluruh Malaysia pada 12 Februari 2009. Film Geng pertama kali diluncurkan dalam sebuah acara peluncuran pada 11 September 2007 bersama dengan serial animasi pendek Upin & Ipin yang berhubungan dengan film tersebut. Pembuatan film ini didukung oleh berbagai pihak seperti Kementerian Sains, Teknologi dan Inovasi Malaysia (MOSTI) dengan memberi bantuan berupa dana sebesar RM1 juta.'),
('INTERLINGUA', ' super le sitos que tu visita isto es necessari pro render disponibile alcun functionalitates del barra de utensiles a fin que nos pote monstrar informationes ulterior super un sito le barra de utensiles debe dicer a nos le'),
('INTERLINGUE', ' abhorre exceptiones in li derivation plu cardinal por un l i es li regularità del flexion conjugation ples comparar latino sine flexione e li antiqui projectes naturalistic queles have quasi null regules de derivation ma si on nu examina li enunciationes'),
('INUPIAK', ' kuubuuraqabniqsuq ataruamik colville mi aasii tavrani siku kilaabman sulukpaukkat makua niksisugrufagivut tavrani sunaimña atifa quaqqat ii quaqqat aasii ukiabmagu utiqhuta tamaufa utqiabvifñun aasiiñ tatpaaffaqapta tuvaaqatinifarufa aasiiñ'),
('KASHMIRI', 'پیٹھ سٮ۪اگت! آکھ آزاد گیانکوشٖٔ ہۄ کٲنٛسِہ تِہ ہٮ۪کُن اٮ۪ڑِٹ۔ تور چھک ٢٢٨ مَضموٗنن منز کٲشُر ویکیپیٖڈیا چھُ آکھ مَنصوٗبہٕ خٲطرٕ بنَاوُن آکھ گیانکوشٖٔ سۭتۍ آزاد منز 280 زَبانَن تٔمِس یۄسہٕ ژٕ سۭتۍ تُہُنٛد گیان ہُرٮ۪ر کَرُن ہٮ۪کُن'),
('KAZAKH', ' ﺎ ﻗﻴﺎﻧﺎﺕ ﺑﻮﻟﻤﺎﻳﺪﻯ ﺑﯘﻝ ﭘﺮﻭﺗﺴﻪﺳﯩﻦ ﻳﺎﻋﻨﻲ ﻗﺎﻻ ﻭﻣﯩﺮﯨﻨﺪﻩ ﻗﺎﺯﺍﻕ ء ﺗﯩﻠﯩﻨﯩﯔ ﻗﻮﻟﺪﺍﻧﯩﻠﻤﺎﯞﻯ ﻗﺎﺯﺍﻕ ﺟﻪﺭﯨﻨﺪﻩ'),
('KAZAKH', ' а билердің өзіне рұқсат берілмеген егер халық талап етсе ғана хан келісім берген өздеріңіз білесіздер қр қыл мыс тық кодексінде жазаның'),
('KHASI', ' kaba jem jai sa sngap thuh ia ki bynta ba sharum naka sohbuin jong phi nangta sa pynhiar ia ka kti kadiang jong phi sha ka krung jong phi bad da kaba pyndonkam kumjuh ia ki shympriahti jong phi sa sngap thuh shapoh ka tohtit jong phi pyndonkam ia kajuh ka'),
('KURDISH', ' بۆ به ڕێوه بردنی نامه ی که دێتن ڕاسته وخۆ ڕه وان بکه نامه کانی گ مایل بۆ حسابی پۆستێکی تر هێنانی په یوه ندکاره کان له'),
('KYRGYZ', ' جانا انى تانۇۇ ۇلۇتۇن تانۇۇ قىرعىزدى بئلۉۉ دەگەندىك اچىق ايتساق ماناستى تاانىعاندىق ۅزۉڭدۉ تاانىعاندىق بۉگۉن تەما جۉكتۅمۅ ق ى رع ى ز ت ى ل ى'),
('KYRGYZ', ' агай эле оболу мен садыбакас аганын өзү менен эмес эмгектери менен тааныштым жылдары ташкенде өзбекстан илимдер академиясынын баяны'),
('LATIN', ' a deo qui enim nocendi causa mentiri solet si iam consulendi causa mentiatur multum profecit sed aliud est quod per se ipsum laudabile proponitur aliud quod in deterioris comparatione praeponitur aliter enim gratulamur cum sanus est homo aliter cum melius'),
('LINGALA', ' abakisamaki ndenge esengeli moyebami abongisamaki solo mpenza kombo ya moyebami elonguamaki kombo ya bayebami elonguamaki kombo eleki molayi po na esika epesameli limbisa esika ya kotia ba kombo esuki boye esengeli olimbola ndako na yo ya mikanda kombo'),
('LUXEMBOURGISH', ' a gewerkschaften och hei gefuerdert dir dammen an dir häre vun de gewerkschaften denkt un déi aarm wann der äer fuerderunge formuléiert d sechst congés woch an aarbechtszäitverkierzung hëllefen hinnen net d unhiewe vun de steigerungssäz bei de'),
('MALAGASY', ' amporisihin i ianao mba hijery ny dika teksta ranofotsiny an ity lahatsoratra ity tsy ilaina ny opérateur efa karohina daholo ny teny rehetra nosoratanao ampiasao anaovana dokambarotra i google telugu datin ny takelaka fikarohana sary renitakelak i'),
('MALAY', 'bilik sebelah berkata julai pada pm ladymariah hmm sume ni terpulang kepada individu mungkin anda bernasib baik selama ini dalam membeli hp yang bagus deli berkata julai pada pm walaupun bukan bahsa baku tp tetap bahasa melayu kan perubahan boleh dibuat'),
('MANX', ' and not ripe as i thought yn assyl yn shynnagh as yn lion the ass the fox and the lion va assyl as shynnagh ayns commee son nyn vendeilys as sauchys hie ad magh ayns y cheyll dy shelg cha row ad er gholl feer foddey tra veeit ad rish lion yn shynnagh'),
('MAORI', ' haere ki te kainga o o haere ki te kainga o o haere ki te kainga o te rapunga ahua o haere ki te kainga o ka tangohia he ki to rapunga kaore au mohio te tikanga whakatiki o te ra he whakaharuru te pai rapunga a te rapunga ahua a e kainga o nga awhina o te'),
('MAURITIAN_CREOLE', 'Anz dir mwa, Sa bann delo ki to trouve la, kot fam prostitie asize, samem bann pep, bann lafoul dimoun, bann nasion ek bann langaz. Sa dis korn ki to finn trouve, ansam avek bebet la, zot pou ena laenn pou prostitie la; zot pou pran tou seki li ena e met li touni, zot pou manz so laser e bril seki reste dan dife. Parski Bondie finn met dan zot leker proze pou realiz so plan. Zot pou met zot dakor pou sed zot pouvwar bebet la ziska ki parol Bondie fini realize.'),
('MONGOLIAN', ' а боловсронгуй болгох орон нутгийн ажил үйлсийг уялдуулж зохицуулах дүрэм журам боловсруулах орон нутгийн өмч хөрөнгө санхүүгийн'),
('NAURU', ' arcol obabakaen riringa itorere ibibokiei ababaro min kuduwa airumena baoin tokin rowiowet itiket keram damadamit eigirow etoreiy row keitsito boney ibingo itsiw dorerin naoerodelaporte s nauruan dictionary a c a c d g h o p s t y aiquen ion eins aiquen'),
('NORWEGIAN_N', ' a for verktylina til å hjelpa deg å nå oss merk at pagerank syninga ikkje automatisk kjem til å henta inn informasjon frå sider med argument dvs frå sider med eit i en dersom datamaskina di er plassert bak ein mellomtenar for vevsider kan det verka'),
('NYANJA', 'Boma ndi gawo la dziko lomwe linapangidwa ndi cholinga chothandiza ntchito yolamulira. Kuŵalako kulikuunikabe mandita, Edipo nyima unalephera kugonjetsa kuŵalako.'),
('OCCITAN', ' Pasmens, la classificacion pus admesa uei (segon Juli Ronjat e Pèire Bèc) agropa lei parlars deis Aups dins l\'occitan vivaroaupenc e non dins lo dialècte provençau.'),
('OROMO', ' afaan katalaa bork bork bork hiikaa jira hin argamne gareen barbaadame hin argamne gargarsa qube en gar bayee jira garee walitti firooman gareewwan walitti firooman fuula web akka tartiiba qubeetiin agarsiisi akka tartiiba qubeetiin agarsiisaa jira akka'),
('PASHTO', ' اتو مستقل رياست جوړ شو او د پخواني ادبي انجمن څانګې ددې رياست جز شوی او ددې انجمن د ژبې مديريت د پښتو ټولنې په لوی مديريت واوښت لوی مدير يې د'),
('PEDI', 'Bophara bja Asia ekaba 8.6% bja lefase goba 29.4% bja naga ya lefase (ntle le mawatle). Asia enale badudu bao bakabago dimillione millione tše nne (4 billion) yeo e bago 60% ya badudi ba lefase ka bophara. A bapolelwa rena sefapanong mehleng ya Pontius Pilatus. A hlokofatšwa, A bolokwa, A tsoga ka letšatši la boraro, ka mo mangwalo a bolelago ka gona, a rotogela magodimong, '),
('QUECHUA', ' is t ipanakunatapis rikuchinankupaq qanpa simiykipi noqaykoqpa uya jllanakunamanta kunan jamoq simikunaman qelqan tiyan watukuy qpa uyata qanpa llaqtaykipi llank anakuna simimanta yanapakuna simimanta mayqen llaqtallapis kay simimanta t ijray qpa qelqa'),
('RHAETO_ROMANCE', ' Cur ch’il chantun Turitg ha dà il dretg da votar a las dunnas (1970) è ella vegnida elegida en il cussegl da vischnanca da Zumikon per la Partida liberaldemocratica svizra (PLD). Da 1974 enfin 1982 è ella stada presidenta da vischnanca da Zumikon. L’onn 1979 è Elisabeth Kopp vegnida elegida en il Cussegl naziunal e reelegida quatter onns pli tard cun in resultat da sur 100 000 vuschs. L’onn 1984 è ella daventada vicepresidenta da la PLD.'),
('RUNDI', ' ishaka mu ndero y abana bawe ganira n abigisha nimba hari ingorane izo ari zo zose ushobora gusaba kubonana n umwigisha canke kuvugana nawe kuri terefone inyuma y uko babarungikira urutonde rw amanota i muhira mu bisanzwe amashure aratumira abavyeyi'),
('SAMOAN', ' autu mea o lo totonu le e le minaomia matou te tuu i totonu i le faamatalaina o le suesuega i taimi uma mea o lo totonu fuafua i mea e tatau fa afoi tala mai le newsgroup mataupu fa afoi mai tala e ai le mataupu e ai totonu tusitala o le itu o faamatalaga'),
('SANGO', ' atâa na âkotta zo me lâkwê angbâ gï tarrango nî âkotta zo tî koddoro nî âde agbû tenne nî na kate töngana mbênî kotta kpalle tî nzönî dutï tî halëzo pëpe atâa sô âla lü gbâ tî ândya tî mâi na sahngo asâra gbâ tî'),
('SANSKRIT', ' ं क र्मणस् त स्य य त्कि ङ्चेह करो त्यय ं त स्माल् लोका त्पु नरै ति अस्मै लोका य क र्मण इ ति नु काम'),
('SANSKRIT', ' brahmā tatraivāntaradhīyata tataḥ saśiṣyo vālmīkir munir vismayam āyayau tasya śiṣyās tataḥ sarve jaguḥ ślokam imaṃ punaḥ muhur muhuḥ prīyamāṇāḥ prāhuś ca bhṛśavismitāḥ samākṣaraiś caturbhir yaḥ pādair gīto'),
('SCOTS', ' a gless an geordie runciman ower a gless an tamson their man preached a hale hoor aboot the glorious memories o forty three an backsliders an profane persons like esau an aboot jeroboam the son o nebat that gaed stravagin to anither kirk an made aa israel'),
('SESELWA', 'Sesel ou menm nou sel patri. Kot nou viv dan larmoni. Lazwa, lanmour ek lape. Nou remersye Bondye. Preserv labote nou pei. Larises nou losean. En leritaz byen presye. Pour boner nou zanfan. Reste touzour dan linite. Fer monte nou paviyon. Ansanm pou tou leternite. Koste Seselwa!'),
('SESOTHO', ' bang ba nang le thahasello matshwao a sehlooho thuto e thehilweng hodima diphetho ke tsela ya ho ruta le ho ithuta e totobatsang hantle seo baithuti ba lokelang ho se fihlella ntlhatheo eo e sebetsang ka yona ke ya hore titjhere o hlakisa pele seo'),
('SHONA', ' chete vanyori vanotevera vakabatsira kunyora zvikamu zvino kumba home tinyorere tsamba chikamu chakumbirwa hachina kuwanikwa chikamu ichi cheninge chakayiswa kuimwe nzvimbo mudhairekitori rino chimwe chikamu chopadhuze pane chinhu chatadza kushanda bad'),
('SINDHI', ' اضافو ٿي ٿيو پر اها خبر عثمان کي بعد پيئي ته سگريٽ ڇڪيندڙ مسلمان نه هو بلڪ هندو هو دڪان تي پهچي عثمان ڪسبت کولي گراهڪن جي سيرب لاهڻ شروع ڪئي پر'),
('SISWANT', ' bakhokhintsela yesikhashana bafake imininingwane ye akhawunti leliciniso kulelifomu nangabe akukafakwa imininingwane leliciniso imali lekhokhiwe angeke ifakwe kumkhokhintsela lofanele imininingwane ye akhawunti ime ngalendlela lelandzelako inombolo'),
('SOMALI', ' a oo maanta bogga koobaad ugu qoran yahey beesha caalamka laakiin si kata oo beesha caalamku ula guntato soomaaliya waxa aan shaki ku jirin in aakhirataanka dadka soomaalida oo kaliya ay yihiin ku soomaaliya ka saari kara dhibka ay ku jirto'),
('SUNDANESE', ' alus gampang deuih uhun im gmail obrolan ulah disimpen na koropak kuring simpen obrolan dina koropak kuring obrolan obrolan anjeun teu boga arsip obrolan slovak slovenia vietnam catalan czech estonia hindi lithuania romania tagalog thai turkish édit iber'),
('TAJIK', ' адолат ва инсондӯстиро бар фашизм нажодпарастӣ ва адоват тарҷеҳ додааст чоп кунед ба дигарон фиристед чоп кунед ба дигарон фиристед'),
('TATAR', 'ачарга да бирмәде чәт чәт килеп тора безнең абыйнымы олы абыйнымы эштән'),
('TATAR', ' alarnı eşkärtü proğramnarın eşläwen däwam itü tatar söylämen buldıru wä sizep alu sistemnarın eşläwen däwat itü häm başqalar yılnıñ mayında tatar internetı ictimağıy oyışması milli ts isemle berençe däräcäle häm tat'),
('TIBETAN', ' གང ནི ཀུན ལ སྦྱར པ དང ཅན ལྡན བདག པོའི སྒྲ ག ད བ ས ན མ པ ང འ ར ལ མཐའ མེད པ བདག པོའི སྒྲ ལ པ ཉིད དོ མ མི མིན'),
('TIGRINYA', ' ሃገር ተረፎም ዘለዉ ኢትዮጵያውያን ኣብቲ ምስ ኢትዮጵያ ዝዳውብ ኣውራጃ ደቡብ ንኽነብሩ ኣይፍቀደሎምን እዩ ካብ ሃገር ንኽትወጽእ ዜጋ ኹን ወጻእተኛ ናይ'),
('TONGA', ' a ke kumi oku ikai ke ma u vakai ki hono hokohoko faka alafapeti api pe ko e uluaki peesi a ho o fekumi faka malatihi fekumi ki he lea oku fakaha atu pe ko ha fonua fekumi ki he fekumi ki he peesi oku ngaahi me a oku sai imisi alu ki he ki he ulu aki'),
('TSONGA', ' a ku na timhaka leti nga ta vulavuriwa na google google yi hlonipha yi tlhela yi sirheleta vanhu hinkwavo lava tirhisaka google toolbar ku dyondza hi vusireleli eka system ya hina hi kombela u hlaya vusireleli bya hina eka toolbar mbulavulo wu tshikiwile'),
('TSWANA', ' go etela batla ditsebe tsa web tse di nang le le batla ditsebe tse di golaganya le tswang mo leka go batla web yotlhe batla mo web yotlhe go bona home page ya google batla mo a o ne o batla gore a o ne o batla ditsebe tsa bihari batla mo re maswabi ga go'),
('TURKMEN', ' айдянларына ынанярмыка эхли боз мейданлары сурулип гутарылан тебигы ота гарып гумлукларда миллиондан да артыкмач ири шахлы малы миллиона'),
('TURKMEN', ' akyllylyk çyn söýgi üçin böwet däl de tebigylykdyr duýgularyň gödeňsiligi aç açanlygy bahyllygy söýgini betnyşanlyk derejesine düşürýändir söýeni söý söýmedige süýkenme özüni söýmeýändigini görmek ýigit üçin uly'),
('AKAN', ' amammui tumidifo no bɛtow ahyɛ atoro som so mpofirim na wɔasɛe no pasaa ma ayɛ nwonwa dɛn na ɛbɛka wɔn ma wɔayɛ saa bible no ma ho mmuae wɔ adiyisɛm nhoma no mu sɛ onyankopɔn na ɔde hyɛɛ wɔn komam sɛ wɔmma ne nsusuwii mmra mu'),
('UIGHUR', ' ئالەملەرنىڭ پەرۋەردىگارىدىن تىلەيمەن سىلەر بۇ يەرلەردە باغچىلاردىن بۇلاقلاردىن زىرائەتلەردىن يۇمشاق پىشقان خورمىلاردىن بەھرىمەن بولۇپ'),
('UIGHUR', ' а башлиди әмма бу қетимқи канада мәтбуатлириниң хәвәрлиридә илгирикидәк хитай һөкүмәт мәтбуатлиридин нәқил алидиған вә уни көчүрүп'),
('UZBEK', ' آرقلی بوتون سیاسی حزب و گروه لرفعالیتیگه رخصت بیرگن اخبارات واسطه لری شو ییل مدتیده مثال سیز ترقی تاپکن و اهالی نینگ اقتصادی وضعیتی اوتمیش'),
('UZBEK', ' а гапирадиган бўлсак бунинг иккита йўли бор биринчиси мана шу қуриган сатҳини қумликларни тўхтатиш учун экотизимни мустаҳкамлаш қумга'),
('UZBEK', ' abadiylashtirildi aqsh ayol prezidentga tayyormi markaziy osiyo afg onistonga qanday yordam berishi mumkin ukrainada o zbekistonlik muhojirlar tazyiqdan shikoyat qilmoqda gruziya va ukraina hozircha natoga qabul qilinmaydi afg oniston o zbekistonni g'),
('VENDA', 'Vho ṱanganedzwa kha Wikipedia nga tshiVenḓa. Vhadivhi vha manwalo a TshiVenda vha talusa divhazwakale na vhubvo ha Vhavenda ngau fhambana. Vha tikedza mbuno dzavho uya nga mawanwa a thoduluso dze vha ita. Vhanwe vha vhatodulusi vhari Vhavenda vho tumbuka Afrika vhukati vha tshimbila vha tshiya Tshipembe ha Afrika, Rhodesia hune ha vho vhidzwa Zimbagwe namusi.'),
('VOLAPUK', ' brefik se volapükavol nüm balid äpubon ün dü lif lölik okas redakans älaipübons gasedi at nomöfiko äd ai mu kuratiko pläo timü koup nedäna fa ns deutän kü päproibon fa koupanef me gased at ästeifülom ad propagidön volapüki as sam ün'),
('WARAY_PHILIPPINES', 'Amo ini an balay han Winaray o Binisaya nga Lineyte-Samarnon nga Wikipedia, an libre ngan gawasnon nga ensayklopedya nga bisan hin-o puyde magliwat o mag-edit. An Wikipedia syahan gintikang ha Iningles nga yinaknan han tuig 2001. Ini nga bersyon Winaray gintikang han ika-25 han Septyembre 2005 ngan ha yana mayda 514,613 nga artikulo. Kon karuyag niyo magsari o magprobar, pakadto ha . An Gastrotheca pulchra[2] in uska species han Anura nga ginhulagway ni Ulisses Caramaschi ngan Rodrigues hadton 2007. An Gastrotheca pulchra in nahilalakip ha genus nga Gastrotheca, ngan familia nga Hemiphractidae.[3][4] Ginklasipika han IUCN an species komo kulang hin datos.[1] Waray hini subspecies nga nakalista.[3]'),
('WOLOF', ' am ak dëgg dëggam ak gëm aji bind ji te gëstu ko te jëfandikoo tegtalu xel ci saxal ko sokraat nag jëfandikoo woon na xeltu ngir tas jikko yu rafet ci biir nit ñi ak dëggu ak soppante sokraat nag ñëw na mook aflaton platon sukkandiku ci ñaari'),
('XHOSA', ' a naynga zonke futhi libhengezwa kwiwebsite yebond yasemzantsi afrika izinga elisebenzayo xa usenza olu tyalo mali liya kusebenza de liphele ixesha lotyalo mali lwakho inzala ihlawulwa rhoqo emva kweenyanga ezintandathu ngomhla wamashumi amathathu ananye'),
('X_KLINGON', ' a ghuv bid soh naq jih lodni yisov chich wo vamvo qeylis lunge pu chah povpu vodleh a dah ghah cho ej dah wo che pujwi bommu tlhegh darinmohlahchu pu majqa horey so lom qa ip quv law may vad suvtahbogh wa sanid utlh quv pus datu pu a vitu chu pu johwi tar'),
('X_PIG_LATIN', ' away ackupbay editcray ardcay ybay isitingvay ouryay illingbay eferencespray agepay orway isitvay ethay adwordsway elphay entrecay orfay oremay etailsday adwordsway ooglegay omcay upportsay'),
('YORUBA', ' abinibi han ikawe alantakun le ni opolopo ede abinibi ti a to lesese bi eniyan to fe lo se fe lati se atunse jowo mo pe awon oju iwe itakunagbaye miran ti ako ni oniruru ede abinibi le faragba nipa atunse ninu se iwadi blogs ni ori itakun agbaye ti e ba'),
('ZHUANG', ' dih yinzminz ndaej daengz bujbienq youjyau dih cingzyin caeuq cinhingz diuz daihit boux boux ma daengz lajmbwn couh miz cwyouz cinhyenz caeuq genzli bouxboux bingzdaengj gyoengq vunz miz lijsing caeuq liengzsim wngdang daih gyoengq de lumj beixnuengx'),
('ZULU', ' ana engu uma inkinga iqhubeka siza ubike kwi isexwayiso ngenxa yephutha lomlekeleli sikwazi ukubuyisela emuva kuphela imiphumela engaqediwe ukuthola imiphumela eqediwe zama ukulayisha kabusha leli khasi emizuzwini engu uma inkinga iqhubeka siza uthumele'),
# This is just the "version marker":
('SLOVENIAN', 'qpdbmrmxyzptlkuuddlrlrbas las les qpdbmrmxyzptlkuuddlrlrbas el la qpdbmrmxyzptlkuuddlrlrbas'),
)
class TestCLD(unittest.TestCase):
langsSeen = set()
fullLangsSeen = set()
def runOne(self, expectedLangName, s, doFull = False):
if VERBOSE:
print('')
print('Test: %s [%d bytes]' % (expectedLangName, len(s)))
failed = False
for isPlainText in False, True:
if doFull:
detector = cld2full.detect
else:
detector = cld2.detect
isReliable, textBytesFound, details = detector(s, isPlainText=isPlainText)
if len(details) > 0:
detectedLangName, detectedLangeCode = details[0][:2]
if VERBOSE:
print(' detected: %s' % detectedLangName)
print(' reliable: %s' % (isReliable != 0))
print(' textBytes: %s' % textBytesFound)
print(' details: %s' % str(details))
try:
self.assertEqual(expectedLangName, detectedLangName, '%s != %s; details: %s' % (detectedLangName, expectedLangName, str(details)))
except:
traceback.print_exc()
failed = True
break
if doFull:
self.fullLangsSeen.add(detectedLangName)
else:
self.langsSeen.add(detectedLangName)
else:
try:
self.fail('no language detected; expected %s' % expectedLangName)
except:
traceback.print_exc()
failed = True
break
if failed:
self.fail('some languages were wrong')
def test_basic(self):
for lang, text in testData:
self.runOne(lang, text)
for lang, text in fullTestData:
self.runOne(lang, text, True)
# End of per-language tests; start tests for specific functions:
def test_vectors(self):
for detector in cld2, cld2full:
for lang, text in testData:
isReliable, textBytesFound, details, vectors = detector.detect(text, returnVectors=True)
self.assertTrue(textBytesFound > 0)
if text == fr_en_Latn:
self.assertEqual(3, len(vectors))
self.assertEqual(('en', 'fr', 'en'), tuple(x[3] for x in vectors))
def test_encoding_hint(self):
for detector in cld2, cld2full:
for lang, text in testData:
for encoding in cld2.ENCODINGS:
detector.detect(text, hintEncoding=encoding)
def test_language_hint(self):
for detector in cld2, cld2full:
for lang, text in testData:
for langHint in cld2.LANGUAGES:
detector.detect(text, hintLanguage=langHint[0])
detector.detect(text, hintLanguage=langHint[1])
def test_top_level_domain_hint(self):
for detector in cld2, cld2full:
for lang, text in testData:
detector.detect(text, hintTopLevelDomain='edu')
detector.detect(text, hintTopLevelDomain='com')
detector.detect(text, hintTopLevelDomain='id')
def test_language_http_headers_hint(self):
for detector in cld2, cld2full:
for lang, text in testData:
detector.detect(text, hintLanguageHTTPHeaders='mi,en')
def test_debug_flags(self):
for detector in cld2, cld2full:
detector.detect(fr_en_Latn, debugScoreAsQuads=True)
detector.detect(fr_en_Latn, debugHTML=True)
detector.detect(fr_en_Latn, debugHTML=True, debugCR=True)
detector.detect(fr_en_Latn, debugHTML=True, debugQuiet=True)
detector.detect(fr_en_Latn, debugHTML=True, debugVerbose=True)
detector.detect(fr_en_Latn, debugHTML=True, debugEcho=True)
if __name__ == '__main__':
try:
unittest.main()
finally:
# Confirm that cld2.DETECTED_LANGUAGES == all languages detected by
# the test cases:
for lang in cld2.DETECTED_LANGUAGES:
# Raises KeyError if lang was never detected by the test:
TestCLD.langsSeen.remove(lang)
# Confirm that no languages detected by the test were not listed in cld2.DETECTED_LANGUAGES:
if len(TestCLD.langsSeen) != 0:
raise RuntimeError('unexpected additional languages were detected: %s' % TestCLD.langsSeen)
if False:
l = list(TestCLD.fullLangsSeen)
l.sort()
for x in l:
print('PyTuple_SET_ITEM(detLangs, upto++, PyUnicode_FromString("%s"));' % x)
# Confirm that cld2full.DETECTED_LANGUAGES == all languages detected by
# the test cases:
#print('FULL %d: %s' % (len(TestCLD.fullLangsSeen), ', '.join(TestCLD.fullLangsSeen)))
for lang in cld2full.DETECTED_LANGUAGES:
# Raises KeyError if lang was never detected by the test:
TestCLD.fullLangsSeen.remove(lang)
# Confirm that no languages detected by the test were not listed in cld2full.DETECTED_LANGUAGES:
if len(TestCLD.fullLangsSeen) != 0:
raise RuntimeError('unexpected additional languages were detected: %s' % TestCLD.fullLangsSeen)
| Python |
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generates encodings.cc from ../../public/encodings.h
import re
s = open('../../public/encodings.h').read()
r = re.compile('\s*(.*?)\s+=\s*(\d+),')
l = []
for line in s.split('\n'):
line = line.strip()
m = r.match(line)
if m is not None:
l.append((m.group(1), int(m.group(2))))
print()
print('''struct cld_encoding {
const char# name;
CLD2::Encoding encoding;
};''')
print('const cld_encoding cld_encoding_info[] = {')
for k, v in l:
print(' {"%s", CLD2::%s},' % (k, k))
print('};')
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
from xml.sax.saxutils import escape
import sys, os
from optparse import OptionParser
from androguard.core.androgen import Androguard
from androguard.core.analysis import analysis
option_0 = { 'name' : ('-i', '--input'), 'help' : 'filename input', 'nargs' : 1 }
option_1 = { 'name' : ('-o', '--output'), 'help' : 'filename output of the xgmml', 'nargs' : 1 }
option_2 = { 'name' : ('-f', '--functions'), 'help' : 'include function calls', 'action' : 'count' }
option_3 = { 'name' : ('-e', '--externals'), 'help' : 'include extern function calls', 'action' : 'count' }
option_4 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_4]
METHODS_ID = {}
EXTERNAL_METHODS_ID = {}
NODES_ID = {}
EDGES_ID = {}
NODE_GRAPHIC = {
"classic" : {
"h" : 20.0,
"w" : 20.0,
"type" : "ELLIPSE",
"width" : 1,
"fill" : "#e1e1e1",
"outline" : "#000000",
},
"extern" : {
"h" : 20.0,
"w" : 20.0,
"type" : "ELLIPSE",
"width" : 1,
"fill" : "#ff8c00",
"outline" : "#000000",
}
}
EDGE_GRAPHIC = {
"cfg" : {
"width" : 2,
"fill" : "#0000e1",
},
"fcg" : {
"width" : 3,
"fill" : "#9acd32",
},
"efcg" : {
"width" : 3,
"fill" : "#808000",
}
}
def get_node_name(method, bb) :
return "%s-%s-%s" % ( method.get_class_name(), escape(bb.name), escape(method.get_descriptor()) )
def export_xgmml_cfg(g, fd) :
method = g.get_method()
name = method.get_name()
class_name = method.get_class_name()
descriptor = method.get_descriptor()
if method.get_code() != None :
size_ins = method.get_code().get_length()
for i in g.basic_blocks.get() :
fd.write("<node id=\"%d\" label=\"%s\">\n" % (len(NODES_ID), get_node_name(method, i)))
fd.write("<att type=\"string\" name=\"classname\" value=\"%s\"/>\n" % (escape(class_name)))
fd.write("<att type=\"string\" name=\"name\" value=\"%s\"/>\n" % (escape(name)))
fd.write("<att type=\"string\" name=\"descriptor\" value=\"%s\"/>\n" % (escape(descriptor)))
fd.write("<att type=\"integer\" name=\"offset\" value=\"%d\"/>\n" % (i.start))
cl = NODE_GRAPHIC["classic"]
width = cl["width"]
fill = cl["fill"]
# No child ...
if i.childs == [] :
fill = "#87ceeb"
if i.start == 0 :
fd.write("<att type=\"string\" name=\"node.label\" value=\"%s\\n%s\"/>\n" % (escape(name), i.get_instructions()[-1].get_name()))
width = 3
fill = "#ff0000"
METHODS_ID[ class_name + name + descriptor ] = len(NODES_ID)
else :
fd.write("<att type=\"string\" name=\"node.label\" value=\"0x%x\\n%s\"/>\n" % (i.start, i.get_instructions()[-1].get_name()))
size = 0
for tmp_ins in i.get_instructions() :
size += (tmp_ins.get_length() / 2)
h = ((size / float(size_ins)) * 20) + cl["h"]
fd.write("<graphics type=\"%s\" h=\"%.1f\" w=\"%.1f\" width=\"%d\" fill=\"%s\" outline=\"%s\">\n" % ( cl["type"], h, h, width, fill, cl["outline"]))
fd.write("</graphics>\n")
fd.write("</node>\n")
NODES_ID[ class_name + i.name + descriptor ] = len(NODES_ID)
for i in g.basic_blocks.get() :
for j in i.childs :
if j[-1] != None :
label = "%s (cfg) %s" % (get_node_name(method, i), get_node_name(method, j[-1]))
id = len(NODES_ID) + len(EDGES_ID)
fd.write( "<edge id=\"%d\" label=\"%s\" source=\"%d\" target=\"%d\">\n" % (id, label, NODES_ID[ class_name + i.name + descriptor ], NODES_ID[ class_name + j[-1].name + descriptor ]) )
cl = EDGE_GRAPHIC["cfg"]
fd.write("<graphics width=\"%d\" fill=\"%s\">\n" % (cl["width"], cl["fill"]) )
fd.write("</graphics>\n")
fd.write("</edge>\n")
EDGES_ID[ label ] = id
def export_xgmml_fcg(a, x, fd) :
classes = a.get_classes_names()
# Methods flow graph
for m, _ in x.get_tainted_packages().get_packages() :
paths = m.get_methods()
for j in paths :
if j.get_method().get_class_name() in classes and m.get_info() in classes :
if j.get_access_flag() == analysis.TAINTED_PACKAGE_CALL :
t = m.get_info() + j.get_name() + j.get_descriptor()
if t not in METHODS_ID :
continue
bb1 = x.get_method( j.get_method() ).basic_blocks.get_basic_block( j.get_idx() )
node1 = get_node_name(j.get_method(), bb1) + "@0x%x" % j.get_idx()
node2 = "%s-%s-%s" % (m.get_info(), escape(j.get_name()), escape(j.get_descriptor()))
label = "%s (fcg) %s" % (node1, node2)
if label in EDGES_ID :
continue
id = len(NODES_ID) + len(EDGES_ID)
fd.write( "<edge id=\"%d\" label=\"%s\" source=\"%d\" target=\"%d\">\n" % (id,
label,
NODES_ID[ j.get_method().get_class_name() + bb1.name + j.get_method().get_descriptor() ],
METHODS_ID[ m.get_info() + j.get_name() + j.get_descriptor() ]) )
cl = EDGE_GRAPHIC["fcg"]
fd.write("<graphics width=\"%d\" fill=\"%s\">\n" % (cl["width"], cl["fill"]) )
fd.write("</graphics>\n")
fd.write("</edge>\n")
EDGES_ID[ label ] = id
def export_xgmml_efcg(a, x, fd) :
classes = a.get_classes_names()
# Methods flow graph
for m, _ in x.get_tainted_packages().get_packages() :
paths = m.get_methods()
for j in paths :
if j.get_method().get_class_name() in classes and m.get_info() not in classes :
if j.get_access_flag() == analysis.TAINTED_PACKAGE_CALL :
t = m.get_info() + j.get_name() + j.get_descriptor()
if t not in EXTERNAL_METHODS_ID :
fd.write("<node id=\"%d\" label=\"%s\">\n" % (len(NODES_ID), escape(t)))
fd.write("<att type=\"string\" name=\"classname\" value=\"%s\"/>\n" % (escape(m.get_info())))
fd.write("<att type=\"string\" name=\"name\" value=\"%s\"/>\n" % (escape(j.get_name())))
fd.write("<att type=\"string\" name=\"descriptor\" value=\"%s\"/>\n" % (escape(j.get_descriptor())))
cl = NODE_GRAPHIC["extern"]
fd.write("<att type=\"string\" name=\"node.label\" value=\"%s\\n%s\\n%s\"/>\n" % (escape(m.get_info()), escape(j.get_name()), escape(j.get_descriptor())))
fd.write("<graphics type=\"%s\" h=\"%.1f\" w=\"%.1f\" width=\"%d\" fill=\"%s\" outline=\"%s\">\n" % ( cl["type"], cl["h"], cl["h"], cl["width"], cl["fill"], cl["outline"]))
fd.write("</graphics>\n")
fd.write("</node>\n")
NODES_ID[ t ] = len(NODES_ID)
EXTERNAL_METHODS_ID[ t ] = NODES_ID[ t ]
bb1 = x.get_method( j.get_method() ).basic_blocks.get_basic_block( j.get_idx() )
node1 = get_node_name(j.get_method(), bb1) + "@0x%x" % j.get_idx()
node2 = "%s-%s-%s" % (m.get_info(), escape(j.get_name()), escape(j.get_descriptor()))
label = "%s (efcg) %s" % (node1, node2)
if label in EDGES_ID :
continue
id = len(NODES_ID) + len(EDGES_ID)
fd.write( "<edge id=\"%d\" label=\"%s\" source=\"%d\" target=\"%d\">\n" % (id,
label,
NODES_ID[ j.get_method().get_class_name() + bb1.name + j.get_method().get_descriptor() ],
EXTERNAL_METHODS_ID[ m.get_info() + j.get_name() + j.get_descriptor() ]) )
cl = EDGE_GRAPHIC["efcg"]
fd.write("<graphics width=\"%d\" fill=\"%s\">\n" % (cl["width"], cl["fill"]) )
fd.write("</graphics>\n")
fd.write("</edge>\n")
EDGES_ID[ label ] = id
def export_apps_to_xgmml( input, output, fcg, efcg ) :
a = Androguard( [ input ] )
fd = open(output, "w")
fd.write("<?xml version='1.0'?>\n")
fd.write("<graph label=\"Androguard XGMML %s\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns1=\"http://www.w3.org/1999/xlink\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns=\"http://www.cs.rpi.edu/XGMML\" directed=\"1\">\n" % (os.path.basename(input)))
for vm in a.get_vms() :
x = analysis.VMAnalysis( vm )
# CFG
for method in vm.get_methods() :
g = x.get_method( method )
export_xgmml_cfg(g, fd)
if fcg :
export_xgmml_fcg(vm, x, fd)
if efcg :
export_xgmml_efcg(vm, x, fd)
fd.write("</graph>")
fd.close()
def main(options, arguments) :
if options.input != None and options.output != None :
export_apps_to_xgmml( options.input, options.output, options.functions, options.externals )
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012/2013, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import shutil
import sys
import os
import re
from optparse import OptionParser
from androguard.core.androgen import Androguard
from androguard.core import androconf
from androguard.core.analysis import analysis
from androguard.core.bytecodes import dvm
from androguard.core.bytecode import method2dot, method2format
from androguard.decompiler import decompiler
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use this filename', 'nargs' : 1 }
option_1 = { 'name' : ('-o', '--output'), 'help' : 'base directory to output all files', 'nargs' : 1 }
option_2 = { 'name' : ('-d', '--decompiler'), 'help' : 'choose a decompiler', 'nargs' : 1 }
option_3 = { 'name' : ('-j', '--jar'), 'help' : 'output jar file', 'action' : 'count' }
option_4 = { 'name' : ('-f', '--format'), 'help' : 'write the method in specific format (png, ...)', 'nargs' : 1 }
option_5 = { 'name' : ('-l', '--limit'), 'help' : 'limit analysis to specific methods/classes by using a regexp', 'nargs' : 1}
option_6 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3, option_4, option_5, option_6]
def valid_class_name(class_name):
if class_name[-1] == ";":
return class_name[1:-1]
return class_name
def create_directory(class_name, output):
output_name = output
if output_name[-1] != "/":
output_name = output_name + "/"
pathdir = output_name + class_name
try:
if not os.path.exists(pathdir):
os.makedirs(pathdir)
except OSError:
# FIXME
pass
def export_apps_to_format(filename, a, output, methods_filter=None, jar=None, decompiler_type=None, format=None):
print "Dump information %s in %s" % (filename, output)
if not os.path.exists(output):
print "Create directory %s" % output
os.makedirs(output)
else:
print "Clean directory %s" % output
androconf.rrmdir(output)
os.makedirs(output)
methods_filter_expr = None
if methods_filter:
methods_filter_expr = re.compile(methods_filter)
output_name = output
if output_name[-1] != "/":
output_name = output_name + "/"
dump_classes = []
for vm in a.get_vms():
print "Analysis ...",
sys.stdout.flush()
vmx = analysis.VMAnalysis(vm)
print "End"
print "Decompilation ...",
sys.stdout.flush()
if not decompiler_type:
vm.set_decompiler(decompiler.DecompilerDAD(vm, vmx))
elif decompiler_type == "dex2jad":
vm.set_decompiler(decompiler.DecompilerDex2Jad(vm,
androconf.CONF["PATH_DEX2JAR"],
androconf.CONF["BIN_DEX2JAR"],
androconf.CONF["PATH_JAD"],
androconf.CONF["BIN_JAD"],
androconf.CONF["TMP_DIRECTORY"]))
elif decompiler_type == "dex2winejad":
vm.set_decompiler(decompiler.DecompilerDex2WineJad(vm,
androconf.CONF["PATH_DEX2JAR"],
androconf.CONF["BIN_DEX2JAR"],
androconf.CONF["PATH_JAD"],
androconf.CONF["BIN_WINEJAD"],
androconf.CONF["TMP_DIRECTORY"]))
elif decompiler_type == "ded":
vm.set_decompiler(decompiler.DecompilerDed(vm,
androconf.CONF["PATH_DED"],
androconf.CONF["BIN_DED"],
androconf.CONF["TMP_DIRECTORY"]))
elif decompiler_type == "dex2fernflower":
vm.set_decompiler(decompiler.DecompilerDex2Fernflower(vm,
androconf.CONF["PATH_DEX2JAR"],
androconf.CONF["BIN_DEX2JAR"],
androconf.CONF["PATH_FERNFLOWER"],
androconf.CONF["BIN_FERNFLOWER"],
androconf.CONF["OPTIONS_FERNFLOWER"],
androconf.CONF["TMP_DIRECTORY"]))
else:
raise("invalid decompiler !")
print "End"
if options.jar:
print "jar ...",
filenamejar = decompiler.Dex2Jar(vm,
androconf.CONF["PATH_DEX2JAR"],
androconf.CONF["BIN_DEX2JAR"],
androconf.CONF["TMP_DIRECTORY"]).get_jar()
shutil.move(filenamejar, output + "classes.jar")
print "End"
for method in vm.get_methods():
if methods_filter_expr:
msig = "%s%s%s" % (method.get_class_name(),
method.get_name(),
method.get_descriptor())
if not methods_filter_expr.search(msig):
continue
filename_class = valid_class_name(method.get_class_name())
create_directory(filename_class, output)
print "Dump %s %s %s ..." % (method.get_class_name(),
method.get_name(),
method.get_descriptor()),
filename_class = output_name + filename_class
if filename_class[-1] != "/":
filename_class = filename_class + "/"
descriptor = method.get_descriptor()
descriptor = descriptor.replace(";", "")
descriptor = descriptor.replace(" ", "")
descriptor = descriptor.replace("(", "-")
descriptor = descriptor.replace(")", "-")
descriptor = descriptor.replace("/", "_")
filename = filename_class + method.get_name() + descriptor
if len(method.get_name() + descriptor) > 250:
all_identical_name_methods = vm.get_methods_descriptor(method.get_class_name(), method.get_name())
pos = 0
for i in all_identical_name_methods:
if i.get_descriptor() == method.get_descriptor():
break
pos += 1
filename = filename_class + method.get_name() + "_%d" % pos
buff = method2dot(vmx.get_method(method))
if format:
print "%s ..." % format,
method2format(filename + "." + format, format, None, buff)
if method.get_class_name() not in dump_classes:
print "source codes ...",
current_class = vm.get_class(method.get_class_name())
current_filename_class = valid_class_name(current_class.get_name())
create_directory(filename_class, output)
current_filename_class = output_name + current_filename_class + ".java"
fd = open(current_filename_class, "w")
fd.write(current_class.get_source())
fd.close()
dump_classes.append(method.get_class_name())
print "bytecodes ...",
bytecode_buff = dvm.get_bytecodes_method(vm, vmx, method)
fd = open(filename + ".ag", "w")
fd.write(bytecode_buff)
fd.close()
print
def main(options, arguments):
if options.input != None and options.output != None:
a = Androguard([options.input])
export_apps_to_format(options.input, a, options.output, options.limit, options.jar, options.decompiler, options.format)
elif options.version != None:
print "Androdd version %s" % androconf.ANDROGUARD_VERSION
else:
print "Please, specify an input file and an output directory"
if __name__ == "__main__":
parser = OptionParser()
for option in options:
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
#!/usr/bin/env python
# This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Androguard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
import sys, os
from optparse import OptionParser
from androguard.core import androconf
from androguard.core.bytecodes import apk
from androguard.core.analysis import risk
option_0 = { 'name' : ('-i', '--input'), 'help' : 'file : use these filenames', 'nargs' : 1 }
option_1 = { 'name' : ('-m', '--method'), 'help' : 'perform analysis of each method', 'action' : 'count' }
option_2 = { 'name' : ('-d', '--directory'), 'help' : 'directory : use this directory', 'nargs' : 1 }
option_3 = { 'name' : ('-v', '--version'), 'help' : 'version of the API', 'action' : 'count' }
options = [option_0, option_1, option_2, option_3]
def display_result(res) :
for i in res :
print "\t", i
for j in res[i] :
print "\t\t", j, res[i][j]
def analyze_app(filename, ri, a) :
print filename
display_result( ri.with_apk( a ) )
def analyze_dex(filename, ri, d) :
print filename
display_result( ri.with_dex( d ) )
def main(options, arguments) :
ri = risk.RiskIndicator()
ri.add_risk_analysis( risk.RedFlags() )
ri.add_risk_analysis( risk.FuzzyRisk() )
if options.input != None :
ret_type = androconf.is_android( options.input )
if ret_type == "APK" :
a = apk.APK( options.input )
analyze_app( options.input, ri, a )
elif ret_type == "DEX" :
analyze_dex( options.input, ri, open(options.input, "r").read() )
elif options.directory != None :
for root, dirs, files in os.walk( options.directory, followlinks=True ) :
if files != [] :
for f in files :
real_filename = root
if real_filename[-1] != "/" :
real_filename += "/"
real_filename += f
ret_type = androconf.is_android( real_filename )
if ret_type == "APK" :
try :
a = apk.APK( real_filename )
analyze_app( real_filename, ri, a )
except Exception, e :
print e
elif ret_type == "DEX" :
analyze_dex( real_filename, ri, open(real_filename, "r").read() )
elif options.version != None :
print "Androrisk version %s" % androconf.ANDROGUARD_VERSION
if __name__ == "__main__" :
parser = OptionParser()
for option in options :
param = option['name']
del option['name']
parser.add_option(*param, **option)
options, arguments = parser.parse_args()
sys.argv[:] = arguments
main(options, arguments)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.