Exemplo n.º 1
0
static inline bool
parse_pyint(PyObject* o, int32_t* ret, int32_t min, int32_t max) {
  long val = PyInt_AsLong(o);

  if (INT_CONV_ERROR_OCCURRED(val)) {
    return false;
  }
  if (!CHECK_RANGE(val, min, max)) {
    PyErr_SetString(PyExc_OverflowError, "int out of range");
    return false;
  }

  *ret = (int32_t) val;
  return true;
}
Exemplo n.º 2
0
bool Environment::initConfig(Config::Config *config, const std::string& name,
                             int fromStage, int toStage, bool standalone) const {
	std::string globalConfig, appConfig;

	globalConfig = configFileLocation(name, CS_DEFAULT_GLOBAL);
	appConfig = configFileLocation(name, CS_DEFAULT_APP);

	if ( !standalone ) {
		if ( CHECK_RANGE(CS_DEFAULT_GLOBAL, fromStage, toStage) ) {
			if ( appConfig != globalConfig && Util::fileExists(globalConfig) )
				if ( !config->readConfig(globalConfig, CS_DEFAULT_GLOBAL) ) return false;
		}
	}

	if ( CHECK_RANGE(CS_DEFAULT_APP, fromStage, toStage) ) {
		if ( Util::fileExists(appConfig) )
			if ( !config->readConfig(appConfig, CS_DEFAULT_APP) ) return false;
	}

	globalConfig = configFileLocation(name, CS_CONFIG_GLOBAL);
	appConfig = configFileLocation(name, CS_CONFIG_APP);

	if ( !standalone ) {
		if ( CHECK_RANGE(CS_CONFIG_GLOBAL, fromStage, toStage) ) {
			if ( appConfig != globalConfig && Util::fileExists(globalConfig) )
				if ( !config->readConfig(globalConfig, CS_CONFIG_GLOBAL) ) return false;
		}
	}

	if ( CHECK_RANGE(CS_CONFIG_APP, fromStage, toStage) ) {
		if ( Util::fileExists(appConfig) )
			if ( !config->readConfig(appConfig, CS_CONFIG_APP) ) return false;
	}

	globalConfig = configFileLocation(name, CS_USER_GLOBAL);
	appConfig = configFileLocation(name, CS_USER_APP);

	if ( !standalone ) {
		if ( CHECK_RANGE(CS_USER_GLOBAL, fromStage, toStage) ) {
			if ( appConfig != globalConfig && Util::fileExists(globalConfig) )
				if ( !config->readConfig(globalConfig, CS_USER_GLOBAL) ) return false;
		}
	}

	if ( CHECK_RANGE(CS_USER_APP, fromStage, toStage) ) {
		if ( Util::fileExists(appConfig) )
			if ( !config->readConfig(appConfig, CS_USER_APP) ) return false;
	}

	return true;
}
Exemplo n.º 3
0
static int
pylzma_compfile_init(CCompressionFileObject *self, PyObject *args, PyObject *kwargs)
{
    PyObject *inFile;
    CLzmaEncProps props;
    Byte header[LZMA_PROPS_SIZE];
    size_t headerSize = LZMA_PROPS_SIZE;
    int result = -1;
    
    // possible keywords for this function
    static char *kwlist[] = {"infile", "dictionary", "fastBytes", "literalContextBits",
                             "literalPosBits", "posBits", "algorithm", "eos", "multithreading", "matchfinder", NULL};
    int dictionary = 23;         // [0,28], default 23 (8MB)
    int fastBytes = 128;         // [5,255], default 128
    int literalContextBits = 3;  // [0,8], default 3
    int literalPosBits = 0;      // [0,4], default 0
    int posBits = 2;             // [0,4], default 2
    int eos = 1;                 // write "end of stream" marker?
    int multithreading = 1;      // use multithreading if available?
    char *matchfinder = NULL;    // matchfinder algorithm
    int algorithm = 2;
    int res;
    
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|iiiiiiiis", kwlist, &inFile, &dictionary, &fastBytes,
                                                                 &literalContextBits, &literalPosBits, &posBits, &algorithm, &eos, &multithreading, &matchfinder))
        return -1;
    
    CHECK_RANGE(dictionary,         0,  28, "dictionary must be between 0 and 28");
    CHECK_RANGE(fastBytes,          5, 255, "fastBytes must be between 5 and 255");
    CHECK_RANGE(literalContextBits, 0,   8, "literalContextBits must be between 0 and 8");
    CHECK_RANGE(literalPosBits,     0,   4, "literalPosBits must be between 0 and 4");
    CHECK_RANGE(posBits,            0,   4, "posBits must be between 0 and 4");
    CHECK_RANGE(algorithm,          0,   2, "algorithm must be between 0 and 2");
    
    if (matchfinder != NULL) {
#if (PY_VERSION_HEX >= 0x02050000)
        PyErr_WarnEx(PyExc_DeprecationWarning, "matchfinder selection is deprecated and will be ignored", 1);
#else
        PyErr_Warn(PyExc_DeprecationWarning, "matchfinder selection is deprecated and will be ignored");
#endif
    }
    
    if (PyString_Check(inFile)) {
        // create new cStringIO object from string
        inFile = PycStringIO->NewInput(inFile);
        if (inFile == NULL)
        {
            PyErr_NoMemory();
            return -1;
        }
    } else if (!PyObject_HasAttrString(inFile, "read")) {
        PyErr_SetString(PyExc_ValueError, "first parameter must be a file-like object");
        return -1;
    } else {
        // protect object from being refcounted out...
        Py_INCREF(inFile);
    }
    
    self->encoder = LzmaEnc_Create(&allocator);
    if (self->encoder == NULL) {
        Py_DECREF(inFile);
        PyErr_NoMemory();
        return -1;
    }
    
    LzmaEncProps_Init(&props);
    
    props.dictSize = 1 << dictionary;
    props.lc = literalContextBits;
    props.lp = literalPosBits;
    props.pb = posBits;
    props.algo = algorithm;
    props.fb = fastBytes;
    // props.btMode = 1;
    // props.numHashBytes = 4;
    // props.mc = 32;
    props.writeEndMark = eos ? 1 : 0;
    props.numThreads = multithreading ? 2 : 1;
    LzmaEncProps_Normalize(&props);
    res = LzmaEnc_SetProps(self->encoder, &props);
    if (res != SZ_OK) {
        Py_DECREF(inFile);
        PyErr_Format(PyExc_TypeError, "could not set encoder properties: %d", res);
        return -1;
    }

    self->inFile = inFile;
    CreatePythonInStream(&self->inStream, inFile);
    CreateMemoryOutStream(&self->outStream);

    LzmaEnc_WriteProperties(self->encoder, header, &headerSize);
    if (self->outStream.s.Write(&self->outStream, header, headerSize) != headerSize) {
        PyErr_SetString(PyExc_TypeError, "could not generate stream header");
        goto exit;
    }
    
    LzmaEnc_Prepare(self->encoder, &self->inStream.s, &self->outStream.s, &allocator, &allocator);
    result = 0;
    
exit:
    return result;
}
Exemplo n.º 4
0
int CreatureAttributes::numInjured(BodyPart part) const {
  return CHECK_RANGE(injuredBodyParts[part], -10000000, 10000000, name->bare());
}
Exemplo n.º 5
0
int CreatureAttributes::numLost(BodyPart part) const {
  return CHECK_RANGE(lostBodyParts[part], -10000000, 10000000, name->bare());
}
Exemplo n.º 6
0
// Returns a new reference.
static PyObject*
decode_val(DecodeBuffer* input, TType type, PyObject* typeargs, long string_limit, long container_limit) {
    switch (type) {

    case T_BOOL: {
        int8_t v = readByte(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }

        switch (v) {
        case 0:
            Py_RETURN_FALSE;
        case 1:
            Py_RETURN_TRUE;
        // Don't laugh.  This is a potentially serious issue.
        default:
            PyErr_SetString(PyExc_TypeError, "boolean out of range");
            return NULL;
        }
        break;
    }
    case T_I08: {
        int8_t v = readByte(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }

        return PyInt_FromLong(v);
    }
    case T_I16: {
        int16_t v = readI16(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }
        return PyInt_FromLong(v);
    }
    case T_I32: {
        int32_t v = readI32(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }
        return PyInt_FromLong(v);
    }

    case T_I64: {
        int64_t v = readI64(input);
        if (INT_CONV_ERROR_OCCURRED(v)) {
            return NULL;
        }
        // TODO(dreiss): Find out if we can take this fastpath always when
        //               sizeof(long) == sizeof(long long).
        if (CHECK_RANGE(v, LONG_MIN, LONG_MAX)) {
            return PyInt_FromLong((long) v);
        }

        return PyLong_FromLongLong(v);
    }

    case T_DOUBLE: {
        double v = readDouble(input);
        if (v == -1.0 && PyErr_Occurred()) {
            return false;
        }
        return PyFloat_FromDouble(v);
    }

    case T_STRING: {
        Py_ssize_t len = readI32(input);
        char* buf;
        if (!readBytes(input, &buf, len)) {
            return NULL;
        }
        if (!check_length_limit(len, string_limit)) {
            return NULL;
        }

        if (is_utf8(typeargs))
            return PyUnicode_DecodeUTF8(buf, len, 0);
        else
            return PyString_FromStringAndSize(buf, len);
    }

    case T_LIST:
    case T_SET: {
        SetListTypeArgs parsedargs;
        int32_t len;
        PyObject* ret = NULL;
        int i;
        bool use_tuple = false;

        if (!parse_set_list_args(&parsedargs, typeargs)) {
            return NULL;
        }

        if (!checkTypeByte(input, parsedargs.element_type)) {
            return NULL;
        }

        len = readI32(input);
        if (!check_length_limit(len, container_limit)) {
            return NULL;
        }

        use_tuple = type == T_LIST && parsedargs.immutable;
        ret = use_tuple ? PyTuple_New(len) : PyList_New(len);
        if (!ret) {
            return NULL;
        }

        for (i = 0; i < len; i++) {
            PyObject* item = decode_val(input, parsedargs.element_type, parsedargs.typeargs, string_limit, container_limit);
            if (!item) {
                Py_DECREF(ret);
                return NULL;
            }
            if (use_tuple) {
                PyTuple_SET_ITEM(ret, i, item);
            } else  {
                PyList_SET_ITEM(ret, i, item);
            }
        }

        // TODO(dreiss): Consider biting the bullet and making two separate cases
        //               for list and set, avoiding this post facto conversion.
        if (type == T_SET) {
            PyObject* setret;
            setret = parsedargs.immutable ? PyFrozenSet_New(ret) : PySet_New(ret);
            Py_DECREF(ret);
            return setret;
        }
        return ret;
    }

    case T_MAP: {
        int32_t len;
        int i;
        MapTypeArgs parsedargs;
        PyObject* ret = NULL;

        if (!parse_map_args(&parsedargs, typeargs)) {
            return NULL;
        }

        if (!checkTypeByte(input, parsedargs.ktag)) {
            return NULL;
        }
        if (!checkTypeByte(input, parsedargs.vtag)) {
            return NULL;
        }

        len = readI32(input);
        if (!check_length_limit(len, container_limit)) {
            return NULL;
        }

        ret = PyDict_New();
        if (!ret) {
            goto error;
        }

        for (i = 0; i < len; i++) {
            PyObject* k = NULL;
            PyObject* v = NULL;
            k = decode_val(input, parsedargs.ktag, parsedargs.ktypeargs, string_limit, container_limit);
            if (k == NULL) {
                goto loop_error;
            }
            v = decode_val(input, parsedargs.vtag, parsedargs.vtypeargs, string_limit, container_limit);
            if (v == NULL) {
                goto loop_error;
            }
            if (PyDict_SetItem(ret, k, v) == -1) {
                goto loop_error;
            }

            Py_DECREF(k);
            Py_DECREF(v);
            continue;

            // Yuck!  Destructors, anyone?
loop_error:
            Py_XDECREF(k);
            Py_XDECREF(v);
            goto error;
        }

        if (parsedargs.immutable) {
            PyObject* thrift = PyImport_ImportModule("thrift.Thrift");
            PyObject* cls = NULL;
            PyObject* arg = NULL;
            if (!thrift) {
                goto error;
            }
            cls = PyObject_GetAttrString(thrift, "TFrozenDict");
            if (!cls) {
                goto error;
            }
            arg = PyTuple_New(1);
            PyTuple_SET_ITEM(arg, 0, ret);
            return PyObject_CallObject(cls, arg);
        }

        return ret;

error:
        Py_XDECREF(ret);
        return NULL;
    }

    case T_STRUCT: {
        StructTypeArgs parsedargs;
        if (!parse_struct_args(&parsedargs, typeargs)) {
            return NULL;
        }

        return decode_struct(input, Py_None, parsedargs.klass, parsedargs.spec, string_limit, container_limit);
    }

    case T_STOP:
    case T_VOID:
    case T_UTF16:
    case T_UTF8:
    case T_U64:
    default:
        PyErr_SetString(PyExc_TypeError, "Unexpected TType");
        return NULL;
    }
}
Exemplo n.º 7
0
static bool
output_val(PyObject* output, PyObject* value, TType type, PyObject* typeargs) {
    /*
     * Refcounting Strategy:
     *
     * We assume that elements of the thrift_spec tuple are not going to be
     * mutated, so we don't ref count those at all. Other than that, we try to
     * keep a reference to all the user-created objects while we work with them.
     * output_val assumes that a reference is already held. The *caller* is
     * responsible for handling references
     */

    switch (type) {

    case T_BOOL: {
        int v = PyObject_IsTrue(value);
        if (v == -1) {
            return false;
        }

        writeByte(output, (int8_t) v);
        break;
    }
    case T_I08: {
        int32_t val;

        if (!parse_pyint(value, &val, INT8_MIN, INT8_MAX)) {
            return false;
        }

        writeByte(output, (int8_t) val);
        break;
    }
    case T_I16: {
        int32_t val;

        if (!parse_pyint(value, &val, INT16_MIN, INT16_MAX)) {
            return false;
        }

        writeI16(output, (int16_t) val);
        break;
    }
    case T_I32: {
        int32_t val;

        if (!parse_pyint(value, &val, INT32_MIN, INT32_MAX)) {
            return false;
        }

        writeI32(output, val);
        break;
    }
    case T_I64: {
        int64_t nval = PyLong_AsLongLong(value);

        if (INT_CONV_ERROR_OCCURRED(nval)) {
            return false;
        }

        if (!CHECK_RANGE(nval, INT64_MIN, INT64_MAX)) {
            PyErr_SetString(PyExc_OverflowError, "int out of range");
            return false;
        }

        writeI64(output, nval);
        break;
    }

    case T_DOUBLE: {
        double nval = PyFloat_AsDouble(value);
        if (nval == -1.0 && PyErr_Occurred()) {
            return false;
        }

        writeDouble(output, nval);
        break;
    }

    case T_STRING: {
        Py_ssize_t len = 0;
        if (is_utf8(typeargs) && PyUnicode_Check(value))
            value = PyUnicode_AsUTF8String(value);
        len = PyString_Size(value);

        if (!check_ssize_t_32(len)) {
            return false;
        }

        writeI32(output, (int32_t) len);
        PycStringIO->cwrite(output, PyString_AsString(value), (int32_t) len);
        break;
    }

    case T_LIST:
    case T_SET: {
        Py_ssize_t len;
        SetListTypeArgs parsedargs;
        PyObject *item;
        PyObject *iterator;

        if (!parse_set_list_args(&parsedargs, typeargs)) {
            return false;
        }

        len = PyObject_Length(value);

        if (!check_ssize_t_32(len)) {
            return false;
        }

        writeByte(output, parsedargs.element_type);
        writeI32(output, (int32_t) len);

        iterator =  PyObject_GetIter(value);
        if (iterator == NULL) {
            return false;
        }

        while ((item = PyIter_Next(iterator))) {
            if (!output_val(output, item, parsedargs.element_type, parsedargs.typeargs)) {
                Py_DECREF(item);
                Py_DECREF(iterator);
                return false;
            }
            Py_DECREF(item);
        }

        Py_DECREF(iterator);

        if (PyErr_Occurred()) {
            return false;
        }

        break;
    }

    case T_MAP: {
        PyObject *k, *v;
        Py_ssize_t pos = 0;
        Py_ssize_t len;

        MapTypeArgs parsedargs;

        len = PyDict_Size(value);
        if (!check_ssize_t_32(len)) {
            return false;
        }

        if (!parse_map_args(&parsedargs, typeargs)) {
            return false;
        }

        writeByte(output, parsedargs.ktag);
        writeByte(output, parsedargs.vtag);
        writeI32(output, len);

        // TODO(bmaurer): should support any mapping, not just dicts
        while (PyDict_Next(value, &pos, &k, &v)) {
            // TODO(dreiss): Think hard about whether these INCREFs actually
            //               turn any unsafe scenarios into safe scenarios.
            Py_INCREF(k);
            Py_INCREF(v);

            if (!output_val(output, k, parsedargs.ktag, parsedargs.ktypeargs)
                    || !output_val(output, v, parsedargs.vtag, parsedargs.vtypeargs)) {
                Py_DECREF(k);
                Py_DECREF(v);
                return false;
            }
            Py_DECREF(k);
            Py_DECREF(v);
        }
        break;
    }

    // TODO(dreiss): Consider breaking this out as a function
    //               the way we did for decode_struct.
    case T_STRUCT: {
        StructTypeArgs parsedargs;
        Py_ssize_t nspec;
        Py_ssize_t i;

        if (!parse_struct_args(&parsedargs, typeargs)) {
            return false;
        }

        nspec = PyTuple_Size(parsedargs.spec);

        if (nspec == -1) {
            return false;
        }

        for (i = 0; i < nspec; i++) {
            StructItemSpec parsedspec;
            PyObject* spec_tuple;
            PyObject* instval = NULL;

            spec_tuple = PyTuple_GET_ITEM(parsedargs.spec, i);
            if (spec_tuple == Py_None) {
                continue;
            }

            if (!parse_struct_item_spec (&parsedspec, spec_tuple)) {
                return false;
            }

            instval = PyObject_GetAttr(value, parsedspec.attrname);

            if (!instval) {
                return false;
            }

            if (instval == Py_None) {
                Py_DECREF(instval);
                continue;
            }

            writeByte(output, (int8_t) parsedspec.type);
            writeI16(output, parsedspec.tag);

            if (!output_val(output, instval, parsedspec.type, parsedspec.typeargs)) {
                Py_DECREF(instval);
                return false;
            }

            Py_DECREF(instval);
        }

        writeByte(output, (int8_t)T_STOP);
        break;
    }

    case T_STOP:
    case T_VOID:
    case T_UTF16:
    case T_UTF8:
    case T_U64:
    default:
        PyErr_SetString(PyExc_TypeError, "Unexpected TType");
        return false;

    }

    return true;
}
Exemplo n.º 8
0
int
main(int argc, char *argv[])
{
	struct psc_vbitmap *vb, vba = VBITMAP_INIT_AUTO;
	size_t elem, j, cap, len, off;
	int i, c, u, t;

	pfl_init();
	while ((c = getopt(argc, argv, "")) != -1)
		switch (c) {
		default:
			usage();
		}

	argc -= optind;
	if (argc)
		usage();

	for (i = 0; i < 79; i++)
		if (psc_vbitmap_next(&vba, &j) != 1)
			psc_fatalx("psc_vbitmap_next failed with auto");
		else if (j != (size_t)i)
			psc_fatalx("elem %d is not supposed to be %zu", i, j);

	if ((vb = psc_vbitmap_new(213)) == NULL)
		psc_fatal("psc_vbitmap_new");

	psc_vbitmap_setrange(vb, 13, 9);
	psc_vbitmap_printbin1(vb);
	for (i = 0; i < 13; i++)
		pfl_assert(psc_vbitmap_get(vb, i) == 0);
	for (j = 0; j < 9; j++, i++)
	    pfl_assert(psc_vbitmap_get(vb, i) == 1);
	for (j = 0; j < 25; j++, i++)
	    pfl_assert(psc_vbitmap_get(vb, i) == 0);

	psc_vbitmap_clearall(vb);
	for (i = 0; i < 213; i++)
	    pfl_assert(psc_vbitmap_get(vb, i) == 0);

	psc_vbitmap_setrange(vb, 25, 3);
	for (i = 0; i < 25; i++)
		pfl_assert(psc_vbitmap_get(vb, i) == 0);
	for (j = 0; j < 3; j++, i++)
	    pfl_assert(psc_vbitmap_get(vb, i) == 1);
	for (j = 0; j < 25; j++, i++)
	    pfl_assert(psc_vbitmap_get(vb, i) == 0);

	psc_vbitmap_clearall(vb);
	for (i = 0; i < 213; i++)
	    pfl_assert(psc_vbitmap_get(vb, i) == 0);

	for (i = 0; i < 213; i++)
		if (!psc_vbitmap_next(vb, &elem))
			psc_fatalx("out of elements at pos %d", i);

	if (psc_vbitmap_next(vb, &elem))
		psc_fatalx("an unexpected extra unused elem was found; pos=%zu", elem);

	psc_vbitmap_getstats(vb, &u, &t);
	if (u != 213 || t != 213)
		psc_fatalx("wrong size, got %d,%d want %d", u, t, 213);

	psc_vbitmap_unsetrange(vb, 13, 2);
	for (i = 0; i < 13; i++)
		pfl_assert(psc_vbitmap_get(vb, i) == 1);
	for (j = 0; j < 2; j++, i++)
	    pfl_assert(psc_vbitmap_get(vb, i) == 0);
	for (j = 0; j < 25; j++, i++)
	    pfl_assert(psc_vbitmap_get(vb, i) == 1);

	if (psc_vbitmap_resize(vb, NELEM) == -1)
		psc_fatal("psc_vbitmap_resize");

	pfl_assert(psc_vbitmap_getsize(vb) == NELEM);

	/* fill up bitmap */
	for (i = 0; i < NELEM - 211; i++)
		if (!psc_vbitmap_next(vb, &elem))
			psc_fatalx("out of elements at iter %d", i);

	/* try one past end of filled bitmap */
	if (psc_vbitmap_next(vb, &elem))
		psc_fatalx("an unexpected extra unused elem was found; pos=%zu", elem);

	/* free some slots */
	for (i = 0, elem = 0; elem < NELEM; i++, elem += NELEM / 10)
		psc_vbitmap_unset(vb, elem);

	t = psc_vbitmap_nfree(vb);
	if (t != i)
		psc_fatalx("wrong number of free elements; has=%d want=%d", t, i);
	psc_vbitmap_invert(vb);
	t = psc_vbitmap_nfree(vb);
	if (t != NELEM - i)
		psc_fatalx("wrong number of inverted elements; has=%d want=%d",
		    t, NELEM - i);
	psc_vbitmap_invert(vb);
	t = psc_vbitmap_nfree(vb);
	if (t != i)
		psc_fatalx("wrong number of original elements; has=%d want=%d", t, i);

	/* try to re-grab the freed slots */
	for (i = 0; i <= 10; i++)
		if (!psc_vbitmap_next(vb, &elem))
			psc_fatalx("out of elements, request %d/%d", i, 10);

	/* try one past end of filled bitmap */
	if (psc_vbitmap_next(vb, &elem))
		psc_fatalx("an unexpected extra unused elem was found; pos=%zu", elem);

	psc_vbitmap_setval_range(vb, 0, NELEM, 0);
	CHECK_RANGE(vb, 0, 581, 371);
	CHECK_RANGE(vb, 0, 581, 1);
	pfl_assert(pfl_vbitmap_isempty(vb));

	psc_vbitmap_setval_range(vb, 0, NELEM, 1);
	CHECK_RANGE(vb, 1, 581, 371);
	CHECK_RANGE(vb, 1, 581, 1);
	pfl_assert(psc_vbitmap_isfull(vb));

	psc_vbitmap_free(vb);

	vb = psc_vbitmap_newf(0, PVBF_AUTO);
	pfl_assert(vb);
	pfl_assert(pfl_vbitmap_isempty(vb));
	pfl_assert(psc_vbitmap_getsize(vb) == 0);
	pfl_assert(psc_vbitmap_resize(vb, 6) == 0);
	pfl_assert(psc_vbitmap_getsize(vb) == 6);
	pfl_assert(pfl_vbitmap_isempty(vb));
	psc_vbitmap_free(vb);

	vb = psc_vbitmap_newf(0, PVBF_AUTO);
	cap = psc_vbitmap_getsize(vb);
	off = 0;
	len = 6;
	if (off + len > cap)
		psc_vbitmap_resize(vb, off + len);
	psc_vbitmap_setrange(vb, off, len);
	ENSURE(vb, "111111");
	CHECK_RANGE(vb, 1, 2, 4);

	psc_vbitmap_clearall(vb);
	pfl_assert(psc_vbitmap_setval_range(vb, 2, 4, 1) == 0);
	CHECK_RANGE(vb, 1, 2, 4);
	ENSURE(vb, "001111");
	psc_vbitmap_free(vb);

	vb = psc_vbitmap_new(0);
	for (i = 1; i < 101; i++) {
		if (psc_vbitmap_resize(vb, i) == -1)
			psc_fatal("psc_vbitmap_new");
		psc_vbitmap_setval(vb, i - 1, i % 2);
		pfl_assert(psc_vbitmap_get(vb, i - 1) == i % 2);
	}
	psc_vbitmap_free(vb);

	for (cap = 0; cap < 100; cap++) {
		for (off = 1; off < cap; off++) {
			for (len = 1; off + len < cap; len++) {
				size_t last;

				last = cap - off - len;
				vb = psc_vbitmap_new(cap);
				psc_vbitmap_setrange(vb, off, len);
				ENSURE(vb, "%0*d%*d%0*d", (int)off, 0,
				    (int)len, 1, (int)last, 0);
				CHECK_RANGE(vb, 0, 0, off);
				CHECK_RANGE(vb, 1, off, len);
				CHECK_RANGE(vb, 0, off+len, last);
				psc_vbitmap_free(vb);
			}
		}
	}

	vb = psc_vbitmap_new(8200);
	pfl_assert(pfl_vbitmap_isempty(vb));
	CHECK_RANGE(vb, 0, 8, 8192);
	psc_vbitmap_free(vb);

	vb = psc_vbitmap_new(16);
	ENSURE_ABBR(vb, "0:8,00000000");
	psc_vbitmap_free(vb);

	vb = psc_vbitmap_new(40);
	psc_vbitmap_setval_range(vb, 0, 10, 0);
	psc_vbitmap_setval_range(vb, 10, 10, 1);
	ENSURE(vb, "0000000000111111111100000000000000000000");
	ENSURE_ABBR(vb, "0:10,1:10,0:12,00000000");
	psc_vbitmap_free(vb);

	vb = psc_vbitmap_new(16);
	ENSURE(vb, "0000000000000000");
	pfl_assert(pfl_vbitmap_isempty(vb));
	CHECK_RANGE(vb, 0, 8, 8);
	CHECK_RANGE(vb, 0, 9, 7);
	psc_vbitmap_setval(vb, 15, 1);
	ENSURE(vb, "0000000000000001");
	CHECK_RANGE(vb, 0, 9, 6);
	CHECK_RANGE(vb, 1, 15, 1);
	pfl_assert(pfl_vbitmap_israngeset(vb, 0, 8, 8) == 0);
	pfl_assert(pfl_vbitmap_israngeset(vb, 1, 8, 8) == 0);
	psc_vbitmap_clearall(vb);
	pfl_assert(pfl_vbitmap_isempty(vb));
	psc_vbitmap_free(vb);

	exit(0);
}
Exemplo n.º 9
0
// Returns a new reference.
static PyObject*
decode_val(DecodeBuffer* input, TType type, PyObject* typeargs) {
  switch (type) {

  case T_BOOL: {
    int8_t v = readByte(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }

    switch (v) {
    case 0: Py_RETURN_FALSE;
    case 1: Py_RETURN_TRUE;
    // Don't laugh.  This is a potentially serious issue.
    default: PyErr_SetString(PyExc_TypeError, "boolean out of range"); return NULL;
    }
    break;
  }
  case T_I08: {
    int8_t v = readByte(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }

    return PyInt_FromLong(v);
  }
  case T_I16: {
    int16_t v = readI16(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }
    return PyInt_FromLong(v);
  }
  case T_I32: {
    int32_t v = readI32(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }
    return PyInt_FromLong(v);
  }

  case T_I64: {
    int64_t v = readI64(input);
    if (INT_CONV_ERROR_OCCURRED(v)) {
      return NULL;
    }
    // TODO(dreiss): Find out if we can take this fastpath always when
    //               sizeof(long) == sizeof(long long).
    if (CHECK_RANGE(v, LONG_MIN, LONG_MAX)) {
      return PyInt_FromLong((long) v);
    }

    return PyLong_FromLongLong(v);
  }

  case T_DOUBLE: {
    double v = readDouble(input);
    if (v == -1.0 && PyErr_Occurred()) {
      return false;
    }
    return PyFloat_FromDouble(v);
  }

  case T_STRING: {
    Py_ssize_t len = readI32(input);
    char* buf;
    if (!readBytes(input, &buf, len)) {
      return NULL;
    }

    return PyString_FromStringAndSize(buf, len);
  }

  case T_LIST:
  case T_SET: {
    SetListTypeArgs parsedargs;
    int32_t len;
    PyObject* ret = NULL;
    int i;

    if (!parse_set_list_args(&parsedargs, typeargs)) {
      return NULL;
    }

    if (!checkTypeByte(input, parsedargs.element_type)) {
      return NULL;
    }

    len = readI32(input);
    if (!check_ssize_t_32(len)) {
      return NULL;
    }

    ret = PyList_New(len);
    if (!ret) {
      return NULL;
    }

    for (i = 0; i < len; i++) {
      PyObject* item = decode_val(input, parsedargs.element_type, parsedargs.typeargs);
      if (!item) {
        Py_DECREF(ret);
        return NULL;
      }
      PyList_SET_ITEM(ret, i, item);
    }

    // TODO(dreiss): Consider biting the bullet and making two separate cases
    //               for list and set, avoiding this post facto conversion.
    if (type == T_SET) {
      PyObject* setret;
#if (PY_VERSION_HEX < 0x02050000)
      // hack needed for older versions
      setret = PyObject_CallFunctionObjArgs((PyObject*)&PySet_Type, ret, NULL);
#else
      // official version
      setret = PySet_New(ret);
#endif
      Py_DECREF(ret);
      return setret;
    }
    return ret;
  }

  case T_MAP: {
    int32_t len;
    int i;
    MapTypeArgs parsedargs;
    PyObject* ret = NULL;

    if (!parse_map_args(&parsedargs, typeargs)) {
      return NULL;
    }

    if (!checkTypeByte(input, parsedargs.ktag)) {
      return NULL;
    }
    if (!checkTypeByte(input, parsedargs.vtag)) {
      return NULL;
    }

    len = readI32(input);
    if (!check_ssize_t_32(len)) {
      return false;
    }

    ret = PyDict_New();
    if (!ret) {
      goto error;
    }

    for (i = 0; i < len; i++) {
      PyObject* k = NULL;
      PyObject* v = NULL;
      k = decode_val(input, parsedargs.ktag, parsedargs.ktypeargs);
      if (k == NULL) {
        goto loop_error;
      }
      v = decode_val(input, parsedargs.vtag, parsedargs.vtypeargs);
      if (v == NULL) {
        goto loop_error;
      }
      if (PyDict_SetItem(ret, k, v) == -1) {
        goto loop_error;
      }

      Py_DECREF(k);
      Py_DECREF(v);
      continue;

      // Yuck!  Destructors, anyone?
      loop_error:
      Py_XDECREF(k);
      Py_XDECREF(v);
      goto error;
    }

    return ret;

    error:
    Py_XDECREF(ret);
    return NULL;
  }

  case T_STRUCT: {
    StructTypeArgs parsedargs;
    if (!parse_struct_args(&parsedargs, typeargs)) {
      return NULL;
    }

    PyObject* ret = PyObject_CallObject(parsedargs.klass, NULL);
    if (!ret) {
      return NULL;
    }

    if (!decode_struct(input, ret, parsedargs.spec)) {
      Py_DECREF(ret);
      return NULL;
    }

    return ret;
  }

  case T_STOP:
  case T_VOID:
  case T_UTF16:
  case T_UTF8:
  case T_U64:
  default:
    PyErr_SetString(PyExc_TypeError, "Unexpected TType");
    return NULL;
  }
}
Exemplo n.º 10
0
static void dwc2_check_params(struct dwc2_hsotg *hsotg)
{
	struct dwc2_hw_params *hw = &hsotg->hw_params;
	struct dwc2_core_params *p = &hsotg->params;
	bool dma_capable = !(hw->arch == GHWCFG2_SLAVE_ONLY_ARCH);

	dwc2_check_param_otg_cap(hsotg);
	dwc2_check_param_phy_type(hsotg);
	dwc2_check_param_speed(hsotg);
	dwc2_check_param_phy_utmi_width(hsotg);
	dwc2_check_param_power_down(hsotg);
	CHECK_BOOL(enable_dynamic_fifo, hw->enable_dynamic_fifo);
	CHECK_BOOL(en_multiple_tx_fifo, hw->en_multiple_tx_fifo);
	CHECK_BOOL(i2c_enable, hw->i2c_enable);
	CHECK_BOOL(ipg_isoc_en, hw->ipg_isoc_en);
	CHECK_BOOL(acg_enable, hw->acg_enable);
	CHECK_BOOL(reload_ctl, (hsotg->hw_params.snpsid > DWC2_CORE_REV_2_92a));
	CHECK_BOOL(lpm, (hsotg->hw_params.snpsid >= DWC2_CORE_REV_2_80a));
	CHECK_BOOL(lpm, hw->lpm_mode);
	CHECK_BOOL(lpm_clock_gating, hsotg->params.lpm);
	CHECK_BOOL(besl, hsotg->params.lpm);
	CHECK_BOOL(besl, (hsotg->hw_params.snpsid >= DWC2_CORE_REV_3_00a));
	CHECK_BOOL(hird_threshold_en, hsotg->params.lpm);
	CHECK_RANGE(hird_threshold, 0, hsotg->params.besl ? 12 : 7, 0);
	CHECK_BOOL(service_interval, hw->service_interval_mode);
	CHECK_RANGE(max_packet_count,
		    15, hw->max_packet_count,
		    hw->max_packet_count);
	CHECK_RANGE(max_transfer_size,
		    2047, hw->max_transfer_size,
		    hw->max_transfer_size);

	if ((hsotg->dr_mode == USB_DR_MODE_HOST) ||
	    (hsotg->dr_mode == USB_DR_MODE_OTG)) {
		CHECK_BOOL(host_dma, dma_capable);
		CHECK_BOOL(dma_desc_enable, p->host_dma);
		CHECK_BOOL(dma_desc_fs_enable, p->dma_desc_enable);
		CHECK_BOOL(host_ls_low_power_phy_clk,
			   p->phy_type == DWC2_PHY_TYPE_PARAM_FS);
		CHECK_RANGE(host_channels,
			    1, hw->host_channels,
			    hw->host_channels);
		CHECK_RANGE(host_rx_fifo_size,
			    16, hw->rx_fifo_size,
			    hw->rx_fifo_size);
		CHECK_RANGE(host_nperio_tx_fifo_size,
			    16, hw->host_nperio_tx_fifo_size,
			    hw->host_nperio_tx_fifo_size);
		CHECK_RANGE(host_perio_tx_fifo_size,
			    16, hw->host_perio_tx_fifo_size,
			    hw->host_perio_tx_fifo_size);
	}

	if ((hsotg->dr_mode == USB_DR_MODE_PERIPHERAL) ||
	    (hsotg->dr_mode == USB_DR_MODE_OTG)) {
		CHECK_BOOL(g_dma, dma_capable);
		CHECK_BOOL(g_dma_desc, (p->g_dma && hw->dma_desc_enable));
		CHECK_RANGE(g_rx_fifo_size,
			    16, hw->rx_fifo_size,
			    hw->rx_fifo_size);
		CHECK_RANGE(g_np_tx_fifo_size,
			    16, hw->dev_nperio_tx_fifo_size,
			    hw->dev_nperio_tx_fifo_size);
		dwc2_check_param_tx_fifo_sizes(hsotg);
	}
}
Exemplo n.º 11
0
void MoleculeGraphics::find_sizes(void) {
  float minx=0.0f, maxx=0.0f;
  float miny=0.0f, maxy=0.0f;
  float minz=0.0f, maxz=0.0f;
  int found_one = 0;
  // go down the list and draw things
  int num = num_elements();
  ShapeClass *shape;
  for (int i=0; i<num; i++) {
    shape = &(shapes[i]);
    switch (shape->shape) {
    case NONE: {
      break;
    }
    case POINT: {
      CHECK_RANGE(shape->data+0);
      break;
    }
    case PICKPOINT: {
      CHECK_RANGE(shape->data+0);
      break;
    }
    case LINE: {
      CHECK_RANGE(shape->data+0);
      CHECK_RANGE(shape->data+3);
      break;
    }
    case TRIANGLE: {
      CHECK_RANGE(shape->data+0);
      CHECK_RANGE(shape->data+3);
      CHECK_RANGE(shape->data+6);
      break;
    }
    case TRINORM: {
      CHECK_RANGE(shape->data+0);
      CHECK_RANGE(shape->data+3);
      CHECK_RANGE(shape->data+6);
      break;
    }
    case TRICOLOR: {
      CHECK_RANGE(shape->data+0);
      CHECK_RANGE(shape->data+3);
      CHECK_RANGE(shape->data+6);
      break;
    }
    case CYLINDER: {
      CHECK_RANGE(shape->data+0);
      CHECK_RANGE(shape->data+3);
      break;
    }
    case CONE: {
      CHECK_RANGE(shape->data+0);
      CHECK_RANGE(shape->data+3);
      break;
    }
    case SPHERE: { // I suppose I should include +/- radius ...
      CHECK_RANGE(shape->data+0);
      break;
    }
    case TEXT: {   // I suppose I should include the string length size...
      CHECK_RANGE(shape->data+0);
      break;
    }
    default:
      break;
    }
  }

  // compute the values for center of volume center and scale
  if (!found_one) {
    cov_pos[0] = cov_pos[1] = cov_pos[2];
    cov_scale = 0.1f;
  } else {
    cov_pos[0] = (minx + maxx) / 2.0f;
    cov_pos[1] = (miny + maxy) / 2.0f;
    cov_pos[2] = (minz + maxz) / 2.0f;
    float dx = maxx - minx;
    float dy = maxy - miny;
    float dz = maxz - minz;
    // a bit of sanity check (eg, suppose there is only one point)
    if (dx == 0 && dy == 0 && dz == 0) dx = 10;
    if (dx > dy) {
      if (dx > dz) {
        cov_scale = 2.0f / dx;
      } else {
        cov_scale = 2.0f / dz;
      }
    } else {
      if (dy > dz) {
        cov_scale = 2.0f / dy;
      } else {
        cov_scale = 2.0f / dz;
      }
    }
  }
}
Exemplo n.º 12
0
Arquivo: type.c Projeto: mk12/eva
static struct EvalError *check_stdproc(
		enum StandardProcedure stdproc, struct Expression *args, size_t n) {
	switch (stdproc) {
	case S_APPLY:;
		Arity arity;
		if (!expression_arity(&arity, args[0])) {
			return new_eval_error_expr(ERR_TYPE_OPERATOR, args[0]);
		}
		size_t length;
		if (!count_list(&length, args[n-1])) {
			return new_syntax_error(args[n-1]);
		}
		size_t n_args = length + n - 2;
		if (!arity_allows(arity, n_args)) {
			return new_arity_error(arity, n_args);
		}
		break;
	case S_MACRO:
		if (args[0].type != E_STDPROCEDURE && args[0].type != E_PROCEDURE) {
			return new_type_error(E_PROCEDURE, args, 0);
		}
		break;
	case S_NUM_EQ:
	case S_NUM_LT:
	case S_NUM_GT:
	case S_NUM_LE:
	case S_NUM_GE:
	case S_ADD:
	case S_SUB:
	case S_MUL:
	case S_EXPT:
	case S_INTEGER_TO_CHAR:
	case S_NUMBER_TO_STRING:
		for (size_t i = 0; i < n; i++) {
			CHECK_TYPE(E_NUMBER, i);
		}
		break;
	case S_DIV:
	case S_REMAINDER:
	case S_MODULO:
		for (size_t i = 0; i < n; i++) {
			CHECK_TYPE(E_NUMBER, i);
			if (i > 0 && args[i].number == 0) {
				// This is not technically a type error, but this is the
				// earliest and most convenient place to catch it.
				return new_eval_error(ERR_DIV_ZERO);
			}
		}
		break;
	case S_CAR:
	case S_CDR:
	case S_SET_CAR:
	case S_SET_CDR:
		CHECK_TYPE(E_PAIR, 0);
		break;
	case S_STRING_LENGTH:
	case S_STRING_EQ:
	case S_STRING_LT:
	case S_STRING_GT:
	case S_STRING_LE:
	case S_STRING_GE:
	case S_STRING_COPY:
	case S_STRING_APPEND:
	case S_STRING_TO_SYMBOL:
	case S_STRING_TO_NUMBER:
	case S_LOAD:
		for (size_t i = 0; i < n; i++) {
			CHECK_TYPE(E_STRING, i);
		}
		break;
	case S_MAKE_STRING:
		CHECK_TYPE(E_NUMBER, 0);
		CHECK_TYPE(E_CHARACTER, 1);
		if (args[0].number < 0) {
			return new_eval_error_expr(ERR_NEGATIVE_SIZE, args[0]);
		}
		break;
	case S_STRING_REF:
		CHECK_TYPE(E_STRING, 0);
		CHECK_TYPE(E_NUMBER, 1);
		CHECK_RANGE(0, 1);
		break;
	case S_STRING_SET:
		CHECK_TYPE(E_STRING, 0);
		CHECK_TYPE(E_NUMBER, 1);
		CHECK_TYPE(E_CHARACTER, 2);
		CHECK_RANGE(0, 1);
		break;
	case S_SUBSTRING:
		CHECK_TYPE(E_STRING, 0);
		CHECK_TYPE(E_NUMBER, 1);
		CHECK_TYPE(E_NUMBER, 2);
		CHECK_RANGE(0, 1);
		CHECK_RANGE(0, 2);
		break;
	case S_STRING_FILL:
		CHECK_TYPE(E_STRING, 0);
		CHECK_TYPE(E_CHARACTER, 1);
		break;
	case S_CHAR_EQ:
	case S_CHAR_LT:
	case S_CHAR_GT:
	case S_CHAR_LE:
	case S_CHAR_GE:
	case S_CHAR_TO_INTEGER:
		for (size_t i = 0; i < n; i++) {
			CHECK_TYPE(E_CHARACTER, i);
		}
		break;
	case S_SYMBOL_TO_STRING:
		CHECK_TYPE(E_SYMBOL, 0);
		break;
	default:
		break;
	}
	return NULL;
}
Exemplo n.º 13
0
PyObject *
pylzma_compress(PyObject *self, PyObject *args, PyObject *kwargs)
{
    PyObject *result = NULL;
    CLzmaEncProps props;
    CLzmaEncHandle encoder=NULL;
    CMemoryOutStream outStream;
    CMemoryInStream inStream;
    Byte header[LZMA_PROPS_SIZE];
    size_t headerSize = LZMA_PROPS_SIZE;
    int res;    
    // possible keywords for this function
    static char *kwlist[] = {"data", "dictionary", "fastBytes", "literalContextBits",
                             "literalPosBits", "posBits", "algorithm", "eos", "multithreading", "matchfinder", NULL};
    int dictionary = 23;         // [0,27], default 23 (8MB)
    int fastBytes = 128;         // [5,273], default 128
    int literalContextBits = 3;  // [0,8], default 3
    int literalPosBits = 0;      // [0,4], default 0
    int posBits = 2;             // [0,4], default 2
    int eos = 1;                 // write "end of stream" marker?
    int multithreading = 1;      // use multithreading if available?
    char *matchfinder = NULL;    // matchfinder algorithm
    int algorithm = 2;
    char *data;
    int length;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s#|iiiiiiiis", kwlist, &data, &length, &dictionary, &fastBytes,
                                                                  &literalContextBits, &literalPosBits, &posBits, &algorithm, &eos, &multithreading, &matchfinder))
        return NULL;
    
    outStream.data = NULL;
    CHECK_RANGE(dictionary,         0,  27, "dictionary must be between 0 and 27");
    CHECK_RANGE(fastBytes,          5, 273, "fastBytes must be between 5 and 273");
    CHECK_RANGE(literalContextBits, 0,   8, "literalContextBits must be between 0 and 8");
    CHECK_RANGE(literalPosBits,     0,   4, "literalPosBits must be between 0 and 4");
    CHECK_RANGE(posBits,            0,   4, "posBits must be between 0 and 4");
    CHECK_RANGE(algorithm,          0,   2, "algorithm must be between 0 and 2");
    
    if (matchfinder != NULL) {
#if (PY_VERSION_HEX >= 0x02050000)
        PyErr_WarnEx(PyExc_DeprecationWarning, "matchfinder selection is deprecated and will be ignored", 1);
#else
        PyErr_Warn(PyExc_DeprecationWarning, "matchfinder selection is deprecated and will be ignored");
#endif
    }
    
    encoder = LzmaEnc_Create(&allocator);
    if (encoder == NULL)
        return PyErr_NoMemory();
    
    CreateMemoryInStream(&inStream, (Byte *) data, length);
    CreateMemoryOutStream(&outStream);
    
    LzmaEncProps_Init(&props);
    
    props.dictSize = 1 << dictionary;
    props.lc = literalContextBits;
    props.lp = literalPosBits;
    props.pb = posBits;
    props.algo = algorithm;
    props.fb = fastBytes;
    // props.btMode = 1;
    // props.numHashBytes = 4;
    // props.mc = 32;
    props.writeEndMark = eos ? 1 : 0;
    props.numThreads = multithreading ? 2 : 1;
    LzmaEncProps_Normalize(&props);
    res = LzmaEnc_SetProps(encoder, &props);
    if (res != SZ_OK) {
        PyErr_Format(PyExc_TypeError, "could not set encoder properties: %d", res);
        goto exit;
    }

    Py_BEGIN_ALLOW_THREADS
    LzmaEnc_WriteProperties(encoder, header, &headerSize);
    if (outStream.s.Write(&outStream, header, headerSize) != headerSize) {
        res = SZ_ERROR_WRITE;
    } else {
        res = LzmaEnc_Encode(encoder, &outStream.s, &inStream.s, NULL, &allocator, &allocator);
    }
    Py_END_ALLOW_THREADS
    if (res != SZ_OK) {
        PyErr_Format(PyExc_TypeError, "Error during compressing: %d", res);
        goto exit;
    }
    
    result = PyBytes_FromStringAndSize((const char *) outStream.data, outStream.size);
    
exit:
    if (encoder != NULL) {
        LzmaEnc_Destroy(encoder, &allocator, &allocator);
    }
    if (outStream.data != NULL) {
        free(outStream.data);
    }
    
    return result;
}
Exemplo n.º 14
0
void
intel_blt_copy(struct intel_batchbuffer *batch,
	      drm_intel_bo *src_bo, int src_x1, int src_y1, int src_pitch,
	      drm_intel_bo *dst_bo, int dst_x1, int dst_y1, int dst_pitch,
	      int width, int height, int bpp)
{
	uint32_t src_tiling, dst_tiling, swizzle;
	uint32_t cmd_bits = 0;
	uint32_t br13_bits;

	drm_intel_bo_get_tiling(src_bo, &src_tiling, &swizzle);
	drm_intel_bo_get_tiling(dst_bo, &dst_tiling, &swizzle);

	if (IS_965(batch->devid) && src_tiling != I915_TILING_NONE) {
		src_pitch /= 4;
		cmd_bits |= XY_SRC_COPY_BLT_SRC_TILED;
	}

	if (IS_965(batch->devid) && dst_tiling != I915_TILING_NONE) {
		dst_pitch /= 4;
		cmd_bits |= XY_SRC_COPY_BLT_DST_TILED;
	}

	br13_bits = 0;
	switch (bpp) {
	case 8:
		break;
	case 16:		/* supporting only RGB565, not ARGB1555 */
		br13_bits |= 1 << 24;
		break;
	case 32:
		br13_bits |= 3 << 24;
		cmd_bits |= XY_SRC_COPY_BLT_WRITE_ALPHA |
			    XY_SRC_COPY_BLT_WRITE_RGB;
		break;
	default:
		abort();
	}

#define CHECK_RANGE(x)	((x) >= 0 && (x) < (1 << 15))
	assert(CHECK_RANGE(src_x1) && CHECK_RANGE(src_y1) &&
	       CHECK_RANGE(dst_x1) && CHECK_RANGE(dst_y1) &&
	       CHECK_RANGE(width) && CHECK_RANGE(height) &&
	       CHECK_RANGE(src_x1 + width) && CHECK_RANGE(src_y1 + height) &&
	       CHECK_RANGE(dst_x1 + width) && CHECK_RANGE(dst_y1 + height) &&
	       CHECK_RANGE(src_pitch) && CHECK_RANGE(dst_pitch));
#undef CHECK_RANGE

	BEGIN_BATCH(8);
	OUT_BATCH(XY_SRC_COPY_BLT_CMD | cmd_bits);
	OUT_BATCH((br13_bits) |
		  (0xcc << 16) | /* copy ROP */
		  dst_pitch);
	OUT_BATCH((dst_y1 << 16) | dst_x1); /* dst x1,y1 */
	OUT_BATCH(((dst_y1 + height) << 16) | (dst_x1 + width)); /* dst x2,y2 */
	OUT_RELOC(dst_bo, I915_GEM_DOMAIN_RENDER, I915_GEM_DOMAIN_RENDER, 0);
	OUT_BATCH((src_y1 << 16) | src_x1); /* src x1,y1 */
	OUT_BATCH(src_pitch);
	OUT_RELOC(src_bo, I915_GEM_DOMAIN_RENDER, 0, 0);
	ADVANCE_BATCH();

	intel_batchbuffer_flush(batch);
}
Exemplo n.º 15
0
//! setting cursor sensitivity (0.0 - min, 1.0 - max)
void CWin32CursorControl::setSensitivity(f32 sens )
{
	m_Sensitivity = sens;

	CHECK_RANGE(m_Sensitivity, 0.01f, 1.0f);
}
Exemplo n.º 16
0
static void sirf_update(void)
{
    int i, j, ch, sv;
    unsigned char *buf;
    size_t len;
    uint8_t dgps;
    char tbuf[JSON_DATE_MAX+1];

    buf = session.lexer.outbuffer + 4;
    len = session.lexer.outbuflen - 8;
    switch (buf[0]) {
    case 0x02:			/* Measured Navigation Data */
	(void)wmove(mid2win, 1, 6);	/* ECEF position */
	(void)wprintw(mid2win, "%8d %8d %8d", getbes32(buf, 1),
		      getbes32(buf, 5), getbes32(buf, 9));
	(void)wmove(mid2win, 2, 6);	/* ECEF velocity */
	(void)wprintw(mid2win, "%8.1f %8.1f %8.1f",
		      (double)getbes16(buf, 13) / 8, (double)getbes16(buf,
								    15) / 8,
		      (double)getbes16(buf, 17) / 8);
	decode_ecef((double)getbes32(buf, 1), (double)getbes32(buf, 5),
		    (double)getbes32(buf, 9), (double)getbes16(buf, 13) / 8,
		    (double)getbes16(buf, 15) / 8, (double)getbes16(buf,
								  17) / 8);
	/* line 3 */
	(void)wmove(mid2win, 3, 7);
	(void)wprintw(mid2win, "%-24s",
			unix_to_iso8601(session.gpsdata.fix.time, tbuf, sizeof(tbuf))
			);
	(void)wmove(mid2win, 3, 38);
	(void)wattrset(mid2win, A_UNDERLINE);
	if (ppstime_enabled)
	   (void)wprintw(mid2win, "%02d", leapseconds);
	else
	   (void)wprintw(mid2win, "??");
	(void)wattrset(mid2win, A_NORMAL);
	/* line 4 */
	/* HDOP */
	(void)wmove(mid2win, 4, 59);
	(void)wprintw(mid2win, "%4.1f", (double)getub(buf, 20) / 5);
	/* Mode 1 */
	(void)wmove(mid2win, 4, 69);
	(void)wprintw(mid2win, "%02x", getub(buf, 19));
	/* Mode 2 */
	(void)wmove(mid2win, 4, 77);
	(void)wprintw(mid2win, "%02x", getub(buf, 21));
	/* SVs in fix */
	(void)wmove(mid2win, 4, 6);
	(void)wprintw(mid2win, "%2d =                                     ",
		      (int)getub(buf, 28));
	/* SV list */
	(void)wmove(mid2win, 4, 10);
	/* coverity_submit[tainted_data] */
	for (i = 0; i < (int)getub(buf, 28); i++)
	   (void)wprintw(mid2win, " %2d", (int)getub(buf, 29 + i));
	monitor_log("MND 0x02=");
	break;

    case 0x04:			/* Measured Tracking Data */
	ch = (int)getub(buf, 7);
	for (i = 0; i < ch; i++) {
	    int az, el, state, off;
	    double cn;

	    off = 8 + 15 * i;
	    (void)wmove(mid4win, i + 2, 3);

	    sv = (int)getub(buf, off);
	    az = (int)getub(buf, off + 1) * 3 / 2;
	    el = (int)getub(buf, off + 2) / 2;
	    state = (int)getbeu16(buf, off + 3);
	    cn = 0;
	    for (j = 0; j < 10; j++)
		cn += (int)getub(buf, off + 5 + j);
	    cn /= 10;

	    (void)wprintw(mid4win, " %3d %3d %2d %04x %4.1f %c",
			   sv, az, el, state, cn, state == 0xbf ? 'T' : ' ');
	}
	monitor_log("MTD 0x04=");
	break;

#ifdef __UNUSED__
    case 0x05:			/* raw track data */
	for (off = 1; off < len; off += 51) {
	    ch = getbeu32(buf, off);
	    (void)wmove(mid4win, ch + 2, 19);
	    cn = 0;

	    for (j = 0; j < 10; j++)
		cn += getub(buf, off + 34 + j);

	    printw("%5.1f", (double)cn / 10);

	    printw("%9d%3d%5d", getbeu32(buf, off + 8),
		   (int)getbeu16(buf, off + 12), (int)getbeu16(buf, off + 14));
	    printw("%8.5f %10.5f", (double)getbeu32(buf, off + 16) / 65536,
		   (double)getbeu32(buf, off + 20) / 1024);
	}
	monitor_log("RTD 0x05=");
	break;
#endif /* __UNUSED */

    case 0x06:			/* firmware version */
	display(mid6win, 1, 1, "%s", buf + 1);
	monitor_log("FV  0x06=");
	break;

    case 0x07:			/* Response - Clock Status Data */
	display(mid7win, 1, 5, "%2d", getub(buf, 7));	/* SVs */
	display(mid7win, 1, 16, "%lu", getbeu32(buf, 8));	/* Clock ppstimes */
	display(mid7win, 1, 29, "%lu", getbeu32(buf, 12));	/* Clock Bias */
	display(mid7win, 2, 11, "%lu", getbeu32(buf, 16));	/* Estimated Time */
	monitor_log("CSD 0x07=");
	break;

    case 0x08:			/* 50 BPS data */
	ch = (int)getub(buf, 1);
	sv = (int)getub(buf, 2);
	display(mid4win, ch + 2, 27, "%2d", sv);
	subframe_enabled = true;
	monitor_log("50B 0x08=");
	break;

    case 0x09:			/* Throughput */
	display(mid9win, 1, 6, "%.3f", (double)getbeu16(buf, 1) / 186);	/*SegStatMax */
	display(mid9win, 1, 18, "%.3f", (double)getbeu16(buf, 3) / 186);	/*SegStatLat */
	display(mid9win, 1, 31, "%.3f", (double)getbeu16(buf, 5) / 186);	/*SegStatTime */
	display(mid9win, 1, 42, "%3d", (int)getbeu16(buf, 7));	/* Last Millisecond */
	monitor_log("THR 0x09=");
	break;

    case 0x0b:			/* Command Acknowledgement */
	monitor_log("ACK 0x0b=");
	break;

    case 0x0c:			/* Command NAcknowledgement */
	monitor_log("NAK 0x0c=");
	break;

    case 0x0d:			/* Visible List */
	display(mid13win, 1, 1, "%02d =                                            ",
				 getub(buf, 1));
	(void)wmove(mid13win, 1, 5);
	for (i = 0; i < (int)getub(buf, 1); i++)
	    (void)wprintw(mid13win, " %d", getub(buf, 2 + 5 * i));
	monitor_log("VL  0x0d=");
	break;

    case 0x13:
#define YESNO(n)	(((int)getub(buf, n) != 0)?'Y':'N')
	display(mid19win, 1, 20, "%d", getub(buf, 5));	/* Alt. hold mode */
	display(mid19win, 2, 20, "%d", getub(buf, 6));	/* Alt. hold source */
	display(mid19win, 3, 20, "%dm", (int)getbeu16(buf, 7));	/* Alt. source input */
	if (getub(buf, 9) != (uint8_t) '\0')
	    display(mid19win, 4, 20, "%dsec", getub(buf, 10));	/* Degraded timeout */
	else
	    display(mid19win, 4, 20, "N/A   ");
	display(mid19win, 5, 20, "%dsec", getub(buf, 11));	/* DR timeout */
	display(mid19win, 6, 20, "%c", YESNO(12));	/* Track smooth mode */
	display(mid19win, 7, 20, "%c", YESNO(13));	/* Static Nav. */
	display(mid19win, 8, 20, "0x%x", getub(buf, 14));	/* 3SV Least Squares */
	display(mid19win, 9, 20, "0x%x", getub(buf, 19));	/* DOP Mask mode */
	display(mid19win, 10, 20, "0x%x", (int)getbeu16(buf, 20));	/* Nav. Elev. mask */
	display(mid19win, 11, 20, "0x%x", getub(buf, 22));	/* Nav. Power mask */
	display(mid19win, 12, 20, "0x%x", getub(buf, 27));	/* DGPS Source */
	display(mid19win, 13, 20, "0x%x", getub(buf, 28));	/* DGPS Mode */
	display(mid19win, 14, 20, "%dsec", getub(buf, 29));	/* DGPS Timeout */
	display(mid19win, 1, 42, "%c", YESNO(34));	/* LP Push-to-Fix */
	display(mid19win, 2, 42, "%dms", getbeu32(buf, 35));	/* LP On Time */
	display(mid19win, 3, 42, "%d", getbeu32(buf, 39));	/* LP Interval */
	display(mid19win, 4, 42, "%c", YESNO(43));	/* User Tasks enabled */
	display(mid19win, 5, 42, "%d", getbeu32(buf, 44));	/* User Task Interval */
	display(mid19win, 6, 42, "%c", YESNO(48));	/* LP Power Cycling Enabled */
	display(mid19win, 7, 42, "%d", getbeu32(buf, 49));	/* LP Max Acq Search Time */
	display(mid19win, 8, 42, "%d", getbeu32(buf, 53));	/* LP Max Off Time */
	display(mid19win, 9, 42, "%c", YESNO(57));	/* APM Enabled */
	display(mid19win, 10, 42, "%d", (int)getbeu16(buf, 58));	/* # of fixes */
	display(mid19win, 11, 42, "%d", (int)getbeu16(buf, 60));	/* Time Between fixes */
	display(mid19win, 12, 42, "%d", getub(buf, 62));	/* H/V Error Max */
	display(mid19win, 13, 42, "%d", getub(buf, 63));	/* Response Time Max */
	display(mid19win, 14, 42, "%d", getub(buf, 64));	/* Time/Accu & Duty Cycle Priority */
#undef YESNO
	monitor_log("NP  0x13=");
	break;

    case 0x1b:
	/******************************************************************
	 Not actually documented in any published materials before the
	 1.6 version of the SiRF binary protocol manual.
	 Here is what Chris Kuethe got from the SiRF folks,
	 (plus some corrections from the GpsPaSsion forums):

	Start of message
	----------------
	Message ID          1 byte    27
	Correction Source   1 byte    0=None, 1=SBAS, 2=Serial, 3=Beacon,
	4=Software

	total:              2 bytes

	Middle part of message varies if using beacon or other:
	-------------------------------------------------------
	If Beacon:
	Receiver Freq Hz    4 bytes
	Bit rate BPS        1 byte
	Status bit map      1 byte    01=Signal Valid,
				      02=Auto frequency detect
				      04=Auto bit rate detect
	Signal Magnitude    4 bytes   Note: in internal units
	Signal Strength dB  2 bytes   derived from Signal Magnitude
	SNR  dB             2 bytes

	total:             14 bytes

	If Not Beacon:
	Correction Age[12]  1 byte x 12  Age in seconds in same order as follows
	Reserved            2 bytes

	total:             14 bytes

	End of Message
	--------------
	Repeated 12 times (pad with 0 if less than 12 SV corrections):
	SVID                1 byte
	Correction (cm)     2 bytes (signed short)

	total               3 x 12 = 36 bytes
	******************************************************************/
	dgps = getub(buf, 1);
	display(mid27win, 1, 1, "%8s =                                      ",
		(CHECK_RANGE(dgpsvec, dgps) ? dgpsvec[dgps] : "???"));
	(void)wmove(mid27win, 1, 11);
	for (ch = 0; ch < SIRF_CHANNELS; ch++)
	    if (getub(buf, 16 + 3 * ch) != '\0')
		(void)wprintw(mid27win, " %d", getub(buf, 16 + 3 * ch));
	monitor_log("DST 0x1b=");
	break;

    case 0x1c:			/* NL Measurement Data */
    case 0x1d:			/* NL DGPS Data */
    case 0x1e:			/* NL SV State Data */
    case 0x1f:			/* NL Initialized Data */
	subframe_enabled = true;
	monitor_log("NL  0x%02x=", buf[0]);
	break;

    case 0x29:			/* Geodetic Navigation Data */
	monitor_log("GND 0x29=");
	break;

    case 0x32:			/* SBAS Parameters */
	monitor_log("SBP 0x32=");
	break;

    case 0x34:			/* PPS Time */
	ppstime_enabled = true;
	leapseconds = (int)getbeu16(buf, 8);
	monitor_log("PPS 0x34=");
	break;

    case 0xff:			/* Development Data */
	while (len > 0 && buf[len - 1] == '\n')
	    len--;
	while (len > 0 && buf[len - 1] == ' ')
	    len--;
	buf[len] = '\0';
	j = 1;
	for (i = 0; verbpat[i] != NULL; i++)
	    if (str_starts_with((char *)(buf + 1), verbpat[i])) {
		j = 0;
		break;
	    }
	if (j != 0)
	    monitor_log("%s\n", buf + 1);
	monitor_log("DD  0xff=");
	break;

    default:
	monitor_log("UNK 0x%02x=", buf[0]);
	break;
    }

#ifdef CONTROLSEND_ENABLE
    /* elicit navigation parameters */
    if (dispmode && (time(NULL) % 10 == 0)) {
	(void)monitor_control_send((unsigned char *)"\x98\x00", 2);
    }
#endif /* CONTROLSEND_ENABLE */

    /* clear the 50bps data field every 6 seconds */
    if (subframe_enabled && (time(NULL) % 6 == 0)) {
	for (ch = 0; ch < SIRF_CHANNELS; ch++)
	   display(mid4win, ch + 2, 27, "  ");
    }

    if (dispmode) {
	(void)touchwin(mid19win);
	(void)wnoutrefresh(mid19win);
    }

#ifdef PPS_ENABLE
    pps_update(mid7win, 2, 32);
#endif /* PPS_ENABLE */
}
Exemplo n.º 17
0
static void udpConnectTo(String* connectToAddress,
                         Dict* config,
                         struct UDPInterface* udpContext,
                         struct Context* ctx)
{
    String* password = Dict_getString(config, BSTR("password"));
    int64_t* authType = Dict_getInt(config, BSTR("authType"));
    String* publicKey = Dict_getString(config, BSTR("publicKey"));
    int64_t* trust = Dict_getInt(config, BSTR("trust"));

    #define FAIL_IF_NULL(cannotBeNull, fieldName) \
        if (!cannotBeNull) {                                                     \
            fprintf(stderr,                                                      \
                    "interfaces.UDPInterface['%s']." fieldName " is not set, "   \
                    "this field is mandatory.\n",                                \
                    connectToAddress->bytes);                                    \
            exit(-1);                                                            \
        }

    FAIL_IF_NULL(password, "password")
    FAIL_IF_NULL(authType, "authType")
    FAIL_IF_NULL(publicKey, "publicKey")
    FAIL_IF_NULL(trust, "trust")

    #undef FAIL_IF_NULL

    #define CHECK_RANGE(number, min, max) \
        if (number < min || number > max) {                                           \
        fprintf(stderr,                                                               \
                "interfaces.UDPInterface['%s'].number must be between min and max\n", \
                connectToAddress->bytes);                                             \
        exit(-1);                                                                     \
    }

    CHECK_RANGE(*authType, 1, 255)
    CHECK_RANGE(*trust, 0, INT64_MAX)

    #undef CHECK_RANGE

    uint8_t pkBytes[32];
    if (publicKey->len < 52 || Base32_decode(pkBytes, 32, (uint8_t*)publicKey->bytes, 52) != 32) {
        fprintf(stderr,
                "interfaces.UDPInterface['%s'].publicKey could not be parsed.\n",
                connectToAddress->bytes);
        exit(-1);
    }
    uint8_t addressBytes[16];
    AddressCalc_addressForPublicKey(addressBytes, pkBytes);
    if (addressBytes[0] != 0xFC) {
        fprintf(stderr,
                "interfaces.UDPInterface['%s'].publicKey\n( %s )\nis not in FC00/8 range, "
                "it was probably mistranscribed.\n",
                connectToAddress->bytes,
                publicKey->bytes);
        exit(-1);
    }

    struct Interface* udp =
        UDPInterface_addEndpoint(udpContext, connectToAddress->bytes, ctx->eHandler);
    struct Interface* authedUdp = CryptoAuth_wrapInterface(udp, pkBytes, false, true, ctx->ca);
    CryptoAuth_setAuth(password, *authType, authedUdp);

    uint64_t switchAddr_be;
    SwitchCore_addInterface(authedUdp, *trust, &switchAddr_be, ctx->switchCore);
    struct Address addr;
    memset(&addr, 0, sizeof(struct Address));
    memcpy(addr.key, pkBytes, 32);
    addr.networkAddress_be = switchAddr_be;
    RouterModule_addNode(&addr, ctx->routerModule);
}
Exemplo n.º 18
0
bool CTextureAnim::loadFromFile(io::IReadFile* file)
{
	if (!file)
		return false;

	io::IXMLReader* xml = FILE_SYSTEM.createXMLReader(file);

	if (!xml)
		return false;

	c8 ch[255];
	sprintf(ch, "Loading animated texture from %s", file->getFileName());
	LOGGER.log(ch, io::ELL_INFORMATION);		

	bool ani_tex_tag_founded = false; 

	core::array<core::stringc> filenames;

	while (xml->read())
	{
		if (xml->getNodeType()== io::EXN_ELEMENT)
		{
			core::stringw xml_node_name = xml->getName();

			if (core::stringw("AnimatedTexture") == xml_node_name)
			{
				ani_tex_tag_founded = true;	
				
				AnimatedTextureParameters.TimePerFrame = xml->getAttributeValueAsInt(L"time_per_frame");
				CHECK_RANGE(AnimatedTextureParameters.TimePerFrame, 10, 10000);

				AnimatedTextureParameters.Loop = xml->getAttributeValueAsInt(L"loop")==0?false:true;
			}
			else
			if (ani_tex_tag_founded && core::stringw("Frame") == xml_node_name)
			{
				core::stringc filename = xml->getAttributeValue(L"filename");
				
				if (filename.size()>0)
				{
					filenames.push_back(filename);
				}
			}
		}
	}

	xml->drop();

	s32 n_tex=0;

	if (filenames.size()>0)
	{
		// loading frames

		LOGGER.increaseFormatLevel();	

		core::stringc filepath = core::extractFilePath(core::stringc(file->getFileName()));

		for (u32 t=0; t<filenames.size(); t++)
		{
			core::stringc full_filename = filepath;
			
			full_filename.append(filenames[t]);

			vid::ITexture* tex = 
				VIDEO_DRIVER.getTexture(full_filename.c_str());

			if (tex)
			{
				addFrame(tex);

				n_tex++;
			}
		}

		LOGGER.decreaseFormatLevel();
	}	
	
	if (n_tex<=0)
	{
		LOGGER.log("Can't load animated texture, there is no any frames in it.", io::ELL_ERROR);		

		return false;
	}
	
	LOGGER.log("Loaded animated texture.", io::ELL_INFORMATION);

	return true;
}