Ejemplo n.º 1
0
/* This function not only tests the 'k' getargs code, but also the
   PyInt_AsUnsignedLongMask() and PyInt_AsUnsignedLongMask() functions. */
static PyObject *
test_k_code(PyObject *self)
{
	PyObject *tuple, *num;
	unsigned long value;

        tuple = PyTuple_New(1);
        if (tuple == NULL)
        	return NULL;

	/* a number larger than ULONG_MAX even on 64-bit platforms */
        num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
        if (num == NULL)
        	return NULL;

	value = PyInt_AsUnsignedLongMask(num);
	if (value != ULONG_MAX)
        	return raiseTestError("test_k_code",
	    "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");

        PyTuple_SET_ITEM(tuple, 0, num);

        value = 0;
        if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
        	return NULL;
        if (value != ULONG_MAX)
        	return raiseTestError("test_k_code",
			"k code returned wrong value for long 0xFFF...FFF");

	Py_DECREF(num);
        num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
        if (num == NULL)
        	return NULL;

	value = PyInt_AsUnsignedLongMask(num);
	if (value != (unsigned long)-0x42)
        	return raiseTestError("test_k_code",
	    "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");

        PyTuple_SET_ITEM(tuple, 0, num);

	value = 0;
        if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
        	return NULL;
        if (value != (unsigned long)-0x42)
        	return raiseTestError("test_k_code",
			"k code returned wrong value for long -0xFFF..000042");

	Py_DECREF(tuple);
	Py_INCREF(Py_None);
	return Py_None;
}
Ejemplo n.º 2
0
// Note: Python3 uses TO_INT2 function.
NUITKA_MAY_BE_UNUSED static PyObject *TO_LONG2( PyObject *value, PyObject *base )
{
    long base_int = PyInt_AsLong( base );

    if (unlikely( base_int == -1 ))
    {
        if (likely( ERROR_OCCURRED() ))
        {
            return NULL;
        }
    }

    if (unlikely( !Nuitka_String_Check( value ) && !PyUnicode_Check( value ) ))
    {
        PyErr_Format( PyExc_TypeError, "long() can't convert non-string with explicit base" );
        return NULL;
    }

    char *value_str = Nuitka_String_AsString( value );
    if (unlikely( value_str == NULL ))
    {
        return NULL;
    }

    PyObject *result = PyLong_FromString( value_str, NULL, base_int );
    if (unlikely( result == NULL ))
    {
        return NULL;
    }

    return result;
}
Ejemplo n.º 3
0
PyObject *
PyGcc_int_from_decimal_string_buffer(const char *buf)
{
    PyObject *long_obj;
#if PY_MAJOR_VERSION < 3
    long long_val;
    int overflow;
#endif
    long_obj = PyLong_FromString((char *)buf, NULL, 10);
    if (!long_obj) {
        return NULL;
    }
#if PY_MAJOR_VERSION >= 3
    return long_obj;
#else
    long_val = PyLong_AsLongAndOverflow(long_obj, &overflow);
    if (overflow) {
        /* Doesn't fit in a PyIntObject; use the PyLongObject: */
        return long_obj;
    } else {
        /* Fits in a PyIntObject: use that */
        PyObject *int_obj = PyInt_FromLong(long_val);
        if (!int_obj) {
            return long_obj;
        }
        Py_DECREF(long_obj);
        return int_obj;
    }
#endif
}
Ejemplo n.º 4
0
PyObject* integer_to_PyLong(const lp_integer_t* x) {
  char* str = lp_integer_to_string(x);
  char* str_p = 0;
  PyObject* result = PyLong_FromString(str, &str_p, 10);
  free(str);
  return result;
}
Ejemplo n.º 5
0
PyObject *
gcc_python_int_from_double_int(double_int di, bool is_unsigned)
{
    PyObject *long_obj;
#if PY_MAJOR_VERSION < 3
    long long_val;
    int overflow;
#endif
    char buf[512]; /* FIXME */
    gcc_python_double_int_as_text(di, is_unsigned, buf, sizeof(buf));

    long_obj = PyLong_FromString(buf, NULL, 10);
    if (!long_obj) {
        return NULL;
    }
#if PY_MAJOR_VERSION >= 3
    return long_obj;
#else
    long_val = PyLong_AsLongAndOverflow(long_obj, &overflow);
    if (overflow) {
        /* Doesn't fit in a PyIntObject; use the PyLongObject: */
        return long_obj;
    } else {
        /* Fits in a PyIntObject: use that */
        PyObject *int_obj = PyInt_FromLong(long_val);
        if (!int_obj) {
            return long_obj;
        }
        Py_DECREF(long_obj);
        return int_obj;
    }
#endif
}
Ejemplo n.º 6
0
static PyObject *from_uint128(const MMDB_entry_data_list_s *entry_data_list)
{
    uint64_t high = 0;
    uint64_t low = 0;
#if MMDB_UINT128_IS_BYTE_ARRAY
    int i;
    for (i = 0; i < 8; i++) {
        high = (high << 8) | entry_data_list->entry_data.uint128[i];
    }

    for (i = 8; i < 16; i++) {
        low = (low << 8) | entry_data_list->entry_data.uint128[i];
    }
#else
    high = entry_data_list->entry_data.uint128 >> 64;
    low = (uint64_t)entry_data_list->entry_data.uint128;
#endif

    char *num_str = malloc(33);
    if (NULL == num_str) {
        PyErr_NoMemory();
        return NULL;
    }

    snprintf(num_str, 33, "%016" PRIX64 "%016" PRIX64, high, low);

    PyObject *py_obj = PyLong_FromString(num_str, NULL, 16);

    free(num_str);
    return py_obj;
}
Ejemplo n.º 7
0
extern "C" PyObject* PyInt_FromString(const char* s, char** pend, int base) noexcept {
    char* end;
    long x;
    Py_ssize_t slen;
    PyObject* sobj, *srepr;

    if ((base != 0 && base < 2) || base > 36) {
        PyErr_SetString(PyExc_ValueError, "int() base must be >= 2 and <= 36");
        return NULL;
    }

    while (*s && isspace(Py_CHARMASK(*s)))
        s++;
    errno = 0;
    if (base == 0 && s[0] == '0') {
        x = (long)strtoul(s, &end, base);
        if (x < 0)
            return PyLong_FromString(s, pend, base);
    } else
        x = strtoul(s, &end, base);
    if (end == s || !isalnum(Py_CHARMASK(end[-1])))
        goto bad;
    while (*end && isspace(Py_CHARMASK(*end)))
        end++;
    if (*end != '\0') {
    bad:
        slen = strlen(s) < 200 ? strlen(s) : 200;
        sobj = PyString_FromStringAndSize(s, slen);
        if (sobj == NULL)
            return NULL;
        srepr = PyObject_Repr(sobj);
        Py_DECREF(sobj);
        if (srepr == NULL)
            return NULL;
        PyErr_Format(PyExc_ValueError, "invalid literal for int() with base %d: %s", base, PyString_AS_STRING(srepr));
        Py_DECREF(srepr);
        return NULL;
    } else if (errno != 0)
        return PyLong_FromString(s, pend, base);
    if (pend)
        *pend = end;
    return PyInt_FromLong(x);
}
static PyObject *
typecast_LONGINTEGER_cast(const char *s, Py_ssize_t len, PyObject *curs)
{
    char buffer[24];

    if (s == NULL) {Py_INCREF(Py_None); return Py_None;}
    if (s[len] != '\0') {
        strncpy(buffer, s, (size_t) len); buffer[len] = '\0';
        s = buffer;
    }
    return PyLong_FromString((char *)s, NULL, 0);
}
Ejemplo n.º 9
0
BoxedLong* _longNew(Box* val, Box* _base) {
    BoxedLong* rtn = new BoxedLong();
    if (_base) {
        if (!isSubclass(_base->cls, int_cls))
            raiseExcHelper(TypeError, "an integer is required");
        int base = static_cast<BoxedInt*>(_base)->n;

        if (!isSubclass(val->cls, str_cls))
            raiseExcHelper(TypeError, "long() can't convert non-string with explicit base");
        BoxedString* s = static_cast<BoxedString*>(val);

        rtn = (BoxedLong*)PyLong_FromString(s->data(), NULL, base);
        checkAndThrowCAPIException();
    } else {
        if (isSubclass(val->cls, long_cls)) {
            BoxedLong* l = static_cast<BoxedLong*>(val);
            if (val->cls == long_cls)
                return l;
            BoxedLong* rtn = new BoxedLong();
            mpz_init_set(rtn->n, l->n);
            return rtn;
        } else if (isSubclass(val->cls, int_cls)) {
            mpz_init_set_si(rtn->n, static_cast<BoxedInt*>(val)->n);
        } else if (val->cls == str_cls) {
            llvm::StringRef s = static_cast<BoxedString*>(val)->s();
            assert(s.data()[s.size()] == '\0');
            int r = mpz_init_set_str(rtn->n, s.data(), 10);
            RELEASE_ASSERT(r == 0, "");
        } else if (val->cls == float_cls) {
            mpz_init_set_si(rtn->n, static_cast<BoxedFloat*>(val)->d);
        } else {
            static BoxedString* long_str = static_cast<BoxedString*>(PyString_InternFromString("__long__"));
            Box* r = callattr(val, long_str, CallattrFlags({.cls_only = true, .null_on_nonexistent = true }),
                              ArgPassSpec(0), NULL, NULL, NULL, NULL, NULL);

            if (!r) {
                fprintf(stderr, "TypeError: long() argument must be a string or a number, not '%s'\n",
                        getTypeName(val));
                raiseExcHelper(TypeError, "");
            }

            if (isSubclass(r->cls, int_cls)) {
                mpz_init_set_si(rtn->n, static_cast<BoxedInt*>(r)->n);
            } else if (!isSubclass(r->cls, long_cls)) {
                raiseExcHelper(TypeError, "__long__ returned non-long (type %s)", r->cls->tp_name);
            } else {
                return static_cast<BoxedLong*>(r);
            }
        }
    }
Ejemplo n.º 10
0
/* Add a check for embedded NULL-bytes in the argument. */
static PyObject *
long_from_string(const char *s, int len)
{
	char *end;
	PyObject *x;

	x = PyLong_FromString((char*)s, &end, 10);
	if (x == NULL)
		return NULL;
	if (end != s + len) {
		PyErr_SetString(PyExc_ValueError,
				"null byte in argument for long()");
		Py_DECREF(x);
		return NULL;
	}
	return x;
}
Ejemplo n.º 11
0
static PyObject *DateTime_long(DateTimeObj *v)
{
    char *end;
    char text[DATETIME_LEN];
    CS_RETCODE conv_result;

    /* PyErr_Clear(); */
    conv_result = datetime_as_string((PyObject*)v, text);
    if (PyErr_Occurred())
	return NULL;
    if (conv_result != CS_SUCCEED) {
	PyErr_SetString(PyExc_TypeError, "datetime to string conversion failed");
	return NULL;
    }

    return PyLong_FromString(text, &end, 10);
}
Ejemplo n.º 12
0
/* -interp, +buf */
static inline PyObject *CReader_readNum(CReader_Buffer *buffer)
 {
  PyObject *res;
  off_t pos = 0;
  char isf = 0;
  char isl = 0;
  char c;

  while (1)
   {
    if (!buffer->type->extend(buffer, pos + 1))
     break;
    c = buffer->buf[buffer->pos + pos];
    switch (c)
     {
      case SEPARATORS:
      case WHITESPACE:
       goto CReader_readNum_end;
      case 'F': case 'f': case 'E': case 'e': case '.':
       isf = 1;
       break;
      case 'L': case 'l':
       isl = 1;
       break;
     }
    pos++;
   }
  CReader_readNum_end:
  {
   char numstr[pos + 1];

   buffer->type->cut(buffer, numstr, pos); /* Nah, we've allready done extend on this, so this *can't* fail */
   numstr[pos] = '\0';

   CReader_Buffer_lockInterpreter(buffer);
   if (isf)
    res = PyFloat_FromDouble(atof(numstr));
   else if (isl)
    res = PyLong_FromString(numstr, NULL, 0);
   else
    res = PyInt_FromString(numstr, NULL, 0);
   CReader_Buffer_releaseInterpreter(buffer);
   return res;
  }
 }
Ejemplo n.º 13
0
std::shared_ptr<MI::MIValue> Str2PyLong2MI(char* strValue, MI_Type valueType)
{
    auto obj = PyLong_FromString(strValue, NULL, 10);
    if (!obj)
    {
        throw MI::TypeConversionException();
    }
    try
    {
        auto retVal = Py2MI(obj, valueType);
        Py_DECREF(obj);
        return retVal;
    }
    catch (std::exception&)
    {
        Py_DECREF(obj);
        throw;
    }
}
Ejemplo n.º 14
0
static PyObject *
get_serial_number (certificate_x509 *self, PyObject *args)
{
	PyObject *ret;

	if (!PyArg_ParseTuple (args, "")) {
		return NULL;
	}

	ASN1_INTEGER *serial_asn = X509_get_serialNumber (self->x509);
	BIGNUM *bn = ASN1_INTEGER_to_BN (serial_asn, NULL);

	char *hex = BN_bn2hex (bn);

	BN_free (bn);
	ret = PyLong_FromString (hex, NULL, 16);
	OPENSSL_free (hex);
	return ret;
}
Ejemplo n.º 15
0
@return: Serial number as a Python integer\n\
";

static PyObject *
crypto_X509_get_serial_number(crypto_X509Obj *self, PyObject *args)
{
    ASN1_INTEGER *asn1_i;
    BIGNUM *bignum;
    char *hex;
    PyObject *res;

    if (!PyArg_ParseTuple(args, ":get_serial_number"))
        return NULL;

    asn1_i = X509_get_serialNumber(self->x509);
    bignum = ASN1_INTEGER_to_BN(asn1_i, NULL);
    hex = BN_bn2hex(bignum);
    res = PyLong_FromString(hex, NULL, 16);
    BN_free(bignum);
    free(hex);
    return res;
}
Ejemplo n.º 16
0
static PyObject *
strop_atol(PyObject *self, PyObject *args)
{
	char *s, *end;
	int base = 10;
	PyObject *x;
	char buffer[256]; /* For errors */

	WARN;
	if (!PyArg_ParseTuple(args, "s|i:atol", &s, &base))
		return NULL;

	if ((base != 0 && base < 2) || base > 36) {
		PyErr_SetString(PyExc_ValueError, "invalid base for atol()");
		return NULL;
	}

	while (*s && isspace(Py_CHARMASK(*s)))
		s++;
	if (s[0] == '\0') {
		PyErr_SetString(PyExc_ValueError, "empty string for atol()");
		return NULL;
	}
	x = PyLong_FromString(s, &end, base);
	if (x == NULL)
		return NULL;
	if (base == 0 && (*end == 'l' || *end == 'L'))
		end++;
	while (*end && isspace(Py_CHARMASK(*end)))
		end++;
	if (*end != '\0') {
		PyOS_snprintf(buffer, sizeof(buffer),
			      "invalid literal for atol(): %.200s", s);
		PyErr_SetString(PyExc_ValueError, buffer);
		Py_DECREF(x);
		return NULL;
	}
	return x;
}
Ejemplo n.º 17
0
static int handle_number(void *ctx, const char *value, unsigned int length)
{
    _YajlDecoder *self = (_YajlDecoder *)(ctx);
    PyObject *object;
#ifdef IS_PYTHON3
    PyBytesObject *string;
#else
    PyObject *string;
#endif

    int floaty_char;

    // take a moment here to scan the input string to see if there's
    // any chars which suggest this is a floating point number
    for (floaty_char = 0; floaty_char < length; floaty_char++) {
        switch (value[floaty_char]) {
            case '.': case 'e': case 'E': goto floatin;
        }
    }

  floatin:
#ifdef IS_PYTHON3
    string = (PyBytesObject *)PyBytes_FromStringAndSize(value, length);
    if (floaty_char >= length) {
        object = PyLong_FromString(string->ob_sval, NULL, 10);
    } else {
        object = PyFloat_FromString((PyObject *)string);
    }
#else
    string = PyString_FromStringAndSize(value, length);
    if (floaty_char >= length) {
        object = PyInt_FromString(PyString_AS_STRING(string), NULL, 10);
    } else {
        object = PyFloat_FromString(string, NULL);
    }
#endif
    Py_XDECREF(string);
    return PlaceObject(self, object);
}
Ejemplo n.º 18
0
static int dict_set_numeric(PyObject* dict, const char* key, char* val){
  PyObject* obj = PyLong_FromString(val, NULL, 10);
  return dict_set(dict, key, obj);
}
Ejemplo n.º 19
0
/**
 * Set one or more options in a decoder instance.
 *
 * Handled options are removed from the hash.
 *
 * @param di Decoder instance.
 * @param options A GHashTable of options to set.
 *
 * @return SRD_OK upon success, a (negative) error code otherwise.
 */
SRD_API int srd_inst_option_set(struct srd_decoder_inst *di,
				GHashTable *options)
{
	PyObject *py_dec_options, *py_dec_optkeys, *py_di_options, *py_optval;
	PyObject *py_optlist, *py_classval;
	Py_UNICODE *py_ustr;
	unsigned long long int val_ull;
	int num_optkeys, ret, size, i;
	char *key, *value;

	if (!PyObject_HasAttrString(di->decoder->py_dec, "options")) {
		/* Decoder has no options. */
		if (g_hash_table_size(options) == 0) {
			/* No options provided. */
			return SRD_OK;
		} else {
			srd_err("Protocol decoder has no options.");
			return SRD_ERR_ARG;
		}
		return SRD_OK;
	}

	ret = SRD_ERR_PYTHON;
	key = NULL;
	py_dec_options = py_dec_optkeys = py_di_options = py_optval = NULL;
	py_optlist = py_classval = NULL;
	py_dec_options = PyObject_GetAttrString(di->decoder->py_dec, "options");

	/* All of these are synthesized objects, so they're good. */
	py_dec_optkeys = PyDict_Keys(py_dec_options);
	num_optkeys = PyList_Size(py_dec_optkeys);
	if (!(py_di_options = PyObject_GetAttrString(di->py_inst, "options")))
		goto err_out;
	for (i = 0; i < num_optkeys; i++) {
		/* Get the default class value for this option. */
		py_str_as_str(PyList_GetItem(py_dec_optkeys, i), &key);
		if (!(py_optlist = PyDict_GetItemString(py_dec_options, key)))
			goto err_out;
		if (!(py_classval = PyList_GetItem(py_optlist, 1)))
			goto err_out;
		if (!PyUnicode_Check(py_classval) && !PyLong_Check(py_classval)) {
			srd_err("Options of type %s are not yet supported.",
				Py_TYPE(py_classval)->tp_name);
			goto err_out;
		}

		if ((value = g_hash_table_lookup(options, key))) {
			/* An override for this option was provided. */
			if (PyUnicode_Check(py_classval)) {
				if (!(py_optval = PyUnicode_FromString(value))) {
					/* Some UTF-8 encoding error. */
					PyErr_Clear();
					goto err_out;
				}
			} else if (PyLong_Check(py_classval)) {
				if (!(py_optval = PyLong_FromString(value, NULL, 0))) {
					/* ValueError Exception */
					PyErr_Clear();
					srd_err("Option %s has invalid value "
						"%s: expected integer.",
						key, value);
					goto err_out;
				}
			}
			g_hash_table_remove(options, key);
		} else {
			/* Use the class default for this option. */
			if (PyUnicode_Check(py_classval)) {
				/* Make a brand new copy of the string. */
				py_ustr = PyUnicode_AS_UNICODE(py_classval);
				size = PyUnicode_GET_SIZE(py_classval);
				py_optval = PyUnicode_FromUnicode(py_ustr, size);
			} else if (PyLong_Check(py_classval)) {
				/* Make a brand new copy of the integer. */
				val_ull = PyLong_AsUnsignedLongLong(py_classval);
				if (val_ull == (unsigned long long)-1) {
					/* OverFlowError exception */
					PyErr_Clear();
					srd_err("Invalid integer value for %s: "
						"expected integer.", key);
					goto err_out;
				}
				if (!(py_optval = PyLong_FromUnsignedLongLong(val_ull)))
					goto err_out;
			}
		}

		/*
		 * If we got here, py_optval holds a known good new reference
		 * to the instance option to set.
		 */
		if (PyDict_SetItemString(py_di_options, key, py_optval) == -1)
			goto err_out;
	}

	ret = SRD_OK;

err_out:
	Py_XDECREF(py_optlist);
	Py_XDECREF(py_di_options);
	Py_XDECREF(py_dec_optkeys);
	Py_XDECREF(py_dec_options);
	g_free(key);
	if (PyErr_Occurred())
		srd_exception_catch("Stray exception in srd_inst_option_set().");

	return ret;
}
Ejemplo n.º 20
0
static void*
tns_parse_integer(const tns_ops *ops, const char *data, size_t len)
{
  long l = 0;
  long long ll = 0;
  int sign = 1;
  char c;
  char *dataend;
  const char *pos, *eod;
  PyObject *v = NULL;

  //  Anything with less than 10 digits, we can fit into a long.
  //  Hand-parsing, as we need tighter error-checking than strtol.
  if (len < 10) {
      pos = data;
      eod = data + len;
      c = *pos++;
      switch(c) {
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
          l = c - '0';
          break;
        case '+':
          break;
        case '-':
          sign = -1;
          break;
        default:
          sentinel("invalid integer literal");
      }
      while(pos < eod) {
          c = *pos++;
          check(c >= '0' && c <= '9', "invalid integer literal");
          l = (l * 10) + (c - '0');
      }
      return PyLong_FromLong(l * sign);
  }
  //  Anything with less than 19 digits fits in a long long.
  //  Hand-parsing, as we need tighter error-checking than strtoll.
  else if(len < 19) {
      pos = data;
      eod = data + len;
      c = *pos++;
      switch(c) {
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
          ll = c - '0';
          break;
        case '+':
          break;
        case '-':
          sign = -1;
          break;
        default:
          sentinel("invalid integer literal");
      }
      while(pos < eod) {
          c = *pos++;
          check(c >= '0' && c <= '9', "invalid integer literal");
          ll = (ll * 10) + (c - '0');
      }
      return PyLong_FromLongLong(ll * sign);
  }
  //  Really big numbers are passed to python's native parser.
  else { 
      // PyLong_FromString allows leading whitespace, so we have to check
      // that there is none present in the string.
      c = *data;
      switch(c) {
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
          break;
        case '+':
        case '-':
          c = *(data+1);
          check(c >= '0' && c <= '9', "invalid integer literal");
          break;
        default:
          sentinel("invalid integer literal");
      }
      // PyLong_FromString insists that the string end in a NULL byte.
      // I am *not* copying all that data.  Instead we lie a little bit
      // about the const-ness of data, write a NULL over the format terminator
      // and restore the original character when we're done.
      c = data[len];
      ((char*)data)[len] = '\0';
      v = PyLong_FromString((char *)data, &dataend, 10);
      ((char*)data)[len] = c;
      check(dataend == data + len, "invalid integer literal");
      return v;
  }
  sentinel("invalid code branch, check your compiler...");

error:
  return NULL;
}