Example #1
0
def prototype(ctx, proto):
    """Get prototype definitions from the remote database
    (or the local database if no remote is found) matching  
    constraints on name of its return type or specific
    arguments. 
    """
    reqs = {}
    try:
        for p in proto:
            pos, t = p.split(':')
            pos = int(pos)
            reqs[pos] = c_type(t).show()
    except:
        click.secho('invalid arguments', fg='red', err=True)
        return
    db = ctx.obj['db']
    Q = ctx.obj.get('select', Query())
    L = db.search(Q, cls='cFunc')
    R = []
    with click.progressbar(L) as pL:
        for l in L:
            x = ccore.from_db(l)
            P = [c_type(t).show() for t in x.argtypes()]
            P.insert(0, c_type(x.restype()).show())
            if max(reqs) >= len(P): continue
            if not all(((t == P[i]) for (i, t) in reqs.items())):
                continue
            R.append(x.show(db, form='C'))
    if R:
        click.echo('\n'.join(R))
Example #2
0
class Select_Prototype(Resource):
    def get(self):
        return {
            "verbose": False,
            "tag": "",
            "key": "",
            "match": "",
            "format": "C",
            "proto": "",
        }

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("verbose", type=bool)
        parser.add_argument("tag")
        parser.add_argument("key")
        parser.add_argument("match")
        parser.add_argument("proto")
        parser.add_argument("format")
        args = parser.parse_args()
        db = g_ctx.obj["db"]
        if args["tag"]:
            db.set_tag(args["tag"])
        if verbose := args["verbose"]:
            keys = ("src", "tag")
        if args["key"] and args["match"]:
            Q = where(args["key"]).matches(args["match"])
        else:
            Q = Query().noop()
        proto = args["proto"].split(";")
        fmt = args.get("format", "C")
        reqs = {}
        try:
            for p in proto:
                pos, t = p.split(":")
                pos = int(pos)
                reqs[pos] = c_type(t).show()
        except Exception:
            return abort(400, reason="bad prototype request")
        L = []
        for l in db.search(Q & (where("cls") == "cFunc")):
            x = ccore.from_db(l)
            P = [c_type(t).show() for t in x.argtypes()]
            P.insert(0, c_type(x.restype()).show())
            if max(reqs) >= len(P):
                continue
            if not all(((t == P[i]) for (i, t) in reqs.items())):
                continue
            d = {"id": l["id"], "val": x.show(db, form=fmt)}
            if verbose:
                for k in keys:
                    d[k] = l[k]
            L.append(d)
        return L
Example #3
0
class Select_Prototype(Resource):
    def get(self):
        return {
            'verbose': False,
            'tag': '',
            'key': '',
            'match': '',
            'format': 'C',
            'proto': ''
        }

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('verbose', type=bool)
        parser.add_argument('tag')
        parser.add_argument('key')
        parser.add_argument('match')
        parser.add_argument('proto')
        parser.add_argument('format')
        args = parser.parse_args()
        db = g_ctx.obj['db']
        if args['tag']:
            db.set_tag(args['tag'])
        if verbose := args['verbose']:
            keys = ('src', 'tag')
        if args['key'] and args['match']:
            Q = where(args['key']).matches(args['match'])
        else:
            Q = Query()
        proto = args['proto'].split(';')
        fmt = args.get('format', 'C')
        reqs = {}
        try:
            for p in proto:
                pos, t = p.split(':')
                pos = int(pos)
                reqs[pos] = c_type(t).show()
        except Exception:
            return abort(400, reason="bad prototype request")
        L = []
        for l in db.search(Q & (where('cls') == 'cFunc')):
            x = ccore.from_db(l)
            P = [c_type(t).show() for t in x.argtypes()]
            P.insert(0, c_type(x.restype()).show())
            if max(reqs) >= len(P): continue
            if not all(((t == P[i]) for (i, t) in reqs.items())):
                continue
            d = {'id': l['id'], 'val': x.show(db, form=fmt)}
            if verbose:
                for k in keys:
                    d[k] = l[k]
            L.append(d)
        return L
Example #4
0
class Select_Struct(Resource):
    def get(self):
        return {
            "verbose": False,
            "tag": "",
            "key": "",
            "match": "",
            "def": False,
            "format": "C",
            "conds": "",
        }

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("verbose", type=bool)
        parser.add_argument("tag")
        parser.add_argument("key")
        parser.add_argument("match")
        parser.add_argument("def", type=bool)
        parser.add_argument("format")
        parser.add_argument("conds")
        args = parser.parse_args()
        db = g_ctx.obj["db"]
        if args["tag"]:
            db.set_tag(args["tag"])
        if verbose := args["verbose"]:
            keys = ("src", "tag")
        if args["key"] and args["match"]:
            Q = where(args["key"]).matches(args["match"])
        else:
            Q = Query().noop()
        fmt = args["format"] or "C"
        conds = args["conds"].split(";")
        pdef = args["def"]
        reqs = {}
        try:
            for p in conds:
                off, t = p.split(":")
                if off == "*":
                    sz = int(t)
                    reqs[off] = sz
                else:
                    off = int(off)
                    if t[0] == "+":
                        reqs[off] = int(t)
                    elif t[0] == "?":
                        reqs[off] = t
                    else:
                        reqs[off] = c_type(t)
        except Exception:
            abort(400, reason="invalid constraints")
        L = []
        for l in db.search(Q & (
            (where("cls") == "cStruct") | (where("cls") == "cClass"))):
            x = ccore.from_db(l)
            out = ""
            ctcls = c_type
            try:
                if x._is_class:
                    x = x.as_cStruct(db)
                t = x.build(db)
            except Exception:
                continue
            F = []
            for i, f in enumerate(t._fields_):
                field = getattr(t, f[0])
                F.append((field.offset, field.size, ctcls(x[i][0])))
            if F:
                xsize = F[-1][0] + F[-1][1]
                if "*" in reqs and reqs["*"] != xsize:
                    continue
                F = dict(((f[0], f[1:3]) for f in F))
                ok = []
                for o, s in reqs.items():
                    if o == "*":
                        continue
                    cond = o in F
                    ok.append(cond)
                    if not cond:
                        break
                    if s == "?":
                        continue
                    if s == "*":
                        cond = F[o][1].is_ptr
                    elif isinstance(s, c_type):
                        cond = F[o][1].show() == s.show()
                    else:
                        cond = F[o][0] == s
                    ok.append(cond)
                    if not cond:
                        break
                if all(ok):
                    if not pdef:
                        out = x.identifier
                    else:
                        out = x.show(db, form=fmt)
            if out:
                d = {"val": out}
                if verbose:
                    for k in keys:
                        d[k] = l[k]
                L.append(d)
        return L
Example #5
0
class Select_Struct(Resource):
    def get(self):
        return {
            'verbose': False,
            'tag': '',
            'key': '',
            'match': '',
            'def': False,
            'format': 'C',
            'conds': ''
        }

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('verbose', type=bool)
        parser.add_argument('tag')
        parser.add_argument('key')
        parser.add_argument('match')
        parser.add_argument('def', type=bool)
        parser.add_argument('format')
        parser.add_argument('conds')
        args = parser.parse_args()
        db = g_ctx.obj['db']
        if args['tag']:
            db.set_tag(args['tag'])
        if verbose := args['verbose']:
            keys = ('src', 'tag')
        if args['key'] and args['match']:
            Q = where(args['key']).matches(args['match'])
        else:
            Q = Query()
        fmt = args['format'] or 'C'
        conds = args['conds'].split(';')
        pdef = args['def']
        reqs = {}
        try:
            for p in conds:
                off, t = p.split(':')
                if off == '*':
                    sz = int(t)
                    reqs[off] = sz
                else:
                    off = int(off)
                    if t[0] == '+':
                        reqs[off] = int(t)
                    elif t[0] == '?':
                        reqs[off] = t
                    else:
                        reqs[off] = c_type(t)
        except Exception:
            abort(400, reason="invalid constraints")
        L = []
        for l in db.search(Q & (
            (where('cls') == 'cStruct') | (where('cls') == 'cClass'))):
            x = ccore.from_db(l)
            out = ''
            ctcls = c_type
            try:
                if x._is_class:
                    x = x.as_cStruct(db)
                t = x.build(db)
            except:
                continue
            F = []
            for i, f in enumerate(t._fields_):
                field = getattr(t, f[0])
                F.append((field.offset, field.size, ctcls(x[i][0])))
            if F:
                xsize = F[-1][0] + F[-1][1]
                if '*' in reqs and reqs['*'] != xsize: continue
                F = dict(((f[0], f[1:3]) for f in F))
                ok = []
                for o, s in reqs.items():
                    if o == '*': continue
                    cond = (o in F)
                    ok.append(cond)
                    if not cond: break
                    if s == '?': continue
                    if s == '*': cond = (F[o][1].is_ptr)
                    elif isinstance(s, c_type):
                        cond = (F[o][1].show() == s.show())
                    else:
                        cond = (F[o][0] == s)
                    ok.append(cond)
                    if not cond: break
                if all(ok):
                    if not pdef: out = x.identifier
                    else: out = x.show(db, form=fmt)
            if out:
                d = {'val': out}
                if verbose:
                    for k in keys:
                        d[k] = l[k]
                L.append(d)
        return L
Example #6
0
def struct(ctx, pdef, conds):
    """Get structured definitions (struct, union or class)
    from the remote database (or the local database if no remote is found) matching  
    constraints on total size or specific type name or size at given offset within
    the structure.
    """
    reqs = {}
    try:
        for p in conds:
            off, t = p.split(':')
            if off == '*':
                sz = int(t)
                reqs[off] = sz
            else:
                off = int(off)
                if t[0] == '+':
                    reqs[off] = int(t)
                elif t[0] == '?':
                    reqs[off] = t
                else:
                    reqs[off] = c_type(t)
    except:
        click.secho('invalid arguments', fg='red', err=True)
        return
    db = ctx.obj['db']
    Q = ctx.obj.get('select', Query())
    L = db.search(Q
                  & ((where('cls') == 'cStruct') | (where('cls') == 'cClass')))
    R = []
    fails = []
    with click.progressbar(L) as pL:
        for l in pL:
            x = ccore.from_db(l)
            ctcls = c_type
            try:
                if x._is_class:
                    x = x.as_cStruct(db)
                t = x.build(db)
            except:
                fails.append("can't build %s" % x.identifier)
                continue
            F = []
            for i, f in enumerate(t._fields_):
                field = getattr(t, f[0])
                F.append((field.offset, field.size, ctcls(x[i][0])))
            if F:
                xsize = F[-1][0] + F[-1][1]
                if '*' in reqs and reqs['*'] != xsize: continue
                F = dict(((f[0], f[1:3]) for f in F))
                ok = []
                for o, s in reqs.items():
                    if o == '*': continue
                    cond = (o in F)
                    ok.append(cond)
                    if not cond: break
                    if s == '?': continue
                    if s == '*': cond = (F[o][1].is_ptr)
                    elif isinstance(s, c_type):
                        cond = (F[o][1].show() == s.show())
                    else:
                        cond = (F[o][0] == s)
                    ok.append(cond)
                    if not cond: break
                if all(ok):
                    if not pdef: res = x.identifier
                    else: res = x.show(db, form='C')
                    R.append(res)
    if conf.VERBOSE:
        click.secho(u'\n'.join(fails), fg='red', err=True)
    if R:
        click.echo('\n'.join(R))