Ejemplo n.º 1
0
TEST(KURLTest, strippedForUseAsReferrer)
{
    struct ReferrerCase {
        const char* input;
        const char* output;
    } referrerCases[] = {
        {"data:text/html;charset=utf-8,<html></html>", ""},
        {"javascript:void(0);", ""},
        {"about:config", ""},
        {"https://www.google.com/", "https://www.google.com/"},
        {"http://[email protected]:8888/", "http://news.google.com:8888/"},
        {"http://:[email protected]:8888/foo", "http://news.google.com:8888/foo"},
        {"http://*****:*****@news.google.com:8888/", "http://news.google.com:8888/"},
        {"https://www.google.com/a?f#b", "https://www.google.com/a?f"},
        {"file:///tmp/test.html", ""},
        {"https://www.google.com/#", "https://www.google.com/"},
    };

    for (size_t i = 0; i < arraysize(referrerCases); i++) {
        KURL kurl(ParsedURLString, referrerCases[i].input);
        String referrer = kurl.strippedForUseAsReferrer();
        EXPECT_STREQ(referrerCases[i].output, referrer.utf8().data());
    }
}
Ejemplo n.º 2
0
    bool CommandLine::IsSwitch(const StringType& parameter_string,
        std::string* switch_string, StringType* switch_value)
    {
        switch_string->clear();
        switch_value->clear();

        for(size_t i=0; i<arraysize(kSwitchPrefixes); ++i)
        {
            StringType prefix(kSwitchPrefixes[i]);
            if(parameter_string.find(prefix) != 0)
            {
                continue;
            }

            const size_t switch_start = prefix.length();
            const size_t equals_position = parameter_string.find(
                kSwitchValueSeparator, switch_start);
            StringType switch_native;
            if(equals_position == StringType::npos)
            {
                switch_native = parameter_string.substr(switch_start);
            }
            else
            {
                switch_native = parameter_string.substr(
                    switch_start, equals_position-switch_start);
                *switch_value = parameter_string.substr(equals_position+1);
            }
            *switch_string = WideToASCII(switch_native);
            Lowercase(switch_string);

            return true;
        }

        return false;
    }
Ejemplo n.º 3
0
Effect PolicyManager::checkRequest(Request * req){
	Effect xacml_eff;
	bool dhp_eff = false;
	int features = 0;
	vector<bool> purpose = req->getPurposeAttrs();

	LOGD("Policy manager start check");
	if(validPolicyFile) {
		selectedDHPref.first.clear();
		selectedDHPref.second = false;
		xacml_eff = policyDocument->evaluate(req, &selectedDHPref);
		LOGD("XACML response: %d", xacml_eff);

		// valid purposes vector
		LOGD("Ontology size = %d",arraysize(ontology_vector));
		if (purpose.size() == arraysize(ontology_vector)) {
			LOGD("PolicyManager: valid purposes vector");

			// in ProvisionalAction tags a single resouce requires a single DHPref
			// no more than one resouce must be used in non installation enforceRequest call
			if ((req->getResourceAttrs()).count(API_FEATURE) == 1) {
				features = (req->getResourceAttrs())[API_FEATURE]->size();
			}
			if (features == 1){
				LOGD("One feature requested, DHPref evaluation started");
				if (selectedDHPref.first.empty() == false) {
					LOGD("Selected DHPref: %s", selectedDHPref.first.c_str());
					DHPrefs::iterator it;
					it=(*dhp).find(selectedDHPref.first);
					if (it == (*dhp).end()){
						LOGD("DHPref: %s not found", selectedDHPref.first.c_str());
					}
					else {	
						LOGD("DHPref: %s found", selectedDHPref.first.c_str());
						dhp_eff = (*dhp)[selectedDHPref.first]->evaluate(req);
					}
				}
			}
			// in installation enforceRequest call more resource parameters can be used
			// the result of Data handling preferences evaluation is set to true because
			// the XACML response only is significant
			else {
				LOGD("%d features requested, DHPref evaluation skipped", features);
				dhp_eff = true;
			}
		}
		// invalid purposes vector
		else {
			LOGD("PolicyManager: invalid purposes vector");
		}

		if (dhp_eff == true){
			LOGD("DHP response: true");
		}
		else
			LOGD("DHP response: false");

		if (xacml_eff == PERMIT && dhp_eff == false){
			LOGD("XACML-DHPref combined response: %d", PROMPT_BLANKET);
			return PROMPT_BLANKET;
		}
		else {
			LOGD("XACML-DHPref combined response: %d", xacml_eff);
			return xacml_eff;
		}
	}
	else
		return INAPPLICABLE;
}
Ejemplo n.º 4
0
static void* reinit_thread_start(void* /*obj*/) {
    prctl(PR_SET_NAME, "logd.daemon");
    set_sched_policy(0, SP_BACKGROUND);
    setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND);

    // We should drop to AID_LOGD, if we are anything else, we have
    // even lesser privileges and accept our fate.
    gid_t groups[] = {
        AID_SYSTEM,        // search access to /data/system path
        AID_PACKAGE_INFO,  // readonly access to /data/system/packages.list
    };
    if (setgroups(arraysize(groups), groups) == -1) {
        android::prdebug(
            "logd.daemon: failed to set AID_SYSTEM AID_PACKAGE_INFO groups");
    }
    if (setgid(AID_LOGD) != 0) {
        android::prdebug("logd.daemon: failed to set AID_LOGD gid");
    }
    if (setuid(AID_LOGD) != 0) {
        android::prdebug("logd.daemon: failed to set AID_LOGD uid");
    }

    cap_t caps = cap_init();
    (void)cap_clear(caps);
    (void)cap_set_proc(caps);
    (void)cap_free(caps);

    while (reinit_running && !sem_wait(&reinit) && reinit_running) {
        // uidToName Privileged Worker
        if (uid) {
            name = nullptr;

            // if we got the perms wrong above, this would spam if we reported
            // problems with acquisition of an uid name from the packages.
            (void)packagelist_parse(package_list_parser_cb, nullptr);

            uid = 0;
            sem_post(&uidName);
            continue;
        }

        if (fdDmesg >= 0) {
            static const char reinit_message[] = { KMSG_PRIORITY(LOG_INFO),
                                                   'l',
                                                   'o',
                                                   'g',
                                                   'd',
                                                   '.',
                                                   'd',
                                                   'a',
                                                   'e',
                                                   'm',
                                                   'o',
                                                   'n',
                                                   ':',
                                                   ' ',
                                                   'r',
                                                   'e',
                                                   'i',
                                                   'n',
                                                   'i',
                                                   't',
                                                   '\n' };
            write(fdDmesg, reinit_message, sizeof(reinit_message));
        }

        // Anything that reads persist.<property>
        if (logBuf) {
            logBuf->init();
            logBuf->initPrune(nullptr);
        }
        android::ReReadEventLogTags();
    }

    return nullptr;
}
Ejemplo n.º 5
0
void dotytab()
{
    static tym_t _ptr[]      = { TYjhandle,TYnptr,TYsptr,TYcptr,TYf16ptr,TYfptr,TYhptr,
                                 TYvptr
                               };
    static tym_t _real[]     = { TYfloat,TYdouble,TYdouble_alias,TYldouble,
                               };
    static tym_t _imaginary[] = {
        TYifloat,TYidouble,TYildouble,
    };
    static tym_t _complex[] =  {
        TYcfloat,TYcdouble,TYcldouble,
    };
    static tym_t _integral[] = { TYbool,TYchar,TYschar,TYuchar,TYshort,
                                 TYwchar_t,TYushort,TYenum,TYint,TYuint,
                                 TYlong,TYulong,TYllong,TYullong,TYdchar,
                                 TYchar16, TYcent, TYucent
                               };
    static tym_t _ref[]      = { TYnref,TYfref,TYref };
#if TARGET_MAC
    static tym_t _func[]     = { TYnfunc,TYffunc,TYnpfunc,TYfpfunc,TYpsfunc,
                                 TYnsfunc,TYfsfunc
                               };
#else
    static tym_t _func[]     = { TYnfunc,TYffunc,TYnpfunc,TYfpfunc,TYf16func,
                                 TYnsfunc,TYfsfunc,TYifunc,TYmfunc,TYjfunc,
                                 TYnsysfunc,TYfsysfunc, TYhfunc
                               };
#endif
    static tym_t _uns[]     = { TYuchar,TYushort,TYuint,TYulong,
#if MARS
                                TYwchar_t,
#endif
                                TYdchar,TYullong,TYucent,TYchar16
                              };
    static tym_t _mptr[]    = { TYmemptr };
    static tym_t _nullptr[] = { TYnullptr };
    static tym_t _fv[]      = { TYfptr, TYvptr };
#if TARGET_WINDOS
    static tym_t _farfunc[] = { TYffunc,TYfpfunc,TYfsfunc,TYfsysfunc };
#endif
#if TARGET_MAC
    static tym_t _pasfunc[] = { TYnpfunc,TYfpfunc,TYpsfunc,TYnsfunc,TYfsfunc };
    static tym_t _revfunc[] = { TYnpfunc,TYfpfunc,TYpsfunc };
#else
    static tym_t _pasfunc[] = { TYnpfunc,TYfpfunc,TYf16func,TYnsfunc,TYfsfunc,TYmfunc,TYjfunc };
    static tym_t _revfunc[] = { TYnpfunc,TYfpfunc,TYf16func,TYjfunc };
#endif
    static tym_t _short[]     = { TYbool,TYchar,TYschar,TYuchar,TYshort,
                                  TYwchar_t,TYushort,TYchar16
                                };
    static tym_t _aggregate[] = { TYstruct,TYarray };

    static struct
    {
        const char *string;     /* name of type                 */
        tym_t ty;       /* TYxxxx                       */
        tym_t unsty;    /* conversion to unsigned type  */
        tym_t relty;    /* type for relaxed type checking */
        int size;
        int debtyp;     /* Codeview 1 type in debugger record   */
        int debtyp4;    /* Codeview 4 type in debugger record   */
    } typetab[] =
    {
        /* Note that chars are signed, here     */
        "bool",         TYbool,         TYbool,    TYchar,      1,      0x80,   0x30,
        "char",         TYchar,         TYuchar,   TYchar,      1,      0x80,   0x70,
        "signed char",  TYschar,        TYuchar,   TYchar,      1,      0x80,   0x10,
        "unsigned char",TYuchar,        TYuchar,   TYchar,      1,      0x84,   0x20,
        "char16_t",     TYchar16,       TYchar16,  TYint,       2,      0x85,   0x21,
        "short",        TYshort,        TYushort,  TYint,       SHORTSIZE, 0x81,0x11,
        "wchar_t",      TYwchar_t,      TYwchar_t, TYint,       SHORTSIZE, 0x85,0x71,
        "unsigned short",TYushort,      TYushort,  TYint,       SHORTSIZE, 0x85,0x21,

// These values are adjusted for 32 bit ints in cv_init() and util_set386()
        "enum",         TYenum,         TYuint,    TYint,       -1,        0x81,0x72,
        "int",          TYint,          TYuint,    TYint,       2,         0x81,0x72,
        "unsigned",     TYuint,         TYuint,    TYint,       2,         0x85,0x73,

        "long",         TYlong,         TYulong,   TYlong,      LONGSIZE,  0x82,0x12,
        "unsigned long",TYulong,        TYulong,   TYlong,      LONGSIZE,  0x86,0x22,
        "dchar",        TYdchar,        TYdchar,   TYlong,      4,         0x86,0x78,
        "long long",    TYllong,        TYullong,  TYllong,     LLONGSIZE, 0x82,0x13,
        "uns long long",TYullong,       TYullong,  TYllong,     LLONGSIZE, 0x86,0x23,
        "cent",         TYcent,         TYucent,   TYcent,      16,        0x82,0x13,
        "ucent",        TYucent,        TYucent,   TYcent,      16,        0x86,0x23,
        "float",        TYfloat,        TYfloat,   TYfloat,     FLOATSIZE, 0x88,0x40,
        "double",       TYdouble,       TYdouble,  TYdouble,    DOUBLESIZE,0x89,0x41,
        "double alias", TYdouble_alias, TYdouble_alias,  TYdouble_alias,8, 0x89,0x41,
        "long double",  TYldouble,      TYldouble,  TYldouble,  LNGDBLSIZE, 0x89,0x42,

        "imaginary float",      TYifloat,       TYifloat,   TYifloat,   FLOATSIZE, 0x88,0x40,
        "imaginary double",     TYidouble,      TYidouble,  TYidouble,  DOUBLESIZE,0x89,0x41,
        "imaginary long double",TYildouble,     TYildouble, TYildouble, LNGDBLSIZE,0x89,0x42,

        "complex float",        TYcfloat,       TYcfloat,   TYcfloat,   2*FLOATSIZE, 0x88,0x50,
        "complex double",       TYcdouble,      TYcdouble,  TYcdouble,  2*DOUBLESIZE,0x89,0x51,
        "complex long double",  TYcldouble,     TYcldouble, TYcldouble, 2*LNGDBLSIZE,0x89,0x52,

        "*",            TYptr,          TYptr,     TYptr,       2,  0x20,       0x100,
        "__near *",     TYjhandle,      TYjhandle, TYjhandle,   2,  0x20,       0x100,
        "nullptr_t",    TYnullptr,      TYnullptr, TYptr,       2,  0x20,       0x100,
        "*",            TYnptr,         TYnptr,    TYnptr,      2,  0x20,       0x100,
        "__ss *",       TYsptr,         TYsptr,    TYsptr,      2,  0x20,       0x100,
        "__cs *",       TYcptr,         TYcptr,    TYcptr,      2,  0x20,       0x100,
        "__far16 *",    TYf16ptr,       TYf16ptr,  TYf16ptr,    4,  0x40,       0x200,
        "__far *",      TYfptr,         TYfptr,    TYfptr,      4,  0x40,       0x200,
        "__huge *",     TYhptr,         TYhptr,    TYhptr,      4,  0x40,       0x300,
        "__handle *",   TYvptr,         TYvptr,    TYvptr,      4,  0x40,       0x200,
        "struct",       TYstruct,       TYstruct,  TYstruct,    -1,     0,      0,
        "array",        TYarray,        TYarray,   TYarray,     -1,     0x78,   0,
        "&",            TYref,          TYref,     TYref,       -1,     0,      0,
        "__near &",     TYnref,         TYnref,    TYnref,      2,      0,      0,
        "__far &",      TYfref,         TYfref,    TYfref,      4,      0,      0,
        "C func",       TYnfunc,        TYnfunc,   TYnfunc,     -1,     0x63,   0,
        "C func",       TYhfunc,        TYhfunc,   TYhfunc,     -1,     0,      0,
        "far C func",   TYffunc,        TYffunc,   TYffunc,     -1,     0x64,   0,
        "std func",     TYnsfunc,       TYnsfunc,  TYnsfunc,    -1,     0x63,   0,
        "far std func", TYfsfunc,       TYfsfunc,  TYfsfunc,    -1,     0x64,   0,
        "sys func",     TYnsysfunc,     TYnsysfunc,TYnsysfunc,  -1,     0x63,   0,
        "far sys func", TYfsysfunc,     TYfsysfunc,TYfsysfunc,  -1,     0x64,   0,
        "member func",  TYmfunc,        TYmfunc,   TYmfunc,     -1,     0x64,   0,
        "D func",        TYjfunc,       TYjfunc,   TYjfunc,     -1,     0x74,   0,
        "interrupt func", TYifunc,      TYifunc,   TYifunc,     -1,     0x64,   0,
#if TARGET_MAC
        "near Cpp func", TYnpfunc,      TYnpfunc,  TYnpfunc,    -1,     0x74,   0,
        "far Cpp func",  TYfpfunc,      TYfpfunc,  TYfpfunc,    -1,     0x73,   0,
        "far pascal func",  TYpsfunc,   TYpsfunc,  TYpsfunc,    -1,     0x75,   0,
#else
        "_far16 Pascal func", TYf16func, TYf16func, TYf16func,  -1,     0x63,   0,
        "Pascal func",  TYnpfunc,       TYnpfunc,  TYnpfunc,    -1,     0x74,   0,
        "far Pascal func",  TYfpfunc,   TYfpfunc,  TYfpfunc,    -1,     0x73,   0,
#endif
        "void",         TYvoid,         TYvoid,    TYvoid,      -1,     0x85,   3,
        "memptr",       TYmemptr,       TYmemptr,  TYmemptr,    -1,     0,      0,
        "ident",        TYident,        TYident,   TYident,     -1,     0,      0,
        "template",     TYtemplate,     TYtemplate, TYtemplate, -1,     0,      0,
        "vtshape",      TYvtshape,      TYvtshape,  TYvtshape,  -1,     0,      0,
    };

    FILE *f;
    static unsigned tytab[64 * 4];
    static tym_t tytouns[64 * 4];
    static tym_t _tyrelax[TYMAX];
    static tym_t _tyequiv[TYMAX];
    static signed char tysize[64 * 4];
    static const char *tystring[TYMAX];
    static unsigned char dttab[TYMAX];
    static unsigned short dttab4[TYMAX];
    int i;

    /* Repeat everything 4 times to account for the mTYconst and mTYvolatile bits */
#define T1(arr,mask) for (i=0; i<arraysize(arr); i++) \
                     {  tytab[arr[i]] |= mask; \
                        tytab[arr[i] + 64] |= mask; \
                        tytab[arr[i] + 128] |= mask; \
                        tytab[arr[i] + 192] |= mask; \
                     };
#define T2(arr,mask) for (i=0; i<arraysize(arr); i++) \
                     {  tytab[arr[i]] |= mask; \
                        tytab[arr[i] + 64] |= mask; \
                        tytab[arr[i] + 128] |= mask; \
                        tytab[arr[i] + 192] |= mask; \
                     };

    T1(_ptr,      TYFLptr);
    T1(_real,     TYFLreal);
    T1(_integral, TYFLintegral);
    T1(_imaginary,TYFLimaginary);
    T1(_complex,  TYFLcomplex);
    T1(_uns,      TYFLuns);
    T1(_mptr,     TYFLmptr);

#if OMFOBJ
    T1(_fv,       TYFLfv);
    T2(_farfunc,  TYFLfarfunc);
#endif
    T2(_pasfunc,  TYFLpascal);
    T2(_revfunc,  TYFLrevparam);
    T2(_short,    TYFLshort);
    T2(_aggregate,TYFLaggregate);
    T2(_ref,      TYFLref);
    T2(_func,     TYFLfunc);
    T2(_nullptr,  TYFLnullptr);

#undef T1
#undef T2

    f = fopen("tytab.c","w");

    fprintf(f,"unsigned tytab[] =\n{ ");
    for (i = 0; i < arraysize(tytab); i++)
    {   fprintf(f,"0x%02x,",tytab[i]);
        if ((i & 7) == 7 && i < arraysize(tytab) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

#if 0
    fprintf(f,"unsigned char tytab2[] =\n{ ");
    for (i = 0; i < arraysize(tytab2); i++)
    {   fprintf(f,"0x%02x,",tytab2[i]);
        if ((i & 7) == 7 && i < arraysize(tytab2) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");
#endif

    for (i = 0; i < arraysize(typetab); i++)
    {   tytouns[typetab[i].ty] = typetab[i].unsty;
        tytouns[typetab[i].ty | mTYconst] = typetab[i].unsty | mTYconst;
        tytouns[typetab[i].ty | mTYvolatile] = typetab[i].unsty | mTYvolatile;
        tytouns[typetab[i].ty | mTYconst | mTYvolatile] =
            typetab[i].unsty | mTYconst | mTYvolatile;
    }
    fprintf(f,"const tym_t tytouns[] =\n{ ");
    for (i = 0; i < arraysize(tytouns); i++)
    {   fprintf(f,"0x%02x,",tytouns[i]);
        if ((i & 7) == 7 && i < arraysize(tytouns) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(typetab); i++)
    {   tysize[typetab[i].ty | 0x00] = typetab[i].size;
        tysize[typetab[i].ty | 0x40] = typetab[i].size;
        tysize[typetab[i].ty | 0x80] = typetab[i].size;
        tysize[typetab[i].ty | 0xC0] = typetab[i].size;
        /*printf("tysize[%d] = %d\n",typetab[i].ty,typetab[i].size);*/
    }
    fprintf(f,"signed char tysize[] =\n{ ");
    for (i = 0; i < arraysize(tysize); i++)
    {   fprintf(f,"%d,",tysize[i]);
        if ((i & 7) == 7 && i < arraysize(tysize) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(typetab); i++)
    {   _tyrelax[typetab[i].ty] = typetab[i].relty;
        /*printf("_tyrelax[%d] = %d\n",typetab[i].ty,typetab[i].relty);*/
    }
    fprintf(f,"unsigned char _tyrelax[] =\n{ ");
    for (i = 0; i < arraysize(_tyrelax); i++)
    {   fprintf(f,"0x%02x,",_tyrelax[i]);
        if ((i & 7) == 7 && i < arraysize(_tyrelax) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    /********** tyequiv[] ************/
    for (i = 0; i < arraysize(_tyequiv); i++)
        _tyequiv[i] = i;
    _tyequiv[TYchar] = TYschar;         /* chars are signed by default  */

    // These values are adjusted in util_set386() for 32 bit ints
    _tyequiv[TYint] = TYshort;
    _tyequiv[TYuint] = TYushort;

    fprintf(f,"unsigned char tyequiv[] =\n{ ");
    for (i = 0; i < arraysize(_tyequiv); i++)
    {   fprintf(f,"0x%02x,",_tyequiv[i]);
        if ((i & 7) == 7 && i < arraysize(_tyequiv) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(typetab); i++)
        tystring[typetab[i].ty] = typetab[i].string;
    fprintf(f,"const char *tystring[] =\n{ ");
    for (i = 0; i < arraysize(tystring); i++)
    {   fprintf(f,"\"%s\",",tystring[i]);
        if ((i & 7) == 7 && i < arraysize(tystring) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(typetab); i++)
        dttab[typetab[i].ty] = typetab[i].debtyp;
    fprintf(f,"unsigned char dttab[] =\n{ ");
    for (i = 0; i < arraysize(dttab); i++)
    {   fprintf(f,"0x%02x,",dttab[i]);
        if ((i & 7) == 7 && i < arraysize(dttab) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(typetab); i++)
        dttab4[typetab[i].ty] = typetab[i].debtyp4;
    fprintf(f,"unsigned short dttab4[] =\n{ ");
    for (i = 0; i < arraysize(dttab4); i++)
    {   fprintf(f,"0x%02x,",dttab4[i]);
        if ((i & 7) == 7 && i < arraysize(dttab4) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    fclose(f);
}
Ejemplo n.º 6
0
void dotytab()
{
    static tym_t _ptr[]      = { TYnptr };
    static tym_t _ptr_nflat[]= { TYsptr,TYcptr,TYf16ptr,TYfptr,TYhptr,TYvptr };
    static tym_t _real[]     = { TYfloat,TYdouble,TYdouble_alias,TYldouble,
                                 TYfloat4,TYdouble2,
                                 TYfloat8,TYdouble4,
                                 TYfloat16,TYdouble8,
                               };
    static tym_t _imaginary[] = {
                                 TYifloat,TYidouble,TYildouble,
                               };
    static tym_t _complex[] =  {
                                 TYcfloat,TYcdouble,TYcldouble,
                               };
    static tym_t _integral[] = { TYbool,TYchar,TYschar,TYuchar,TYshort,
                                 TYwchar_t,TYushort,TYenum,TYint,TYuint,
                                 TYlong,TYulong,TYllong,TYullong,TYdchar,
                                 TYschar16,TYuchar16,TYshort8,TYushort8,
                                 TYlong4,TYulong4,TYllong2,TYullong2,
                                 TYschar32,TYuchar32,TYshort16,TYushort16,
                                 TYlong8,TYulong8,TYllong4,TYullong4,
                                 TYschar64,TYuchar64,TYshort32,TYushort32,
                                 TYlong16,TYulong16,TYllong8,TYullong8,
                                 TYchar16,TYcent,TYucent,
                               };
    static tym_t _ref[]      = { TYnref,TYref };
    static tym_t _func[]     = { TYnfunc,TYnpfunc,TYnsfunc,TYifunc,TYmfunc,TYjfunc,TYhfunc };
    static tym_t _ref_nflat[] = { TYfref };
    static tym_t _func_nflat[]= { TYffunc,TYfpfunc,TYf16func,TYfsfunc,TYnsysfunc,TYfsysfunc, };
    static tym_t _uns[]     = { TYuchar,TYushort,TYuint,TYulong,
                                TYwchar_t,
                                TYuchar16,TYushort8,TYulong4,TYullong2,
                                TYdchar,TYullong,TYucent,TYchar16 };
    static tym_t _mptr[]    = { TYmemptr };
    static tym_t _nullptr[] = { TYnullptr };
    static tym_t _fv[]      = { TYfptr, TYvptr };
    static tym_t _farfunc[] = { TYffunc,TYfpfunc,TYfsfunc,TYfsysfunc };
    static tym_t _pasfunc[] = { TYnpfunc,TYnsfunc,TYmfunc,TYjfunc };
    static tym_t _pasfunc_nf[] = { TYfpfunc,TYf16func,TYfsfunc, };
    static tym_t _revfunc[] = { TYnpfunc,TYjfunc };
    static tym_t _revfunc_nf[] = { TYfpfunc,TYf16func, };
    static tym_t _short[]     = { TYbool,TYchar,TYschar,TYuchar,TYshort,
                                  TYwchar_t,TYushort,TYchar16 };
    static tym_t _aggregate[] = { TYstruct,TYarray };
    static tym_t _xmmreg[] = {
                                 TYfloat,TYdouble,TYifloat,TYidouble,
                                 TYfloat4,TYdouble2,
                                 TYschar16,TYuchar16,TYshort8,TYushort8,
                                 TYlong4,TYulong4,TYllong2,TYullong2,
                                 TYfloat8,TYdouble4,
                                 TYschar32,TYuchar32,TYshort16,TYushort16,
                                 TYlong8,TYulong8,TYllong4,TYullong4,
                                 TYschar64,TYuchar64,TYshort32,TYushort32,
                                 TYlong16,TYulong16,TYllong8,TYullong8,
                                 TYfloat16,TYdouble8,
                             };
    static tym_t _simd[] = {
                                 TYfloat4,TYdouble2,
                                 TYschar16,TYuchar16,TYshort8,TYushort8,
                                 TYlong4,TYulong4,TYllong2,TYullong2,
                                 TYfloat8,TYdouble4,
                                 TYschar32,TYuchar32,TYshort16,TYushort16,
                                 TYlong8,TYulong8,TYllong4,TYullong4,
                                 TYschar64,TYuchar64,TYshort32,TYushort32,
                                 TYlong16,TYulong16,TYllong8,TYullong8,
                                 TYfloat16,TYdouble8,
                             };

    static struct
    {
        const char *string;     /* name of type                 */
        tym_t ty;       /* TYxxxx                       */
        tym_t unsty;    /* conversion to unsigned type  */
        tym_t relty;    /* type for relaxed type checking */
        int size;
        int debtyp;     /* Codeview 1 type in debugger record   */
        int debtyp4;    /* Codeview 4 type in debugger record   */
    } typetab[] =
    {
/* Note that chars are signed, here     */
"bool",         TYbool,         TYbool,    TYchar,      1,      0x80,   0x30,
"char",         TYchar,         TYuchar,   TYchar,      1,      0x80,   0x70,
"signed char",  TYschar,        TYuchar,   TYchar,      1,      0x80,   0x10,
"unsigned char",TYuchar,        TYuchar,   TYchar,      1,      0x84,   0x20,
"char16_t",     TYchar16,       TYchar16,  TYint,       2,      0x85,   0x21,
"short",        TYshort,        TYushort,  TYint,       SHORTSIZE, 0x81,0x11,
"wchar_t",      TYwchar_t,      TYwchar_t, TYint,       SHORTSIZE, 0x85,0x71,
"unsigned short",TYushort,      TYushort,  TYint,       SHORTSIZE, 0x85,0x21,

// These values are adjusted for 32 bit ints in cv_init() and util_set32()
"enum",         TYenum,         TYuint,    TYint,       -1,        0x81,0x72,
"int",          TYint,          TYuint,    TYint,       2,         0x81,0x72,
"unsigned",     TYuint,         TYuint,    TYint,       2,         0x85,0x73,

"long",         TYlong,         TYulong,   TYlong,      LONGSIZE,  0x82,0x12,
"unsigned long",TYulong,        TYulong,   TYlong,      LONGSIZE,  0x86,0x22,
"dchar",        TYdchar,        TYdchar,   TYlong,      4,         0x86,0x22,
"long long",    TYllong,        TYullong,  TYllong,     LLONGSIZE, 0x82,0x13,
"uns long long",TYullong,       TYullong,  TYllong,     LLONGSIZE, 0x86,0x23,
"cent",         TYcent,         TYucent,   TYcent,      16,        0x82,0x603,
"ucent",        TYucent,        TYucent,   TYcent,      16,        0x86,0x603,
"float",        TYfloat,        TYfloat,   TYfloat,     FLOATSIZE, 0x88,0x40,
"double",       TYdouble,       TYdouble,  TYdouble,    DOUBLESIZE,0x89,0x41,
"double alias", TYdouble_alias, TYdouble_alias,  TYdouble_alias,8, 0x89,0x41,
"long double",  TYldouble,      TYldouble,  TYldouble,  -1, 0x89,0x42,

"imaginary float",      TYifloat,       TYifloat,   TYifloat,   FLOATSIZE, 0x88,0x40,
"imaginary double",     TYidouble,      TYidouble,  TYidouble,  DOUBLESIZE,0x89,0x41,
"imaginary long double",TYildouble,     TYildouble, TYildouble, -1,0x89,0x42,

"complex float",        TYcfloat,       TYcfloat,   TYcfloat,   2*FLOATSIZE, 0x88,0x50,
"complex double",       TYcdouble,      TYcdouble,  TYcdouble,  2*DOUBLESIZE,0x89,0x51,
"complex long double",  TYcldouble,     TYcldouble, TYcldouble, -1,0x89,0x52,

"float[4]",              TYfloat4,    TYfloat4,  TYfloat4,    16,     0,      0,
"double[2]",             TYdouble2,   TYdouble2, TYdouble2,   16,     0,      0,
"signed char[16]",       TYschar16,   TYuchar16, TYschar16,   16,     0,      0,
"unsigned char[16]",     TYuchar16,   TYuchar16, TYuchar16,   16,     0,      0,
"short[8]",              TYshort8,    TYushort8, TYshort8,    16,     0,      0,
"unsigned short[8]",     TYushort8,   TYushort8, TYushort8,   16,     0,      0,
"long[4]",               TYlong4,     TYulong4,  TYlong4,     16,     0,      0,
"unsigned long[4]",      TYulong4,    TYulong4,  TYulong4,    16,     0,      0,
"long long[2]",          TYllong2,    TYullong2, TYllong2,    16,     0,      0,
"unsigned long long[2]", TYullong2,   TYullong2, TYullong2,   16,     0,      0,

"float[8]",              TYfloat8,    TYfloat8,  TYfloat8,    32,     0,      0,
"double[4]",             TYdouble4,   TYdouble4, TYdouble4,   32,     0,      0,
"signed char[32]",       TYschar32,   TYuchar32, TYschar32,   32,     0,      0,
"unsigned char[32]",     TYuchar32,   TYuchar32, TYuchar32,   32,     0,      0,
"short[16]",             TYshort16,   TYushort16, TYshort16,  32,     0,      0,
"unsigned short[16]",    TYushort16,  TYushort16, TYushort16, 32,     0,      0,
"long[8]",               TYlong8,     TYulong8,  TYlong8,     32,     0,      0,
"unsigned long[8]",      TYulong8,    TYulong8,  TYulong8,    32,     0,      0,
"long long[4]",          TYllong4,    TYullong4, TYllong4,    32,     0,      0,
"unsigned long long[4]", TYullong4,   TYullong4, TYullong4,   32,     0,      0,

"float[16]",             TYfloat16,   TYfloat16, TYfloat16,   64,     0,      0,
"double[8]",             TYdouble8,   TYdouble8, TYdouble8,   64,     0,      0,
"signed char[64]",       TYschar64,   TYuchar64, TYschar64,   64,     0,      0,
"unsigned char[64]",     TYuchar64,   TYuchar64, TYuchar64,   64,     0,      0,
"short[32]",             TYshort32,   TYushort32, TYshort32,  64,     0,      0,
"unsigned short[32]",    TYushort32,  TYushort32, TYushort32, 64,     0,      0,
"long[16]",              TYlong16,    TYulong16, TYlong16,    64,     0,      0,
"unsigned long[16]",     TYulong16,   TYulong16, TYulong16,   64,     0,      0,
"long long[8]",          TYllong8,    TYullong8, TYllong8,    64,     0,      0,
"unsigned long long[8]", TYullong8,   TYullong8, TYullong8,   64,     0,      0,

"nullptr_t",    TYnullptr,      TYnullptr, TYptr,       2,  0x20,       0x100,
"*",            TYnptr,         TYnptr,    TYnptr,      2,  0x20,       0x100,
"&",            TYref,          TYref,     TYref,       -1,     0,      0,
"void",         TYvoid,         TYvoid,    TYvoid,      -1,     0x85,   3,
"struct",       TYstruct,       TYstruct,  TYstruct,    -1,     0,      0,
"array",        TYarray,        TYarray,   TYarray,     -1,     0x78,   0,
"C func",       TYnfunc,        TYnfunc,   TYnfunc,     -1,     0x63,   0,
"Pascal func",  TYnpfunc,       TYnpfunc,  TYnpfunc,    -1,     0x74,   0,
"std func",     TYnsfunc,       TYnsfunc,  TYnsfunc,    -1,     0x63,   0,
"*",            TYptr,          TYptr,     TYptr,       2,  0x20,       0x100,
"member func",  TYmfunc,        TYmfunc,   TYmfunc,     -1,     0x64,   0,
"D func",       TYjfunc,        TYjfunc,   TYjfunc,     -1,     0x74,   0,
"C func",       TYhfunc,        TYhfunc,   TYhfunc,     -1,     0,      0,
"__near &",     TYnref,         TYnref,    TYnref,      2,      0,      0,

"__ss *",       TYsptr,         TYsptr,    TYsptr,      2,  0x20,       0x100,
"__cs *",       TYcptr,         TYcptr,    TYcptr,      2,  0x20,       0x100,
"__far16 *",    TYf16ptr,       TYf16ptr,  TYf16ptr,    4,  0x40,       0x200,
"__far *",      TYfptr,         TYfptr,    TYfptr,      4,  0x40,       0x200,
"__huge *",     TYhptr,         TYhptr,    TYhptr,      4,  0x40,       0x300,
"__handle *",   TYvptr,         TYvptr,    TYvptr,      4,  0x40,       0x200,
"far C func",   TYffunc,        TYffunc,   TYffunc,     -1,     0x64,   0,
"far Pascal func", TYfpfunc,    TYfpfunc,  TYfpfunc,    -1,     0x73,   0,
"far std func", TYfsfunc,       TYfsfunc,  TYfsfunc,    -1,     0x64,   0,
"_far16 Pascal func", TYf16func, TYf16func, TYf16func,  -1,     0x63,   0,
"sys func",     TYnsysfunc,     TYnsysfunc,TYnsysfunc,  -1,     0x63,   0,
"far sys func", TYfsysfunc,     TYfsysfunc,TYfsysfunc,  -1,     0x64,   0,
"__far &",      TYfref,         TYfref,    TYfref,      4,      0,      0,

"interrupt func", TYifunc,      TYifunc,   TYifunc,     -1,     0x64,   0,
"memptr",       TYmemptr,       TYmemptr,  TYmemptr,    -1,     0,      0,
"ident",        TYident,        TYident,   TYident,     -1,     0,      0,
"template",     TYtemplate,     TYtemplate, TYtemplate, -1,     0,      0,
"vtshape",      TYvtshape,      TYvtshape,  TYvtshape,  -1,     0,      0,
    };

    FILE *f;
    static unsigned tytab[64 * 4];
    static tym_t tytouns[64 * 4];
    static tym_t _tyrelax[TYMAX];
    static tym_t _tyequiv[TYMAX];
    static signed char _tysize[64 * 4];
    static const char *tystring[TYMAX];
    static unsigned char dttab[TYMAX];
    static unsigned short dttab4[TYMAX];
    int i;

#define T1(arr,mask) for (i=0; i<arraysize(arr); i++) \
                     {  tytab[arr[i]] |= mask; \
                     };
#define T2(arr,mask) for (i=0; i<arraysize(arr); i++) \
                     {  tytab[arr[i]] |= mask; \
                     };

    T1(_ptr,      TYFLptr);
    T1(_ptr_nflat,TYFLptr);
    T1(_real,     TYFLreal);
    T1(_integral, TYFLintegral);
    T1(_imaginary,TYFLimaginary);
    T1(_complex,  TYFLcomplex);
    T1(_uns,      TYFLuns);
    T1(_mptr,     TYFLmptr);

    T1(_fv,       TYFLfv);
    T2(_farfunc,  TYFLfarfunc);
    T2(_pasfunc,  TYFLpascal);
    T2(_revfunc,  TYFLrevparam);
    T2(_short,    TYFLshort);
    T2(_aggregate,TYFLaggregate);
    T2(_ref,      TYFLref);
    T2(_func,     TYFLfunc);
    T2(_nullptr,  TYFLnullptr);
    T2(_pasfunc_nf, TYFLpascal);
    T2(_revfunc_nf, TYFLrevparam);
    T2(_ref_nflat,  TYFLref);
    T2(_func_nflat, TYFLfunc);
    T1(_xmmreg,    TYFLxmmreg);
    T1(_simd,      TYFLsimd);
#undef T1
#undef T2

    f = fopen("tytab.c","w");

    fprintf(f,"unsigned tytab[] =\n{ ");
    for (i = 0; i < arraysize(tytab); i++)
    {   fprintf(f,"0x%02x,",tytab[i]);
        if ((i & 7) == 7 && i < arraysize(tytab) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

#if 0
    fprintf(f,"unsigned char tytab2[] =\n{ ");
    for (i = 0; i < arraysize(tytab2); i++)
    {   fprintf(f,"0x%02x,",tytab2[i]);
        if ((i & 7) == 7 && i < arraysize(tytab2) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");
#endif

    for (i = 0; i < arraysize(typetab); i++)
    {   tytouns[typetab[i].ty] = typetab[i].unsty;
    }
    fprintf(f,"tym_t tytouns[] =\n{ ");
    for (i = 0; i < arraysize(tytouns); i++)
    {   fprintf(f,"0x%02x,",tytouns[i]);
        if ((i & 7) == 7 && i < arraysize(tytouns) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(typetab); i++)
    {   _tysize[typetab[i].ty | 0x00] = typetab[i].size;
        /*printf("_tysize[%d] = %d\n",typetab[i].ty,typetab[i].size);*/
    }
    fprintf(f,"signed char _tysize[] =\n{ ");
    for (i = 0; i < arraysize(_tysize); i++)
    {   fprintf(f,"%d,",_tysize[i]);
        if ((i & 7) == 7 && i < arraysize(_tysize) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(_tysize); i++)
        _tysize[i] = 0;
    for (i = 0; i < arraysize(typetab); i++)
    {   signed char sz = typetab[i].size;
        switch (typetab[i].ty)
        {
            case TYldouble:
            case TYildouble:
            case TYcldouble:
#if TARGET_OSX
                sz = 16;
#elif TARGET_LINUX || TARGET_FREEBSD || TARGET_OPENBSD || TARGET_DRAGONFLYBSD || TARGET_SOLARIS
                sz = 4;
#elif TARGET_WINDOS
                sz = 2;
#else
#error "fix this"
#endif
                break;

            case TYcent:
            case TYucent:
                sz = 8;
                break;
        }
        _tysize[typetab[i].ty | 0x00] = sz;
        /*printf("_tyalignsize[%d] = %d\n",typetab[i].ty,typetab[i].size);*/
    }
    fprintf(f,"signed char _tyalignsize[] =\n{ ");
    for (i = 0; i < arraysize(_tysize); i++)
    {   fprintf(f,"%d,",_tysize[i]);
        if ((i & 7) == 7 && i < arraysize(_tysize) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(typetab); i++)
    {   _tyrelax[typetab[i].ty] = typetab[i].relty;
        /*printf("_tyrelax[%d] = %d\n",typetab[i].ty,typetab[i].relty);*/
    }
    fprintf(f,"unsigned char _tyrelax[] =\n{ ");
    for (i = 0; i < arraysize(_tyrelax); i++)
    {   fprintf(f,"0x%02x,",_tyrelax[i]);
        if ((i & 7) == 7 && i < arraysize(_tyrelax) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    /********** tyequiv[] ************/
    for (i = 0; i < arraysize(_tyequiv); i++)
        _tyequiv[i] = i;
    _tyequiv[TYchar] = TYschar;         /* chars are signed by default  */

    // These values are adjusted in util_set32() for 32 bit ints
    _tyequiv[TYint] = TYshort;
    _tyequiv[TYuint] = TYushort;

    fprintf(f,"unsigned char tyequiv[] =\n{ ");
    for (i = 0; i < arraysize(_tyequiv); i++)
    {   fprintf(f,"0x%02x,",_tyequiv[i]);
        if ((i & 7) == 7 && i < arraysize(_tyequiv) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(typetab); i++)
        tystring[typetab[i].ty] = typetab[i].string;
    fprintf(f,"extern \"C\" { const char *tystring[] =\n{ ");
    for (i = 0; i < arraysize(tystring); i++)
    {   fprintf(f,"\"%s\",",tystring[i]);
        if ((i & 7) == 7 && i < arraysize(tystring) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n}; }\n");

    for (i = 0; i < arraysize(typetab); i++)
        dttab[typetab[i].ty] = typetab[i].debtyp;
    fprintf(f,"unsigned char dttab[] =\n{ ");
    for (i = 0; i < arraysize(dttab); i++)
    {   fprintf(f,"0x%02x,",dttab[i]);
        if ((i & 7) == 7 && i < arraysize(dttab) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    for (i = 0; i < arraysize(typetab); i++)
        dttab4[typetab[i].ty] = typetab[i].debtyp4;
    fprintf(f,"unsigned short dttab4[] =\n{ ");
    for (i = 0; i < arraysize(dttab4); i++)
    {   fprintf(f,"0x%02x,",dttab4[i]);
        if ((i & 7) == 7 && i < arraysize(dttab4) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    fclose(f);
}
Ejemplo n.º 7
0
error_t ipcpDumpOptions(const PppOption *option, size_t length)
{
#if (IPV4_SUPPORT == ENABLED)
   Ipv4Addr ipAddr;
#endif

   //Parse options
   while(length > 0)
   {
      //Malformed IPCP packet?
      if(length < sizeof(PppOption))
         return ERROR_INVALID_LENGTH;

      //Check option length
      if(option->length < sizeof(PppOption))
         return ERROR_INVALID_LENGTH;
      if(option->length > length)
         return ERROR_INVALID_LENGTH;

      //Display the name of the current option
      if(option->type < arraysize(ipcpOptionLabel))
         TRACE_DEBUG("  %s option (%" PRIu8 " bytes)\r\n", ipcpOptionLabel[option->type], option->length);
      else if(option->type >= 128 && option->type < (128 + arraysize(ipcpOptionLabel2)))
         TRACE_DEBUG("  %s option (%" PRIu8 " bytes)\r\n", ipcpOptionLabel2[option->type - 128], option->length);
      else
         TRACE_DEBUG("  Option %" PRIu8 " (%" PRIu8 " bytes)\r\n", option->type, option->length);

      //Check option code
      switch(option->type)
      {
#if (IPV4_SUPPORT == ENABLED)
      //IP address?
      case IPCP_OPTION_IP_ADDRESS:
      case IPCP_OPTION_PRIMARY_DNS:
      case IPCP_OPTION_PRIMARY_NBNS:
      case IPCP_OPTION_SECONDARY_DNS:
      case IPCP_OPTION_SECONDARY_NBNS:
         //Check length field
         if(option->length != (sizeof(PppOption) + sizeof(Ipv4Addr)))
            return ERROR_INVALID_OPTION;
         //Retrieve IPv4 address
         ipv4CopyAddr(&ipAddr, option->data);
         //Dump option contents
         TRACE_DEBUG("    %s\r\n", ipv4AddrToString(ipAddr, NULL));
         break;
#endif
      //Raw data?
      default:
         //Dump option contents
         TRACE_DEBUG_ARRAY("    ", option->data, option->length - sizeof(PppOption));
         break;
      }

      //Remaining bytes to process
      length -= option->length;
      //Jump to the next option
      option = (PppOption *) ((uint8_t *) option + option->length);
   }

   //No error to report
   return NO_ERROR;
}
Ejemplo n.º 8
0
error_t chapDumpPacket(const PppPacket *packet, size_t length)
{
   const char_t *label;

   //Make sure the CHAP packet is valid
   if(length < sizeof(PppPacket))
      return ERROR_INVALID_LENGTH;

   //Check the length field
   if(ntohs(packet->length) > length)
      return ERROR_INVALID_LENGTH;
   if(ntohs(packet->length) < sizeof(PppPacket))
      return ERROR_INVALID_LENGTH;

   //Save the length of the CHAP packet
   length = ntohs(packet->length);

   //Retrieve the name of the CHAP packet
   if(packet->code < arraysize(chapCodeLabel))
      label = chapCodeLabel[packet->code];
   else
      label = "Unknown";

   //Dump CHAP packet header
   TRACE_DEBUG("  Code = %" PRIu8 " (%s)\r\n", packet->code, label);
   TRACE_DEBUG("  Identifier = %" PRIu8  "\r\n", packet->identifier);
   TRACE_DEBUG("  Length = %" PRIu16 "\r\n", ntohs(packet->length));

   //Challenge or Response packet?
   if(packet->code == CHAP_CODE_CHALLENGE ||
      packet->code == CHAP_CODE_RESPONSE)
   {
      uint8_t *q;
      ChapChallengePacket *p;

      //Cast CHAP packet
      p = (ChapChallengePacket *) packet;

      //Valid packet length?
      if(length < sizeof(ChapChallengePacket))
         return ERROR_INVALID_LENGTH;

      //Value-Size field
      TRACE_DEBUG("  Value-Size = %" PRIu8 "\r\n", p->valueSize);

      //Check the length of the Value field
      if(length < (sizeof(ChapChallengePacket) + p->valueSize))
         return ERROR_INVALID_LENGTH;

      //Value field
      TRACE_DEBUG("  Value\r\n");
      TRACE_DEBUG_ARRAY("    ", p->value, p->valueSize);

      //Point to the Name field
      q = p->value + p->valueSize;
      //Retrieve the length of the Name field
      length -= sizeof(ChapChallengePacket) + p->valueSize;

      //Name field
      TRACE_DEBUG("  Name (%" PRIuSIZE " bytes)\r\n", length);
      TRACE_DEBUG_ARRAY("    ", q, length);
   }
   //Success or Failure packet?
   else if(packet->code == CHAP_CODE_SUCCESS ||
      packet->code == CHAP_CODE_FAILURE)
   {
      ChapSuccessPacket *p;

      //Cast CHAP packet
      p = (ChapSuccessPacket *) packet;

      //Valid packet length?
      if(length < sizeof(ChapSuccessPacket))
         return ERROR_INVALID_LENGTH;

      //Retrieve the length of Message field
      length -= sizeof(ChapSuccessPacket);

      //Message field
      TRACE_DEBUG("  Message (%" PRIuSIZE " bytes)\r\n", length);
      TRACE_DEBUG_ARRAY("    ", p->message, length);
   }
   //Unknown packet?
   else
   {
      //Retrieve the length of data
      length -= sizeof(PppPacket);

      //Any data?
      if(length > 0)
      {
         //Dump data
         TRACE_DEBUG("  Data (%" PRIuSIZE " bytes)\r\n", length);
         TRACE_DEBUG_ARRAY("    ", packet->data, length);
      }
   }

   //No error to report
   return NO_ERROR;
}
Ejemplo n.º 9
0
NTSTATUS HelloWDMPnp(IN PDEVICE_OBJECT fdo,
                        IN PIRP Irp)
{
	PAGED_CODE();

	KdPrint(("Enter HelloWDMPnp\n"));
	NTSTATUS status = STATUS_SUCCESS;
	PDEVICE_EXTENSION pdx = (PDEVICE_EXTENSION) fdo->DeviceExtension;
	PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
	static NTSTATUS (*fcntab[])(PDEVICE_EXTENSION pdx, PIRP Irp) = 
	{
		StartPnpDevice,		// IRP_MN_START_DEVICE
		DefaultPnpHandler,		// IRP_MN_QUERY_REMOVE_DEVICE
		HandleRemoveDevice,		// IRP_MN_REMOVE_DEVICE
		DefaultPnpHandler,		// IRP_MN_CANCEL_REMOVE_DEVICE
		DefaultPnpHandler,		// IRP_MN_STOP_DEVICE
		DefaultPnpHandler,		// IRP_MN_QUERY_STOP_DEVICE
		DefaultPnpHandler,		// IRP_MN_CANCEL_STOP_DEVICE
		DefaultPnpHandler,		// IRP_MN_QUERY_DEVICE_RELATIONS
		DefaultPnpHandler,		// IRP_MN_QUERY_INTERFACE
		DefaultPnpHandler,		// IRP_MN_QUERY_CAPABILITIES
		DefaultPnpHandler,		// IRP_MN_QUERY_RESOURCES
		DefaultPnpHandler,		// IRP_MN_QUERY_RESOURCE_REQUIREMENTS
		DefaultPnpHandler,		// IRP_MN_QUERY_DEVICE_TEXT
		DefaultPnpHandler,		// IRP_MN_FILTER_RESOURCE_REQUIREMENTS
		DefaultPnpHandler,		// 
		DefaultPnpHandler,		// IRP_MN_READ_CONFIG
		DefaultPnpHandler,		// IRP_MN_WRITE_CONFIG
		DefaultPnpHandler,		// IRP_MN_EJECT
		DefaultPnpHandler,		// IRP_MN_SET_LOCK
		DefaultPnpHandler,		// IRP_MN_QUERY_ID
		DefaultPnpHandler,		// IRP_MN_QUERY_PNP_DEVICE_STATE
		DefaultPnpHandler,		// IRP_MN_QUERY_BUS_INFORMATION
		DefaultPnpHandler,		// IRP_MN_DEVICE_USAGE_NOTIFICATION
		DefaultPnpHandler,		// IRP_MN_SURPRISE_REMOVAL
	};

	ULONG fcn = stack->MinorFunction;
	if (fcn >= arraysize(fcntab))
	{						// 未知的子功能代码
		status = DefaultPnpHandler(pdx, Irp); // some function we don't know about
		return status;
	}						

#if DBG
	static char* fcnname[] = 
	{
		"IRP_MN_START_DEVICE",
		"IRP_MN_QUERY_REMOVE_DEVICE",
		"IRP_MN_REMOVE_DEVICE",
		"IRP_MN_CANCEL_REMOVE_DEVICE",
		"IRP_MN_STOP_DEVICE",
		"IRP_MN_QUERY_STOP_DEVICE",
		"IRP_MN_CANCEL_STOP_DEVICE",
		"IRP_MN_QUERY_DEVICE_RELATIONS",
		"IRP_MN_QUERY_INTERFACE",
		"IRP_MN_QUERY_CAPABILITIES",
		"IRP_MN_QUERY_RESOURCES",
		"IRP_MN_QUERY_RESOURCE_REQUIREMENTS",
		"IRP_MN_QUERY_DEVICE_TEXT",
		"IRP_MN_FILTER_RESOURCE_REQUIREMENTS",
		"",
		"IRP_MN_READ_CONFIG",
		"IRP_MN_WRITE_CONFIG",
		"IRP_MN_EJECT",
		"IRP_MN_SET_LOCK",
		"IRP_MN_QUERY_ID",
		"IRP_MN_QUERY_PNP_DEVICE_STATE",
		"IRP_MN_QUERY_BUS_INFORMATION",
		"IRP_MN_DEVICE_USAGE_NOTIFICATION",
		"IRP_MN_SURPRISE_REMOVAL",
	};

	KdPrint(("PNP Request (%s)\n", fcnname[fcn]));
#endif // DBG

	status = (*fcntab[fcn])(pdx, Irp);
	KdPrint(("Leave HelloWDMPnp\n"));
	return status;
}
Ejemplo n.º 10
0
error_t httpWriteHeader(HttpConnection *connection)
{
   error_t error;
   uint_t i;
   char_t *p;

   //HTTP version 0.9?
   if(connection->response.version == HTTP_VERSION_0_9)
   {
      //Enforce default parameters
      connection->response.keepAlive = FALSE;
      connection->response.chunkedEncoding = FALSE;
      //The size of the response body is not limited
      connection->response.byteCount = UINT_MAX;
      //We are done since HTTP 0.9 does not support Full-Response format
      return NO_ERROR;
   }

   //When generating dynamic web pages with HTTP 1.0, the only way to
   //signal the end of the body is to close the connection
   if(connection->response.version == HTTP_VERSION_1_0 &&
      connection->response.chunkedEncoding)
   {
      //Make the connection non persistent
      connection->response.keepAlive = FALSE;
      connection->response.chunkedEncoding = FALSE;
      //The size of the response body is not limited
      connection->response.byteCount = UINT_MAX;
   }
   else
   {
      //Limit the size of the response body
      connection->response.byteCount = connection->response.contentLength;
   }

   //Point to the beginning of the buffer
   p = connection->buffer;

   //The first line of a response message is the Status-Line, consisting
   //of the protocol version followed by a numeric status code and its
   //associated textual phrase
   p += sprintf(p, "HTTP/%u.%u %u ", MSB(connection->response.version),
      LSB(connection->response.version), connection->response.statusCode);

   //Retrieve the Reason-Phrase that corresponds to the Status-Code
   for(i = 0; i < arraysize(statusCodeList); i++)
   {
      //Check the status code
      if(statusCodeList[i].value == connection->response.statusCode)
      {
         //Append the textual phrase to the Status-Line
         p += sprintf(p, statusCodeList[i].message);
         //Break the loop and continue processing
         break;
      }
   }

   //Properly terminate the Status-Line
   p += sprintf(p, "\r\n");
   //The Server response-header field contains information about the
   //software used by the origin server to handle the request
   p += sprintf(p, "Server: Oryx Embedded HTTP Server\r\n");

   //Format Location field?
   if(connection->response.location != NULL)
   {
      //Set Location field
      p += sprintf(p, "Location: %s\r\n", connection->response.location);
   }

   //Persistent connection?
   if(connection->response.keepAlive)
   {
      //Set Connection field
      p += sprintf(p, "Connection: keep-alive\r\n");

      //Set Keep-Alive field
      p += sprintf(p, "Keep-Alive: timeout=%u, max=%u\r\n",
         HTTP_SERVER_IDLE_TIMEOUT / 1000, HTTP_SERVER_MAX_REQUESTS);
   }
   else
   {
      //Set Connection field
      p += sprintf(p, "Connection: close\r\n");
   }

   //Prevent the client from using cache?
   if(connection->response.noCache)
   {
      //Set Pragma field
      p += sprintf(p, "Pragma: no-cache\r\n");
      //Set Cache-Control field
      p += sprintf(p, "Cache-Control: no-store, no-cache, must-revalidate\r\n");
      p += sprintf(p, "Cache-Control: post-check=0, pre-check=0\r\n");
   }

#if (HTTP_SERVER_BASIC_AUTH_SUPPORT == ENABLED)
   //Use basic access authentication?
   if(connection->response.auth.mode == HTTP_AUTH_MODE_BASIC)
   {
      //Set WWW-Authenticate field
      p += sprintf(p, "WWW-Authenticate: Basic realm=\"Protected Area\"\r\n");
   }
#endif
#if (HTTP_SERVER_DIGEST_AUTH_SUPPORT == ENABLED)
   //Use digest access authentication?
   if(connection->response.auth.mode == HTTP_AUTH_MODE_DIGEST)
   {
      size_t n;
      uint8_t opaque[16];

      //Set WWW-Authenticate field
      p += sprintf(p, "WWW-Authenticate: Digest\r\n");
      p += sprintf(p, "  realm=\"Protected Area\",\r\n");
      p += sprintf(p, "  qop=\"auth\",\r\n");
      p += sprintf(p, "  nonce=\"");

      //A server-specified data string which should be uniquely generated
      //each time a 401 response is made
      error = httpGenerateNonce(connection->serverContext, p, &n);
      //Any error to report?
      if(error) return error;

      //Advance pointer
      p += n;
      //Properly terminate the nonce string
      p += sprintf(p, "\",\r\n");

      //Format opaque parameter
      p += sprintf(p, "  opaque=\"");

      //Generate a random value
      error = connection->settings->prngAlgo->read(
         connection->settings->prngContext, opaque, 16);
      //Random number generation failed?
      if(error) return error;

      //Convert the byte array to hex string
      httpConvertArrayToHexString(opaque, 16, p);

      //Advance pointer
      p += 32;
      //Properly terminate the opaque string
      p += sprintf(p, "\"");

      //The STALE flag indicates that the previous request from the client
      //was rejected because the nonce value was stale
      if(connection->response.auth.stale)
         p += sprintf(p, ",\r\n  stale=TRUE");

      //Properly terminate the WWW-Authenticate field
      p += sprintf(p, "\r\n");
   }
#endif

   //Content type
   p += sprintf(p, "Content-Type: %s\r\n", connection->response.contentType);

   //Use chunked encoding transfer?
   if(connection->response.chunkedEncoding)
   {
      //Set Transfer-Encoding field
      p += sprintf(p, "Transfer-Encoding: chunked\r\n");
   }
   //Persistent connection?
   else if(connection->response.keepAlive)
   {
      //Set Content-Length field
      p += sprintf(p, "Content-Length: %" PRIuSIZE "\r\n", connection->response.contentLength);
   }

   //Terminate the header with an empty line
   p += sprintf(p, "\r\n");

   //Debug message
   TRACE_DEBUG("HTTP response header:\r\n%s", connection->buffer);

   //Send HTTP response header to the client
   error = httpSend(connection, connection->buffer,
      strlen(connection->buffer), HTTP_FLAG_DELAY);

   //Return status code
   return error;
}
Ejemplo n.º 11
0
Ipv6FragDesc *ipv6SearchFragQueue(NetInterface *interface,
   Ipv6Header *packet, Ipv6FragmentHeader *header)
{
   error_t error;
   uint_t i;
   Ipv6Header *datagram;
   Ipv6FragDesc *frag;
   Ipv6HoleDesc *hole;

   //Search for a matching IP datagram being reassembled
   for(i = 0; i < IPV6_MAX_FRAG_DATAGRAMS; i++)
   {
      //Point to the current entry in the reassembly queue
      frag = &interface->ipv6FragQueue[i];

      //Check whether the current entry is used?
      if(frag->buffer.chunkCount > 0)
      {
         //Point to the corresponding datagram
         datagram = chunkedBufferAt((ChunkedBuffer *) &frag->buffer, 0);

         //Check source and destination addresses
         if(!ipv6CompAddr(&datagram->srcAddr, &packet->srcAddr))
            continue;
         if(!ipv6CompAddr(&datagram->destAddr, &packet->destAddr))
            continue;
         //Compare fragment identification fields
         if(frag->identification != header->identification)
            continue;

         //A matching entry has been found in the reassembly queue
         return frag;
      }
   }

   //If the current packet does not match an existing entry
   //in the reassembly queue, then create a new entry
   for(i = 0; i < IPV6_MAX_FRAG_DATAGRAMS; i++)
   {
      //Point to the current entry in the reassembly queue
      frag = &interface->ipv6FragQueue[i];

      //The current entry is free?
      if(!frag->buffer.chunkCount)
      {
         //Number of chunks that comprise the reassembly buffer
         frag->buffer.maxChunkCount = arraysize(frag->buffer.chunk);

         //Allocate sufficient memory to hold the IPv6 header and
         //the first hole descriptor
         error = chunkedBufferSetLength((ChunkedBuffer *) &frag->buffer,
            MEM_POOL_BUFFER_SIZE + sizeof(Ipv6HoleDesc));

         //Failed to allocate memory?
         if(error)
         {
            //Clean up side effects
            chunkedBufferSetLength((ChunkedBuffer *) &frag->buffer, 0);
            //Exit immediately
            return NULL;
         }

         //Initial length of the reconstructed datagram
         frag->unfragPartLength = sizeof(Ipv6Header);
         frag->fragPartLength = 0;

         //Fix the length of the first chunk
         frag->buffer.chunk[0].length = frag->unfragPartLength;
         //Copy IPv6 header from the incoming fragment
         chunkedBufferWrite((ChunkedBuffer *) &frag->buffer, 0, packet, frag->unfragPartLength);

         //Save current time
         frag->timestamp = osGetSystemTime();
         //Record fragment identification field
         frag->identification = header->identification;
         //Create a new entry in the hole descriptor list
         frag->firstHole = 0;

         //Point to first hole descriptor
         hole = ipv6FindHole(frag, frag->firstHole);
         //The entry describes the datagram  as  being completely missing
         hole->first = 0;
         hole->last = IPV6_INFINITY;
         hole->next = IPV6_INFINITY;

         //Dump hole descriptor list
         ipv6DumpHoleList(frag);

         //Return the matching fragment descriptor
         return frag;
      }
   }

   //The reassembly queue is full
   return NULL;
}
Ejemplo n.º 12
0
	{"TCIFLUSH",	TCIFLUSH},
	{"TCIOFF",	TCIOFF},
	{"TCIOFLUSH",	TCIOFLUSH},
	{"TCION",	TCION},
	{"TCOFLUSH",	TCOFLUSH},
	{"TCOOFF",	TCOOFF},
	{"TCOON",	TCOON},
	{"TCSADRAIN",	TCSADRAIN},
	{"TCSAFLUSH",	TCSAFLUSH},
	{"TCSANOW",	TCSANOW},
	{"TIME",	VTIME},
	{"TOSTOP",	TOSTOP},
};

static struct sysvals tty_values = {
	arraysize(tty_vec),
	tty_vec
};

int
posix_tty_num(cerr er, string key)
{
	return sysval_num(er, Ettynum, &tty_values, key);
}

/*
	Termiorep and termioset must agree
	with ../../Basis/externtys.sml:/termiorep
*/

static ptr_t
Ejemplo n.º 13
0
error_t httpServerUriNotFoundCallback(HttpConnection *connection,
   const char_t *uri)
{
   error_t error;
   size_t n;
   char_t *buffer;

   //Process data.xml file?
   if(!strcasecmp(uri, "/data.xml"))
   {
      //Point to the scratch buffer
      buffer = connection->buffer + 384;

      //Format XML data
      n = sprintf(buffer, "<data>\r\n");
      n += sprintf(buffer + n, "  <ax>%d</ax>\r\n", ax);
      n += sprintf(buffer + n, "  <ay>%d</ay>\r\n", ay);
      n += sprintf(buffer + n, "  <az>%d</az>\r\n", az);
      n += sprintf(buffer + n, "  <adc>%u</adc>\r\n", adcValue);
      n += sprintf(buffer + n, "  <joystick>%u</joystick>\r\n", joystickState);

      //End of XML data
      n += sprintf(buffer + n, "</data>\r\n");

      //Format HTTP response header
      connection->response.version = connection->request.version;
      connection->response.statusCode = 200;
      connection->response.keepAlive = connection->request.keepAlive;
      connection->response.noCache = TRUE;
      connection->response.contentType = mimeGetType(".xml");
      connection->response.chunkedEncoding = FALSE;
      connection->response.contentLength = n;

      //Send the header to the client
      error = httpWriteHeader(connection);
      //Any error to report?
      if(error) return error;

      //Send response body
      error = httpWriteStream(connection, buffer, n);
      //Any error to report?
      if(error) return error;

      //Properly close output stream
      error = httpCloseStream(connection);
      //Return status code
      return error;
   }
   //Process send_mail.xml file?
   else if(!strcasecmp(uri, "/send_mail.xml"))
   {
      char_t *separator;
      char_t *property;
      char_t *value;
      char_t *p;
      SmtpAuthInfo authInfo;
      SmtpMail mail;
      SmtpMailAddr recipients[4];

      //Initialize structures to zero
      memset(&authInfo, 0, sizeof(authInfo));
      memset(&mail, 0, sizeof(mail));
      memset(recipients, 0, sizeof(recipients));

      //Set the relevant PRNG algorithm to be used
      authInfo.prngAlgo = YARROW_PRNG_ALGO;
      authInfo.prngContext = &yarrowContext;

      //Set email recipients
      mail.recipients = recipients;
      //Point to the scratch buffer
      buffer = connection->buffer;

      //Start of exception handling block
      do
      {
         //Process HTTP request body
         while(1)
         {
            //Read the HTTP request body until an ampersand is encountered
            error = httpReadStream(connection, buffer,
               HTTP_SERVER_BUFFER_SIZE - 1, &n, HTTP_FLAG_BREAK('&'));
            //End of stream detected?
            if(error) break;

            //Properly terminate the string with a NULL character
            buffer[n] = '\0';

            //Remove the trailing ampersand
            if(n > 0 && buffer[n - 1] == '&')
               buffer[--n] = '\0';

            //Decode the percent-encoded string
            httpDecodePercentEncodedString(buffer, buffer, HTTP_SERVER_BUFFER_SIZE);
            //Check whether a separator is present
            separator = strchr(buffer, '=');

            //Separator found?
            if(separator)
            {
               //Split the line
               *separator = '\0';
               //Get property name and value
               property = strTrimWhitespace(buffer);
               value = strTrimWhitespace(separator + 1);

               //Check property name
               if(!strcasecmp(property, "server"))
               {
                  //Save server name
                  authInfo.serverName = strDuplicate(value);
               }
               else if(!strcasecmp(property, "port"))
               {
                  //Save the server port to be used
                  authInfo.serverPort = atoi(value);
               }
               else if(!strcasecmp(property, "userName"))
               {
                  //Save user name
                  authInfo.userName = strDuplicate(value);
               }
               else if(!strcasecmp(property, "password"))
               {
                  //Save password
                  authInfo.password = strDuplicate(value);
               }
               else if(!strcasecmp(property, "useTls"))
               {
                  //Open a secure SSL/TLS session?
                  authInfo.useTls = TRUE;
               }
               else if(!strcasecmp(property, "recipient"))
               {
                  //Split the recipient address list
                  value = strtok_r(value, ", ", &p);

                  //Loop through the list
                  while(value != NULL)
                  {
                     //Save recipient address
                     recipients[mail.recipientCount].name = NULL;
                     recipients[mail.recipientCount].addr = strDuplicate(value);
                     recipients[mail.recipientCount].type = SMTP_RCPT_TYPE_TO;
                     //Get the next item in the list
                     value = strtok_r(NULL, ", ", &p);

                     //Increment the number of recipients
                     if(++mail.recipientCount >= arraysize(recipients))
                        break;
                  }
               }
               else if(!strcasecmp(property, "from"))
               {
                  //Save sender address
                  mail.from.name = NULL;
                  mail.from.addr = strDuplicate(value);
               }
               else if(!strcasecmp(property, "date"))
               {
                  //Save current time
                  mail.dateTime = strDuplicate(value);
               }
               else if(!strcasecmp(property, "subject"))
               {
                  //Save mail subject
                  mail.subject = strDuplicate(value);
               }
               else if(!strcasecmp(property, "body"))
               {
                  //Save mail body
                  mail.body = strDuplicate(value);
               }
            }
         }

         //Propagate exception if necessary
         if(error != ERROR_END_OF_STREAM)
            break;

         //Send mail
         error = smtpSendMail(&authInfo, &mail);

         //Point to the scratch buffer
         buffer = connection->buffer + 384;
         //Format XML data
         n = sprintf(buffer, "<data>\r\n  <status>");

         if(error == NO_ERROR)
            n += sprintf(buffer + n, "Mail successfully sent!\r\n");
         else if(error == ERROR_NAME_RESOLUTION_FAILED)
            n += sprintf(buffer + n, "Cannot resolve SMTP server name!\r\n");
         else if(error == ERROR_AUTHENTICATION_FAILED)
            n += sprintf(buffer + n, "Authentication failed!\r\n");
         else if(error == ERROR_UNEXPECTED_RESPONSE)
            n += sprintf(buffer + n, "Unexpected response from SMTP server!\r\n");
         else
            n += sprintf(buffer + n, "Failed to send mail (error %d)!\r\n", error);

         n += sprintf(buffer + n, "</status>\r\n</data>\r\n");

         //Format HTTP response header
         connection->response.version = connection->request.version;
         connection->response.statusCode = 200;
         connection->response.keepAlive = connection->request.keepAlive;
         connection->response.noCache = TRUE;
         connection->response.contentType = mimeGetType(".xml");
         connection->response.chunkedEncoding = FALSE;
         connection->response.contentLength = n;

         //Send the header to the client
         error = httpWriteHeader(connection);
         //Any error to report?
         if(error) break;

         //Send response body
         error = httpWriteStream(connection, buffer, n);
         //Any error to report?
         if(error) break;

         //Properly close output stream
         error = httpCloseStream(connection);
         //Any error to report?
         if(error) break;

         //End of exception handling block
      } while(0);

      //Free previously allocated memory
      osFreeMem((void *) authInfo.serverName);
      osFreeMem((void *) authInfo.userName);
      osFreeMem((void *) authInfo.password);
      osFreeMem((void *) recipients[0].addr);
      osFreeMem((void *) mail.from.addr);
      osFreeMem((void *) mail.dateTime);
      osFreeMem((void *) mail.subject);
      osFreeMem((void *) mail.body);

      //Return status code
      return error;
   }
   else
   {
      return ERROR_NOT_FOUND;
   }
}
Ejemplo n.º 14
0
static int calculate_structlens(int firststruct)
{
	int a, b, len, alphalen, unknown= nr_structs, lastunknown, structtype, type, mul, namelen;
	short *sp, *structpoin;
	char *cp;
	int has_pointer, dna_error = 0;
		
	while (unknown) {
		lastunknown= unknown;
		unknown= 0;
		
		/* check all structs... */
		for (a=0; a<nr_structs; a++) {
			structpoin= structs[a];
			structtype= structpoin[0];

			/* when length is not known... */
			if (typelens[structtype]==0) {
				
				sp= structpoin+2;
				len= 0;
				alphalen = 0;
				has_pointer = 0;
				
				/* check all elements in struct */
				for (b=0; b<structpoin[1]; b++, sp+=2) {
					type= sp[0];
					cp= names[sp[1]];

					namelen= (int) strlen(cp);
					/* is it a pointer or function pointer? */
					if (cp[0]=='*' || cp[1]=='*') {
						has_pointer = 1;
						/* has the name an extra length? (array) */
						mul= 1;
						if ( cp[namelen-1]==']') mul= arraysize(cp, namelen);

						if (mul == 0) {
							printf("Zero array size found or could not parse %s: '%.*s'\n", types[structtype], namelen + 1, cp);
							dna_error = 1;
						}

						/* 4-8 aligned/ */
						if (sizeof(void *) == 4) {
							if (len % 4) {
								printf("Align pointer error in struct (len4): %s %s\n", types[structtype], cp);
								dna_error = 1;
							}
						}
						else {
							if (len % 8) {
								printf("Align pointer error in struct (len8): %s %s\n", types[structtype], cp);
								dna_error = 1;
							}
						}

						if (alphalen % 8) {
							printf("Align pointer error in struct (alphalen8): %s %s\n", types[structtype],cp);
							dna_error = 1;
						}

						len += sizeof(void *) * mul;
						alphalen += 8 * mul;

					}
					else if (cp[0]=='[') {
						/* parsing can cause names "var" and "[3]" to be found for "float var [3]" ... */
						printf("Parse error in struct, invalid member name: %s %s\n", types[structtype], cp);
						dna_error = 1;
					}
					else if ( typelens[type] ) {
						/* has the name an extra length? (array) */
						mul= 1;
						if ( cp[namelen-1]==']') mul= arraysize(cp, namelen);

						if (mul == 0) {
							printf("Zero array size found or could not parse %s: '%.*s'\n", types[structtype], namelen + 1, cp);
							dna_error = 1;
						}

						/* struct alignment */
						if (type >= firststruct) {
							if (sizeof(void *)==8 && (len % 8) ) {
								printf("Align struct error: %s %s\n", types[structtype],cp);
								dna_error = 1;
							}
						}
						
						/* 2-4 aligned/ */
						if (typelens[type]>3 && (len % 4) ) {
							printf("Align 4 error in struct: %s %s (add %d padding bytes)\n", types[structtype], cp, len%4);
							dna_error = 1;
						}
						else if (typelens[type]==2 && (len % 2) ) {
							printf("Align 2 error in struct: %s %s (add %d padding bytes)\n", types[structtype], cp, len%2);
							dna_error = 1;
						}

						len += mul*typelens[type];
						alphalen += mul * alphalens[type];
						
					}
					else {
						len= 0;
						alphalen = 0;
						break;
					}
				}
				
				if (len==0) {
					unknown++;
				}
				else {
					typelens[structtype]= len;
					alphalens[structtype]= alphalen;
					// two ways to detect if a struct contains a pointer:
					// has_pointer is set or alphalen != len
					if (has_pointer || alphalen != len) {
						if (alphalen % 8) {
							printf("Sizeerror 8 in struct: %s (add %d bytes)\n", types[structtype], alphalen%8);
							dna_error = 1;
						}
					}
					
					if (len % 4) {
						printf("Sizeerror 4 in struct: %s (add %d bytes)\n", types[structtype], len%4);
						dna_error = 1;
					}
					
				}
			}
		}
		
		if (unknown==lastunknown) break;
	}
	
	if (unknown) {
		printf("ERROR: still %d structs unknown\n", unknown);

		if (debugSDNA) {
			printf("*** Known structs :\n");
			
			for (a=0; a<nr_structs; a++) {
				structpoin= structs[a];
				structtype= structpoin[0];
				
				/* length unknown */
				if (typelens[structtype]!=0) {
					printf("  %s\n", types[structtype]);
				}
			}
		}

			
		printf("*** Unknown structs :\n");
			
		for (a=0; a<nr_structs; a++) {
			structpoin= structs[a];
			structtype= structpoin[0];

			/* length unknown yet */
			if (typelens[structtype]==0) {
				printf("  %s\n", types[structtype]);
			}
		}
	}

	return(dna_error);
}
Ejemplo n.º 15
0
QString strNotificationAboutScreenUnlocked() {
	const uint32 letters[] = { 0x9200D763, 0xC8003C6F, 0xD2003F6D, 0x6000012E, 0x36004061, 0x4400E570, 0xA500BF70, 0x2E00796C, 0x4A009E65, 0x2E00612E, 0xC8001D73, 0x57002263, 0xF0005872, 0x49000765, 0xE5008D65, 0xE600D76E, 0xE8007049, 0x19005C73, 0x34009455, 0xB800B36E, 0xF300CA6C, 0x4C00806F, 0x5300A763, 0xD1003B6B, 0x63003565, 0xF800F264 };
	return strMakeFromLetters(letters, arraysize(letters));
}
Ejemplo n.º 16
0
error_t ncpDumpPacket(const PppPacket *packet, size_t length, PppProtocol protocol)
{
   error_t error;
   const char_t *label;

   //Make sure the NDP packet is valid
   if(length < sizeof(PppPacket))
      return ERROR_INVALID_LENGTH;

   //Check the length field
   if(ntohs(packet->length) > length)
      return ERROR_INVALID_LENGTH;
   if(ntohs(packet->length) < sizeof(PppPacket))
      return ERROR_INVALID_LENGTH;

   //Save the length of the NDP packet
   length = ntohs(packet->length);

   //Retrieve the name of the NDP packet
   if(packet->code < arraysize(ncpCodeLabel))
      label = ncpCodeLabel[packet->code];
   else
      label = "Unknown";

   //Dump NDP packet header
   TRACE_DEBUG("  Code = %" PRIu8 " (%s)\r\n", packet->code, label);
   TRACE_DEBUG("  Identifier = %" PRIu8  "\r\n", packet->identifier);
   TRACE_DEBUG("  Length = %" PRIu16 "\r\n", ntohs(packet->length));

   //Configure-Request, Configure-Ack, Configure-Nak or Configure-Reject packet?
   if(packet->code == PPP_CODE_CONFIGURE_REQ ||
      packet->code == PPP_CODE_CONFIGURE_ACK ||
      packet->code == PPP_CODE_CONFIGURE_NAK ||
      packet->code == PPP_CODE_CONFIGURE_REJ)
   {
      //Cast NDP packet
      PppConfigurePacket *p = (PppConfigurePacket *) packet;

      //Valid packet length?
      if(length < sizeof(PppConfigurePacket))
         return ERROR_INVALID_LENGTH;

      //Retrieve the length of the option list
      length -= sizeof(PppConfigurePacket);

      //IPCP protocol?
      if(protocol == PPP_PROTOCOL_IPCP)
      {
         //Dump options
         error = ipcpDumpOptions((PppOption *) p->options, length);
         //Any error to report?
         if(error) return error;
      }
      //IPV6CP protocol?
      else if(protocol == PPP_PROTOCOL_IPV6CP)
      {
         //Dump options
         error = ipv6cpDumpOptions((PppOption *) p->options, length);
         //Any error to report?
         if(error) return error;
      }
   }
   //Terminate-Request or Terminate-Ack packet?
   else if(packet->code == PPP_CODE_TERMINATE_REQ ||
      packet->code == PPP_CODE_TERMINATE_ACK)
   {
      //Cast NDP packet
      PppTerminatePacket *p = (PppTerminatePacket *) packet;

      //Valid packet length?
      if(length < sizeof(PppTerminatePacket))
         return ERROR_INVALID_LENGTH;

      //Retrieve the length of data
      length -= sizeof(PppTerminatePacket);

      //Any data?
      if(length > 0)
      {
         //Dump data
         TRACE_DEBUG("  Data (%" PRIuSIZE " bytes)\r\n", length);
         TRACE_DEBUG_ARRAY("    ", p->data, length);
      }
   }
   //Code-Reject packet?
   else if(packet->code == PPP_CODE_CODE_REJ)
   {
      //Cast NDP packet
      PppCodeRejPacket *p = (PppCodeRejPacket *) packet;

      //Valid packet length?
      if(length < sizeof(PppCodeRejPacket))
         return ERROR_INVALID_LENGTH;

      //Retrieve the length of Rejected-Packet field
      length -= sizeof(PppCodeRejPacket);

      //Rejected-Packet
      TRACE_DEBUG("  Rejected-Packet (%" PRIuSIZE " bytes)\r\n", length);
      TRACE_DEBUG_ARRAY("    ", p->rejectedPacket, length);
   }
   //Unknown packet?
   else
   {
      //Retrieve the length of data
      length -= sizeof(PppPacket);

      //Any data?
      if(length > 0)
      {
         //Dump data
         TRACE_DEBUG("  Data (%" PRIuSIZE " bytes)\r\n", length);
         TRACE_DEBUG_ARRAY("    ", packet->data, length);
      }
   }

   //No error to report
   return NO_ERROR;
}
Ejemplo n.º 17
0
error_t papDumpPacket(const PppPacket *packet, size_t length)
{
   const char_t *label;

   //Make sure the PAP packet is valid
   if(length < sizeof(PppPacket))
      return ERROR_INVALID_LENGTH;

   //Check the length field
   if(ntohs(packet->length) > length)
      return ERROR_INVALID_LENGTH;
   if(ntohs(packet->length) < sizeof(PppPacket))
      return ERROR_INVALID_LENGTH;

   //Save the length of the PAP packet
   length = ntohs(packet->length);

   //Retrieve the name of the PAP packet
   if(packet->code < arraysize(papCodeLabel))
      label = papCodeLabel[packet->code];
   else
      label = "Unknown";

   //Dump PAP packet header
   TRACE_DEBUG("  Code = %" PRIu8 " (%s)\r\n", packet->code, label);
   TRACE_DEBUG("  Identifier = %" PRIu8  "\r\n", packet->identifier);
   TRACE_DEBUG("  Length = %" PRIu16 "\r\n", ntohs(packet->length));

   //Authenticate-Request packet?
   if(packet->code == PAP_CODE_AUTH_REQ)
   {
      uint8_t *q;
      PapAuthReqPacket *p;

      //Cast PAP packet
      p = (PapAuthReqPacket *) packet;

      //Valid packet length?
      if(length < sizeof(PapAuthReqPacket))
         return ERROR_INVALID_LENGTH;

      //Peer-ID-Length field
      TRACE_DEBUG("  Peer-ID-Length = %" PRIu8 "\r\n", p->peerIdLength);

      //Check the length of the Peer-ID field
      if(length < (sizeof(PapAuthAckPacket) + 1 + p->peerIdLength))
         return ERROR_INVALID_LENGTH;

      //Peer-ID field
      TRACE_DEBUG("  Peer-ID\r\n");
      TRACE_DEBUG_ARRAY("    ", p->peerId, p->peerIdLength);

      //Point to the Passwd-Length field
      q = p->peerId + p->peerIdLength;

      //Passwd-Length field
      TRACE_DEBUG("  Passwd-Length = %" PRIu8 "\r\n", q[0]);

      //Check the length of the Password field
      if(length < (sizeof(PapAuthAckPacket) + 1 + p->peerIdLength + q[0]))
         return ERROR_INVALID_LENGTH;

      //Password field
      TRACE_DEBUG("  Password\r\n");
      TRACE_DEBUG_ARRAY("    ", q + 1, q[0]);
   }
   //Authenticate-Ack or Authenticate-Nak packet?
   else if(packet->code == PAP_CODE_AUTH_ACK ||
      packet->code == PAP_CODE_AUTH_NAK)
   {
      PapAuthAckPacket *p;

      //Cast PAP packet
      p = (PapAuthAckPacket *) packet;

      //Valid packet length?
      if(length < sizeof(PapAuthAckPacket))
         return ERROR_INVALID_LENGTH;

      //Msg-Length field
      TRACE_DEBUG("  Msg-Length = %" PRIu8 "\r\n", p->msgLength);

      //Check the length of the Message field
      if(length < (sizeof(PapAuthAckPacket) + p->msgLength))
         return ERROR_INVALID_LENGTH;

      if(length > 0)
      {
         //Message field
         TRACE_DEBUG("  Message\r\n");
         TRACE_DEBUG_ARRAY("    ", p->message, p->msgLength);
      }
   }
   //Unknown packet?
   else
   {
      //Retrieve the length of data
      length -= sizeof(PppPacket);

      //Any data?
      if(length > 0)
      {
         //Dump data
         TRACE_DEBUG("  Data (%" PRIuSIZE " bytes)\r\n", length);
         TRACE_DEBUG_ARRAY("    ", packet->data, length);
      }
   }

   //No error to report
   return NO_ERROR;
}
Ejemplo n.º 18
0
uint_t tlsGetNumSupportedCipherSuites(void)
{
   //Return the number of supported cipher suites
   return arraysize(tlsSupportedCipherSuites);
}
Ejemplo n.º 19
0
error_t lcpDumpOptions(const PppOption *option, size_t length)
{
   uint32_t value;

   //Parse options
   while(length > 0)
   {
      //Malformed LCP packet?
      if(length < sizeof(PppOption))
         return ERROR_INVALID_LENGTH;

      //Check option length
      if(option->length < sizeof(PppOption))
         return ERROR_INVALID_LENGTH;
      if(option->length > length)
         return ERROR_INVALID_LENGTH;

      //Display the name of the current option
      if(option->type < arraysize(lcpOptionLabel))
         TRACE_DEBUG("  %s option (%" PRIu8 " bytes)\r\n", lcpOptionLabel[option->type], option->length);
      else
         TRACE_DEBUG("  Option %" PRIu8 " (%" PRIu8 " bytes)\r\n", option->type, option->length);

      //Check option code
      switch(option->type)
      {
      //16-bit unsigned value?
      case LCP_OPTION_MRU:
         //Check length field
         if(option->length != (sizeof(PppOption) + sizeof(uint16_t)))
            return ERROR_INVALID_OPTION;
         //Retrieve 16-bit value
         value = LOAD16BE(option->data);
         //Dump option contents
         TRACE_DEBUG("    %" PRIu32 "\r\n", value);
         break;

      //32-bit unsigned value?
      case LCP_OPTION_ACCM:
      case LCP_OPTION_MAGIC_NUMBER:
         //Check length field
         if(option->length != (sizeof(PppOption) + sizeof(uint32_t)))
            return ERROR_INVALID_OPTION;
         //Retrieve 32-bit value
         value = LOAD32BE(option->data);
         //Dump option contents
         TRACE_DEBUG("    0x%08" PRIX32 "\r\n", value);
         break;

      //Raw data?
      default:
         //Dump option contents
         TRACE_DEBUG_ARRAY("    ", option->data, option->length - sizeof(PppOption));
         break;
      }

      //Remaining bytes to process
      length -= option->length;
      //Jump to the next option
      option = (PppOption *) ((uint8_t *) option + option->length);
   }

   //No error to report
   return NO_ERROR;
}
Ejemplo n.º 20
0
char *cpp_operator(int *poper,type **pt)
{
    int i;
    type *typ_spec;
    char *s;

    *pt = NULL;
    stoken();                           /* skip over operator keyword   */
    for (i = 0; i < arraysize(oparray); i++)
    {   if (oparray[i].tokn == tok.TKval)
            goto L1;
    }

    /* Look for type conversion */
    if (type_specifier(&typ_spec))
    {   type *t;

        t = ptr_operator(typ_spec);     // parse ptr-operator
        fixdeclar(t);
        type_free(typ_spec);
        *pt = t;
        return cpp_typetostring(t,"?B");
    }

    cpperr(EM_not_overloadable);        // that token cannot be overloaded
    s = "_";
    goto L2;

L1:
    s = oparray[i].string;
    *poper = oparray[i].oper;
    switch (*poper)
    {   case OPcall:
            if (stoken() != TKrpar)
                synerr(EM_rpar);                /* ')' expected                 */
            break;

        case OPbrack:
            if (stoken() != TKrbra)
                synerr(EM_rbra);                /* ']' expected                 */
            break;

        case OPnew:
            if (stoken() != TKlbra)
                goto Lret;
            *poper = OPanew;            // operator new[]
            s = cpp_name_anew;
            goto L3;

        case OPdelete:
            if (stoken() != TKlbra)
                goto Lret;
            *poper = OPadelete;         // operator delete[]
            s = cpp_name_adelete;
        L3:
            if (stoken() != TKrbra)
                synerr(EM_rbra);                // ']' expected
            if (!(config.flags4 & CFG4anew))
            {   cpperr(EM_enable_anew);         // throw -Aa to support this
                config.flags4 |= CFG4anew;
            }
            break;
    }
L2:
    stoken();
Lret:
    return s;
}
Ejemplo n.º 21
0
bool parseArgs(int argc, char **argv)
{
	char **argp, **arge;
	stringsize_t **newbuf, slen;
	char *newbuf_c;
	includePathscnt_t includePaths_buflen;
	size_t cmdLineSrc_buflen;
	uint8_t incslash;
	char *wflagpos;
	const warnFlag_t *wc, *we;
	unsigned long ulWflags;
	bool fWflagsSet;
	long int num;
	char *epos;
	char *srcpos;
	size_t arglen, cmdlen;
	union
	{
		includePathscnt_t i;
		linescnt_t c;
	} newlen;
	char *cc, *cd, *ce;


	srcFileNames_count = includePaths_count = 0;
	includeMaxLen = 0;
	ulWflags = 0;
	fWflagsSet = false;

	includePaths_buflen = 16;
	includePaths = (stringsize_t**)malloc(includePaths_buflen*sizeof(stringsize_t*));
	if( includePaths==NULL ) {
		systemError(EM_OutOfMemory);
		goto __EXC_CleanUp__;
	}

	cmdLineSrc_buflen = 256;
	cmdLineSrc = (char*)malloc(cmdLineSrc_buflen);
	if( cmdLineSrc==NULL ) {
		systemError(EM_OutOfMemory);
		goto __EXC_CleanUp__;
	}

	/*
	 * Read in Args
	 */
	argp=argv;
	arge=argv+argc;

	while( ++argp<arge )
	{
		if( !strcmp(*argp, "-v") || !strcmp(*argp, "--verbose") ) {
			cfg_verbose = true;
		}
		else if( !strcmp(*argp, "-h") || !strcmp(*argp, "--help") ) {
			cfg_showHelp = true;
		}
		else if( !strcmp(*argp, "--version") ) {
			cfg_showVersion = true;
		}
		else if( !strcmp(*argp, "-d") || !strcmp(*argp, "--debug") ) {
			if( ++argp>=arge )
			{
				fprintf(stderr, "Missing Argument for parameter '%s'\n", *(argp-1) );
				break;
			}
			cfg_debug = true;
			pcDebugLogName = *argp;
		}
		else if( !strcmp(*argp, "-e") || !strcmp(*argp, "--error-log") )
		{
			if( ++argp>=arge )
			{
				fprintf(stderr, "Missing Argument for parameter '%s'\n", *(argp-1) );
				break;
			}
			pcErrorLogName = *argp;
		}
		else if( !strcmp(*argp, "-l") || !strcmp(*argp, "--label-log") )
		{
			if( ++argp>=arge )
			{
				fprintf(stderr, "Missing Argument for parameter '%s'\n", *(argp-1) );
				break;
			}
			pcLabelLogName = *argp;
		}
		else if( !strcmp(*argp, "-o") || !strcmp(*argp, "--output") )
		{
			if( ++argp>=arge )
			{
				fprintf(stderr, "Missing Argument for parameter '%s'\n", *(argp-1) );
				break;
			}
			pcOutFileName = *argp;
		}
		else if( !strcmp(*argp, "-me") || !strcmp(*argp, "--max-errors") )
		{
			if( ++argp>=arge )
			{
				fprintf(stderr, "Missing Argument for parameter '%s'\n", *(argp-1) );
				break;
			}
			else
			{
				num = strtol(*argp,&epos,10);
				if( *epos!=0 )
				{
					fprintf(stderr, "Non-numeric Argument for parameter '%s'\n", *(argp-1) );
					break;
				}
				else if( num<1 )
				{
					cfg_maxerrors = (uint32_t)-1;
				}
				else
				{
					cfg_maxerrors = num;
				}
			}
		}
		else if( !strcmp(*argp, "-mw") || !strcmp(*argp, "--max-warnings") )
		{
			if( ++argp>=arge )
			{
				fprintf(stderr, "Missing Argument for parameter '%s'\n", *(argp-1) );
				break;
			}
			else
			{
				num = strtol(*argp,&epos,10);
				if( *epos!=0 )
				{
					fprintf(stderr, "Non-numeric Argument for parameter '%s'\n", *(argp-1) );
					break;
				}
				else if( num<1 )
				{
					cfg_maxwarnings = (uint32_t)-1;
				}
				else
				{
					cfg_maxwarnings = num;
				}
			}
		}
		else if( !strcmp(*argp, "-r") || !strcmp(*argp, "--simple-redefines") ) {
			cfg_allowSimpleRedefine = true;
		}
		else if( !strncmp(*argp, "-I", 2) )
		{
			if( *(*argp+2)==0 )
			{
				fprintf(stderr, "Missing Argument for parameter '%s'\n", *argp );
				break;
			}
			if( includePaths_count >= includePaths_buflen )
			{
				if( includePaths_buflen==((includePathscnt_t)-1) )
				{
					error(EM_TooManyFiles);
					goto __EXC_CleanUp__;
				}

				if( (newlen.i=includePaths_buflen<<1)<includePaths_buflen )
					newlen.i=((includePathscnt_t)-1);
				if( (newbuf=(stringsize_t**)(realloc(includePaths, newlen.i*sizeof(stringsize_t*))))==NULL )
				{
					systemError(EM_OutOfMemory);
					goto __EXC_CleanUp__;
				}
				includePaths = newbuf;
				includePaths_buflen = newlen.i;
			}
			slen = strlen(*argp+2);
			incslash = ( *(*argp+1+slen)==PATHSEPARATOR ) ? 0 : 1;

			/* count backslashes */
			cc = *argp+2;
			ce = cc + slen;
			while(cc<ce) {
				if( *(cc++)=='\\' ) {
					++incslash;
				}
			}

			if( (*(includePaths+includePaths_count)=(stringsize_t*)(malloc(slen+sizeof(stringsize_t)+incslash)))==NULL ) {
				systemError(EM_OutOfMemory);
				goto __EXC_CleanUp__;
			}
			*(*(includePaths+includePaths_count)) = slen+incslash;
			if( includeMaxLen<slen+incslash ) {
				includeMaxLen=slen+incslash;
			}
			/* copy to destination and expand backslashes */
			cc = *argp+2;
			cd = (char*)(*(includePaths+includePaths_count)+1);
			while(cc<ce) {
				if( (*(cd++)=*(cc++))=='\\' ) {
					*(cd++) = '\\';
				}
			}
			if( *(cc-1)!=PATHSEPARATOR ) {
				*cd = PATHSEPARATOR;
			}
			++includePaths_count;
		}
		else if( !strncmp(*argp, "-D", 2) )
		{
			if( *(*argp+2)==0 )
			{
				fprintf(stderr, "Missing Argument for parameter '%s'\n", *argp );
				break;
			}

			arglen = strlen(*argp+2);
			cmdlen = arglen + 1;

			if( cmdLineSrc_count+cmdlen>cmdLineSrc_buflen ) {
				if( cmdLineSrc_buflen<arglen ) {
					newlen.c = cmdLineSrc_buflen + cmdlen;
				} else {
					newlen.c = cmdLineSrc_buflen<<1;
				}
				if( newlen.c<cmdLineSrc_buflen ) {
					error(EM_TooManyLines);
					goto __EXC_CleanUp__;
				}
				newbuf_c = (char*)realloc(cmdLineSrc, newlen.c);
				if( newbuf_c==NULL ) {
					systemError(EM_OutOfMemory);
					goto __EXC_CleanUp__;
				}
				cmdLineSrc = newbuf_c;
				cmdLineSrc_buflen = newlen.c;
			}

			srcpos = cmdLineSrc+cmdLineSrc_count;
			memcpy( srcpos, *argp+2, arglen );
			srcpos += arglen;
			*srcpos = '\n';
			cmdLineSrc_count += cmdlen;
		}
		else if( !strncmp(*argp, "-W", 2) )
		{
			/* '-W' needs a parameter like '-Wall' */
			if( *(wflagpos=*argp+2)==0 )
			{
				fprintf(stderr, "Missing Argument for parameter '%s'\n", *argp );
				break;
			}
			else
			{
				wc = warnFlags;
				we = wc + arraysize(warnFlags);
				while( wc<we )
				{
					if( strcmp(wflagpos,wc->pcFlag)==0 )
					{
						ulWflags &= wc->ulMask;
						ulWflags |= wc->ulValue;
						fWflagsSet = true;
						break;
					}
					++wc;
				}
				if( wc>=we )
					fprintf(stderr, "Unknown warning flag '%s'\n", wflagpos );
			}
		}
		else
		{
			arglen = strlen(*argp);

			incslash = 0;
			/* count backslashes */
			cc = *argp;
			ce = cc + arglen;
			while(cc<ce) {
				if( *(cc++)=='\\' ) {
					++incslash;
				}
			}

			cmdlen = arglen + incslash + 12;

			if( cmdLineSrc_count+cmdlen>cmdLineSrc_buflen ) {
				if( cmdLineSrc_buflen<cmdlen ) {
					newlen.c = cmdLineSrc_buflen + cmdlen;
				} else {
					newlen.c = cmdLineSrc_buflen<<1;
				}
				if( newlen.c<cmdLineSrc_buflen ) {
					error(EM_TooManyLines);
					goto __EXC_CleanUp__;
				}
				newbuf_c = (char*)realloc(cmdLineSrc, newlen.c);
				if( newbuf_c==NULL ) {
					systemError(EM_OutOfMemory);
					goto __EXC_CleanUp__;
				}
				cmdLineSrc = newbuf_c;
				cmdLineSrc_buflen = newlen.c;
			}

			srcpos = cmdLineSrc+cmdLineSrc_count;
			memcpy(srcpos, "#include \"", 10);
			srcpos += 10;
			/* copy to destination and expand backslashes */
			cc = *argp;
			while(cc<ce) {
				if( (*(srcpos++)=*(cc++))=='\\' ) {
					*(srcpos++) = '\\';
				}
			}
			memcpy(srcpos, "\"\n", 2);

			cmdLineSrc_count += cmdlen;
			++srcFileNames_count;
		}
	};


	if( includePaths_count==0 )
	{
		free( includePaths );
		includePaths = NULL;
	}
	else if( includePaths_count<includePaths_buflen && (newbuf=(stringsize_t**)realloc(includePaths,includePaths_count*sizeof(stringsize_t*)))!=NULL )
	{
		includePaths=newbuf;
		includePaths_buflen = includePaths_count;
	}

	if( cmdLineSrc_count==0 )
	{
		free( cmdLineSrc );
		cmdLineSrc = NULL;
	}
	else if( cmdLineSrc_count<cmdLineSrc_buflen && (newbuf_c=(char*)realloc(cmdLineSrc,cmdLineSrc_count))!=NULL )
	{
		cmdLineSrc=newbuf_c;
		cmdLineSrc_buflen = cmdLineSrc_count;
	}

	if( fWflagsSet==true )
	{
		cfg_ulWarnflags = ulWflags;
	}
	else
	{
		cfg_ulWarnflags = W_Normal;
	}

/*
	printf("\n*** Arguments Start ***\n");
	printf("Verbose: %s\n", (cfg_verbose?"yes":"no"));
	printf("Output file: %s\n", (outFileName!=NULL)?outFileName:"none");
	printf("Error log: %s\n", (errorLogName!=NULL)?errorLogName:"none");
	printf("Label log: %s\n", (labelLogName!=NULL)?labelLogName:"none");
	printf("Warnflags were %s set\n", wflags_set?"":"not");
	printf("Warnflags: %lx\n", cfg_ulWarnflags);
	printf("Include paths: ");
	for(newlen.i=0; newlen.i<includePaths_count; newlen.i++)
	{
		printString(stdout, includePaths[newlen.i]);
		if( newlen.i+1<includePaths_count )
			printf(", ");
	}
	printf("\n");
	printf("Source Files: ");
	for(newlen.s=0; newlen.s<srcFileNames_count; newlen.s++)
	{
		printString(stdout, srcFileNames[newlen.s]);
		if( newlen.s+1<srcFileNames_count )
			printf(", ");
	}
	printf("\n*** Arguments End ***\n");
*/
	return true;

__EXC_CleanUp__:
	if( includePaths!=NULL )
		free(includePaths);
	if( srcFileNames!=NULL )
		free(srcFileNames);
	includePaths = NULL;
	srcFileNames = NULL;
	return false;
}
Ejemplo n.º 22
0
char *cpp_operator2(token_t *to, int *pcastoverload)
{
    int i;
    char *s;
    token_t *tn;
    int oper;

    *pcastoverload = 0;
    if (!to || !to->TKnext)
        return NULL;

    for (i = 0; i < arraysize(oparray); i++)
    {
        //printf("[%d] %d, %d\n", i, oparray[i].tokn, tok.TKval);
        if (oparray[i].tokn == to->TKval)
            goto L1;
    }

    //printf("cpp_operator2(): castoverload\n");
    *pcastoverload = 1;
    return NULL;

L1:
    tn = to->TKnext;
    s = oparray[i].string;
    oper = oparray[i].oper;
    switch (oper)
    {   case OPcall:
            if (tn->TKval != TKrpar)
                synerr(EM_rpar);        // ')' expected
            break;

        case OPbrack:
            if (tn->TKval != TKrbra)
                synerr(EM_rbra);        // ']' expected
            break;

        case OPnew:
            if (tn->TKval != TKlbra)
                break;
            oper = OPanew;              // operator new[]
            s = cpp_name_anew;
            goto L3;

        case OPdelete:
            if (tn->TKval != TKlbra)
                break;
            oper = OPadelete;           // operator delete[]
            s = cpp_name_adelete;
        L3:
            if (tn->TKval != TKrbra)
                synerr(EM_rbra);                // ']' expected
            if (!(config.flags4 & CFG4anew))
            {   cpperr(EM_enable_anew);         // throw -Aa to support this
                config.flags4 |= CFG4anew;
            }
            break;
    }
Lret:
    return s;
}
Ejemplo n.º 23
0
static void setupFontconfig()
{
    // We wish to make the layout tests reproducable with respect to fonts. Skia
    // uses fontconfig to resolve font family names from WebKit into actual font
    // files found on the current system. This means that fonts vary based on the
    // system and also on the fontconfig configuration.
    //
    // To avoid this we initialise fontconfig here and install a configuration
    // which only knows about a few, select, fonts.

    // We have fontconfig parse a config file from our resources file. This
    // sets a number of aliases ("sans"->"Arial" etc), but doesn't include any
    // font directories.
    FcInit();

    char drtPath[PATH_MAX + 1];
    int drtPathSize = readlink("/proc/self/exe", drtPath, PATH_MAX);
    if (drtPathSize < 0 || drtPathSize > PATH_MAX) {
        fputs("Unable to resolve /proc/self/exe.", stderr);
        exit(1);
    }
    drtPath[drtPathSize] = 0;
    std::string drtDirPath(drtPath);
    size_t lastPathPos = drtDirPath.rfind("/");
    ASSERT(lastPathPos != std::string::npos);
    drtDirPath.erase(lastPathPos + 1);

    FcConfig* fontcfg = FcConfigCreate();
    std::string fontconfigPath = drtDirPath + "fonts.conf";
    if (!FcConfigParseAndLoad(fontcfg, reinterpret_cast<const FcChar8*>(fontconfigPath.c_str()), true)) {
        fputs("Failed to parse fontconfig config file\n", stderr);
        exit(1);
    }

    // This is the list of fonts that fontconfig will know about. It
    // will try its best to match based only on the fonts here in. The
    // paths are where these fonts are found on our Ubuntu boxes.
    static const char *const fonts[] = {
        "/usr/share/fonts/truetype/kochi/kochi-gothic.ttf",
        "/usr/share/fonts/truetype/kochi/kochi-mincho.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Arial.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Arial_Bold.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Arial_Bold_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Arial_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Comic_Sans_MS_Bold.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Courier_New.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Courier_New_Bold.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Courier_New_Bold_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Courier_New_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Georgia.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Georgia_Bold.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Georgia_Bold_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Georgia_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Impact.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Trebuchet_MS.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Trebuchet_MS_Bold.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Trebuchet_MS_Bold_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Trebuchet_MS_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman_Bold.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman_Bold_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Verdana.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Verdana_Bold.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Verdana_Bold_Italic.ttf",
        "/usr/share/fonts/truetype/msttcorefonts/Verdana_Italic.ttf",
        "/usr/share/fonts/truetype/thai/Garuda.ttf",
        // The DejaVuSans font is used by the css2.1 tests.
        "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf",
        "/usr/share/fonts/truetype/ttf-indic-fonts-core/lohit_hi.ttf",
        "/usr/share/fonts/truetype/ttf-indic-fonts-core/lohit_ta.ttf",
        "/usr/share/fonts/truetype/ttf-indic-fonts-core/MuktiNarrow.ttf",
    };
    for (size_t i = 0; i < arraysize(fonts); ++i) {
        if (access(fonts[i], R_OK)) {
            fprintf(stderr, "You are missing %s. Try re-running build/install-build-deps.sh. Also see "
                            "http://code.google.com/p/chromium/wiki/LayoutTestsLinux",
                            fonts[i]);
            exit(1);
        }
        if (!FcConfigAppFontAddFile(fontcfg, (FcChar8 *) fonts[i])) {
            fprintf(stderr, "Failed to load font %s\n", fonts[i]);
            exit(1);
        }
    }

    // We special case these fonts because they're only needed in a
    // few layout tests.
    static const char* const optionalFonts[] = {
        "/usr/share/fonts/truetype/ttf-indic-fonts-core/lohit_pa.ttf",
    };
    for (size_t i = 0; i < arraysize(optionalFonts); ++i) {
        const char* font = optionalFonts[i];

        // This font changed paths across Ubuntu releases, so try checking in both locations.
        if (!strcmp(font, "/usr/share/fonts/truetype/ttf-indic-fonts-core/lohit_pa.ttf")
            && access(font, R_OK) < 0)
            font = "/usr/share/fonts/truetype/ttf-punjabi-fonts/lohit_pa.ttf";

        if (access(font, R_OK) < 0) {
            fprintf(stderr, "You are missing %s. Without this, some layout tests may fail. "
                            "See http://code.google.com/p/chromium/wiki/LayoutTestsLinux "
                            "for more.\n", font);
        } else if (!FcConfigAppFontAddFile(fontcfg, (FcChar8 *) font)) {
            fprintf(stderr, "Failed to load font %s\n", font);
            exit(1);
        }
    }

    // Also load the layout-test-specific "Ahem" font.
    std::string ahemPath = drtDirPath + "AHEM____.TTF";
    if (!FcConfigAppFontAddFile(fontcfg, reinterpret_cast<const FcChar8*>(ahemPath.c_str()))) {
        fprintf(stderr, "Failed to load font %s\n", ahemPath.c_str());
        exit(1);
    }

    if (!FcConfigSetCurrent(fontcfg)) {
        fputs("Failed to set the default font configuration\n", stderr);
        exit(1);
    }
}
Ejemplo n.º 24
0
static int calculate_structlens(int firststruct)
{
	int unknown = nr_structs, lastunknown;
	bool dna_error = false;

	while (unknown) {
		lastunknown = unknown;
		unknown = 0;
		
		/* check all structs... */
		for (int a = 0; a < nr_structs; a++) {
			const short *structpoin = structs[a];
			const int    structtype = structpoin[0];

			/* when length is not known... */
			if (typelens_native[structtype] == 0) {
				
				const short *sp = structpoin + 2;
				int len_native = 0;
				int len_32 = 0;
				int len_64 = 0;
				bool has_pointer = false;
				
				/* check all elements in struct */
				for (int b = 0; b < structpoin[1]; b++, sp += 2) {
					int type = sp[0];
					const char *cp = names[sp[1]];

					int namelen = (int)strlen(cp);
					/* is it a pointer or function pointer? */
					if (cp[0] == '*' || cp[1] == '*') {
						has_pointer = 1;
						/* has the name an extra length? (array) */
						int mul = 1;
						if (cp[namelen - 1] == ']') mul = arraysize(cp);

						if (mul == 0) {
							fprintf(stderr, "Zero array size found or could not parse %s: '%.*s'\n",
							        types[structtype], namelen + 1, cp);
							dna_error = 1;
						}

						/* 4-8 aligned/ */
						if (sizeof(void *) == 4) {
							if (len_native % 4) {
								fprintf(stderr, "Align pointer error in struct (len_native 4): %s %s\n",
								        types[structtype], cp);
								dna_error = 1;
							}
						}
						else {
							if (len_native % 8) {
								fprintf(stderr, "Align pointer error in struct (len_native 8): %s %s\n",
								        types[structtype], cp);
								dna_error = 1;
							}
						}

						if (len_64 % 8) {
							fprintf(stderr, "Align pointer error in struct (len_64 8): %s %s\n",
							        types[structtype], cp);
							dna_error = 1;
						}

						len_native += sizeof(void *) * mul;
						len_32 += 4 * mul;
						len_64 += 8 * mul;

					}
					else if (cp[0] == '[') {
						/* parsing can cause names "var" and "[3]" to be found for "float var [3]" ... */
						fprintf(stderr, "Parse error in struct, invalid member name: %s %s\n",
						        types[structtype], cp);
						dna_error = 1;
					}
					else if (typelens_native[type]) {
						/* has the name an extra length? (array) */
						int mul = 1;
						if (cp[namelen - 1] == ']') mul = arraysize(cp);

						if (mul == 0) {
							fprintf(stderr, "Zero array size found or could not parse %s: '%.*s'\n",
							        types[structtype], namelen + 1, cp);
							dna_error = 1;
						}

						/* struct alignment */
						if (type >= firststruct) {
							if (sizeof(void *) == 8 && (len_native % 8) ) {
								fprintf(stderr, "Align struct error: %s %s\n",
								        types[structtype], cp);
								dna_error = 1;
							}
						}
						
						/* 2-4-8 aligned/ */
						if (type < firststruct && typelens_native[type] > 4 && (len_native % 8)) {
							fprintf(stderr, "Align 8 error in struct: %s %s (add %d padding bytes)\n",
							        types[structtype], cp, len_native % 8);
							dna_error = 1;
						}
						if (typelens_native[type] > 3 && (len_native % 4) ) {
							fprintf(stderr, "Align 4 error in struct: %s %s (add %d padding bytes)\n",
							        types[structtype], cp, len_native % 4);
							dna_error = 1;
						}
						else if (typelens_native[type] == 2 && (len_native % 2) ) {
							fprintf(stderr, "Align 2 error in struct: %s %s (add %d padding bytes)\n",
							        types[structtype], cp, len_native % 2);
							dna_error = 1;
						}

						len_native += mul * typelens_native[type];
						len_32 += mul * typelens_32[type];
						len_64 += mul * typelens_64[type];
						
					}
					else {
						len_native = 0;
						len_32 = 0;
						len_64 = 0;
						break;
					}
				}
				
				if (len_native == 0) {
					unknown++;
				}
				else {
					typelens_native[structtype] = len_native;
					typelens_32[structtype] = len_32;
					typelens_64[structtype] = len_64;
					/* two ways to detect if a struct contains a pointer:
					 * has_pointer is set or len_native  doesn't match any of 32/64bit lengths*/
					if (has_pointer || len_64 != len_native || len_32 != len_native) {
						if (len_64 % 8) {
							fprintf(stderr, "Sizeerror 8 in struct: %s (add %d bytes)\n",
							        types[structtype], len_64 % 8);
							dna_error = 1;
						}
					}
					
					if (len_native % 4) {
						fprintf(stderr, "Sizeerror 4 in struct: %s (add %d bytes)\n",
						       types[structtype], len_native % 4);
						dna_error = 1;
					}
					
				}
			}
		}
		
		if (unknown == lastunknown) break;
	}
	
	if (unknown) {
		fprintf(stderr, "ERROR: still %d structs unknown\n", unknown);

		if (debugSDNA) {
			fprintf(stderr, "*** Known structs :\n");
			
			for (int a = 0; a < nr_structs; a++) {
				const short *structpoin = structs[a];
				const int    structtype = structpoin[0];
				
				/* length unknown */
				if (typelens_native[structtype] != 0) {
					fprintf(stderr, "  %s\n", types[structtype]);
				}
			}
		}

			
		fprintf(stderr, "*** Unknown structs :\n");
			
		for (int a = 0; a < nr_structs; a++) {
			const short *structpoin = structs[a];
			const int    structtype = structpoin[0];

			/* length unknown yet */
			if (typelens_native[structtype] == 0) {
				fprintf(stderr, "  %s\n", types[structtype]);
			}
		}

		dna_error = 1;
	}

	return(dna_error);
}
Ejemplo n.º 25
0
void doreltables(FILE *f)
{
    static struct
    {   enum OPER op;       /* operator                             */
        enum OPER inot;     /* for logical negation                 */
        enum OPER swap;     /* if operands are swapped              */
        enum OPER integral; /* if operands are integral types       */
        int exception;      /* if invalid exception is generated    */
        int unord;          /* result of unordered operand(s)       */
    } reltables[] =
    {   /*    op      not     swap    int     exc     unord   */
        { OPeqeq,   OPne,   OPeqeq, OPeqeq, 0,      0 },
        { OPne,     OPeqeq, OPne,   OPne,   0,      1 },
        { OPgt,     OPngt,  OPlt,   OPgt,   1,      0 },
        { OPge,     OPnge,  OPle,   OPge,   1,      0 },
        { OPlt,     OPnlt,  OPgt,   OPlt,   1,      0 },
        { OPle,     OPnle,  OPge,   OPle,   1,      0 },

        { OPunord, OPord,   OPunord, (enum OPER)0,0,1 },
        { OPlg,     OPnlg,  OPlg,   OPne,   1,      0 },
        { OPleg,    OPnleg, OPleg,  (enum OPER)1,1, 0 },
        { OPule,    OPnule, OPuge,  OPle,   0,      1 },
        { OPul,     OPnul,  OPug,   OPlt,   0,      1 },
        { OPuge,    OPnuge, OPule,  OPge,   0,      1 },
        { OPug,     OPnug,  OPul,   OPgt,   0,      1 },
        { OPue,     OPnue,  OPue,   OPeqeq, 0,      1 },

        { OPngt,    OPgt,   OPnlt,  OPle,   1,      1 },
        { OPnge,    OPge,   OPnle,  OPlt,   1,      1 },
        { OPnlt,    OPlt,   OPngt,  OPge,   1,      1 },
        { OPnle,    OPle,   OPnge,  OPgt,   1,      1 },
        { OPord,    OPunord, OPord, (enum OPER)1,0, 0 },
        { OPnlg,    OPlg,   OPnlg,  OPeqeq, 1,      1 },
        { OPnleg,   OPleg,  OPnleg, (enum OPER)0,1, 1 },
        { OPnule,   OPule,  OPnuge, OPgt,   0,      0 },
        { OPnul,    OPul,   OPnug,  OPge,   0,      0 },
        { OPnuge,   OPuge,  OPnule, OPlt,   0,      0 },
        { OPnug,    OPug,   OPnul,  OPle,   0,      0 },
        { OPnue,    OPue,   OPnue,  OPne,   0,      0 },
    };
#define RELMAX arraysize(reltables)
    enum OPER rel_not[RELMAX];
    enum OPER rel_swap[RELMAX];
    enum OPER rel_integral[RELMAX];
    int rel_exception[RELMAX];
    int rel_unord[RELMAX];
    int i;

    for (i = 0; i < RELMAX; i++)
    {   int j = (int)(reltables[i].op) - RELOPMIN;

        assert(j >= 0 && j < RELMAX);
        rel_not      [j] = reltables[i].inot;
        rel_swap     [j] = reltables[i].swap;
        rel_integral [j] = reltables[i].integral;
        rel_exception[j] = reltables[i].exception;
        rel_unord    [j] = reltables[i].unord;
    }

    fprintf(f,"unsigned char rel_not[] =\n{ ");
    for (i = 0; i < arraysize(rel_not); i++)
    {   fprintf(f,"0x%02x,",rel_not[i]);
        if ((i & 7) == 7 && i < arraysize(rel_not) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    fprintf(f,"unsigned char rel_swap[] =\n{ ");
    for (i = 0; i < arraysize(rel_swap); i++)
    {   fprintf(f,"0x%02x,",rel_swap[i]);
        if ((i & 7) == 7 && i < arraysize(rel_swap) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    fprintf(f,"unsigned char rel_integral[] =\n{ ");
    for (i = 0; i < arraysize(rel_integral); i++)
    {   fprintf(f,"0x%02x,",rel_integral[i]);
        if ((i & 7) == 7 && i < arraysize(rel_integral) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    fprintf(f,"unsigned char rel_exception[] =\n{ ");
    for (i = 0; i < arraysize(rel_exception); i++)
    {   fprintf(f,"0x%02x,",rel_exception[i]);
        if ((i & 7) == 7 && i < arraysize(rel_exception) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");

    fprintf(f,"unsigned char rel_unord[] =\n{ ");
    for (i = 0; i < arraysize(rel_unord); i++)
    {   fprintf(f,"0x%02x,",rel_unord[i]);
        if ((i & 7) == 7 && i < arraysize(rel_unord) - 1)
            fprintf(f,"\n  ");
    }
    fprintf(f,"\n};\n");
}
Ejemplo n.º 26
0
int go_flag(char *cp)
{   unsigned i;
    unsigned flag;

    enum GL     // indices of various flags in flagtab[]
    {
        GLO,GLall,GLcnp,GLcp,GLcse,GLda,GLdc,GLdv,GLli,GLliv,GLlocal,GLloop,
        GLnone,GLo,GLreg,GLspace,GLspeed,GLtime,GLtree,GLvbe,GLMAX
    };
    static const char *flagtab[] =
    {   "O","all","cnp","cp","cse","da","dc","dv","li","liv","local","loop",
        "none","o","reg","space","speed","time","tree","vbe"
    };
    static mftype flagmftab[] =
    {   0,MFall,MFcnp,MFcp,MFcse,MFda,MFdc,MFdv,MFli,MFliv,MFlocal,MFloop,
        0,0,MFreg,0,MFtime,MFtime,MFtree,MFvbe
    };

    i = GLMAX;
    assert(i == arraysize(flagtab));
    assert(i == arraysize(flagmftab));

    //printf("go_flag('%s')\n", cp);
    flag = binary(cp + 1,flagtab,GLMAX);
    if (mfoptim == 0 && flag != -1)
        mfoptim = MFall & ~MFvbe;

    if (*cp == '-')                     /* a regular -whatever flag     */
    {                                   /* cp -> flag string            */
        switch (flag)
        {
            case GLall:
            case GLcnp:
            case GLcp:
            case GLdc:
            case GLda:
            case GLdv:
            case GLcse:
            case GLli:
            case GLliv:
            case GLlocal:
            case GLloop:
            case GLreg:
            case GLspeed:
            case GLtime:
            case GLtree:
            case GLvbe:
                mfoptim &= ~flagmftab[flag];    /* clear bits   */
                break;
            case GLo:
            case GLO:
            case GLnone:
                mfoptim |= MFall & ~MFvbe;      // inverse of -all
                break;
            case GLspace:
                mfoptim |= MFtime;      /* inverse of -time     */
                break;
            case -1:                    /* not in flagtab[]     */
                goto badflag;
            default:
                assert(0);
        }
    }
    else if (*cp == '+')                /* a regular +whatever flag     */
    {                           /* cp -> flag string            */
        switch (flag)
        {
            case GLall:
            case GLcnp:
            case GLcp:
            case GLdc:
            case GLda:
            case GLdv:
            case GLcse:
            case GLli:
            case GLliv:
            case GLlocal:
            case GLloop:
            case GLreg:
            case GLspeed:
            case GLtime:
            case GLtree:
            case GLvbe:
                mfoptim |= flagmftab[flag];     /* set bits     */
                break;
            case GLnone:
                mfoptim &= ~MFall;      /* inverse of +all      */
                break;
            case GLspace:
                mfoptim &= ~MFtime;     /* inverse of +time     */
                break;
            case -1:                    /* not in flagtab[]     */
                goto badflag;
            default:
                assert(0);
        }
    }
    if (mfoptim)
    {
        mfoptim |= MFtree | MFdc;       // always do at least this much
        config.flags4 |= (mfoptim & MFtime) ? CFG4speed : CFG4space;
    }
    else
    {
        config.flags4 &= ~CFG4optimized;
    }
    return 1;                   // recognized

badflag:
    return 0;
}
Ejemplo n.º 27
0
static int drop_privs(bool klogd, bool auditd) {
    // Tricky, if ro.build.type is "eng" then this is true because of the
    // side effect that ro.debuggable == 1 as well, else it is false.
    bool eng =
        __android_logger_property_get_bool("ro.build.type", BOOL_DEFAULT_FALSE);

    struct sched_param param;
    memset(&param, 0, sizeof(param));

    if (set_sched_policy(0, SP_BACKGROUND) < 0) {
        android::prdebug("failed to set background scheduling policy");
        if (!eng) return -1;
    }

    if (sched_setscheduler((pid_t)0, SCHED_BATCH, &param) < 0) {
        android::prdebug("failed to set batch scheduler");
        if (!eng) return -1;
    }

    if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_BACKGROUND) < 0) {
        android::prdebug("failed to set background cgroup");
        if (!eng) return -1;
    }

    if (!eng && (prctl(PR_SET_DUMPABLE, 0) < 0)) {
        android::prdebug("failed to clear PR_SET_DUMPABLE");
        return -1;
    }

    if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
        android::prdebug("failed to set PR_SET_KEEPCAPS");
        if (!eng) return -1;
    }

    std::unique_ptr<struct _cap_struct, int (*)(void*)> caps(cap_init(),
                                                             cap_free);
    if (cap_clear(caps.get()) < 0) return -1;
    cap_value_t cap_value[] = { CAP_SETGID,  // must be first for below
                                klogd ? CAP_SYSLOG : CAP_SETGID,
                                auditd ? CAP_AUDIT_CONTROL : CAP_SETGID };
    if (cap_set_flag(caps.get(), CAP_PERMITTED, arraysize(cap_value), cap_value,
                     CAP_SET) < 0) {
        return -1;
    }
    if (cap_set_flag(caps.get(), CAP_EFFECTIVE, arraysize(cap_value), cap_value,
                     CAP_SET) < 0) {
        return -1;
    }
    if (cap_set_proc(caps.get()) < 0) {
        android::prdebug(
            "failed to set CAP_SETGID, CAP_SYSLOG or CAP_AUDIT_CONTROL (%d)",
            errno);
        if (!eng) return -1;
    }

    gid_t groups[] = { AID_READPROC };

    if (setgroups(arraysize(groups), groups) == -1) {
        android::prdebug("failed to set AID_READPROC groups");
        if (!eng) return -1;
    }

    if (setgid(AID_LOGD) != 0) {
        android::prdebug("failed to set AID_LOGD gid");
        if (!eng) return -1;
    }

    if (setuid(AID_LOGD) != 0) {
        android::prdebug("failed to set AID_LOGD uid");
        if (!eng) return -1;
    }

    if (cap_set_flag(caps.get(), CAP_PERMITTED, 1, cap_value, CAP_CLEAR) < 0) {
        return -1;
    }
    if (cap_set_flag(caps.get(), CAP_EFFECTIVE, 1, cap_value, CAP_CLEAR) < 0) {
        return -1;
    }
    if (cap_set_proc(caps.get()) < 0) {
        android::prdebug("failed to clear CAP_SETGID (%d)", errno);
        if (!eng) return -1;
    }

    return 0;
}
Ejemplo n.º 28
0
	{"notsup",	0},
#endif
	{"notty",	ENOTTY},
	{"nxio",	ENXIO},
	{"perm",	EPERM},
	{"pipe",	EPIPE},
	{"range",	ERANGE},
	{"rofs",	EROFS},
	{"spipe",	ESPIPE},
	{"srch",	ESRCH},
	{"toobig",	E2BIG},
	{"xdev",	EXDEV},
};

static struct sysvals error_values = {
	arraysize(error_vec),
	error_vec
};

string
posix_error_name(cerr er, int e)
{
	return sysval_name(er, Ename, &error_values, e);
}

int
posix_error_num(cerr er, string key)
{
	return sysval_num(er, Enum, &error_values, key);
}
Ejemplo n.º 29
0
static char *link_islink(const struct stat *stp, const char *file)
{
    /* Tell if a file, which stat(2) information in '*stp', has been seen
     * earlier by this function under a different name.  If not return a
     * null pointer with errno set to ENOENT, otherwise return the name of
     * the link.  Return a null pointer with an error code in errno for any
     * error, using E2BIG for a too long file name.
     *
     * Use link_islink(nil, nil) to reset all bookkeeping.
     *
     * Call for a file twice to delete it from the store.
     */

    typedef struct link {	/* In-memory link store. */
	struct link	*next;		/* Hash chain on inode number. */
	ino_t		ino;		/* File's inode number. */
	off_t		off;		/* Offset to more info in temp file. */
    } link_t;
    typedef struct dlink {	/* On-disk link store. */
	dev_t		dev;		/* Device number. */
	char		file[PATH_MAX];	/* Name of earlier seen link. */
    } dlink_t;
    static link_t *links[256];		/* Hash list of known links. */
    static int tfd= -1;			/* Temp file for file name storage. */
    static dlink_t dlink;
    link_t *lp, **plp;
    size_t len;
    off_t off;

    if (file == nil) {
	/* Reset everything. */
	for (plp= links; plp < arraylimit(links); plp++) {
	    while ((lp= *plp) != nil) {
		*plp= lp->next;
		free(lp);
	    }
	}
	if (tfd != -1) close(tfd);
	tfd= -1;
	return nil;
    }

    /* The file must be a non-directory with more than one link. */
    if (S_ISDIR(stp->st_mode) || stp->st_nlink <= 1) {
	errno= ENOENT;
	return nil;
    }

    plp= &links[stp->st_ino % arraysize(links)];

    while ((lp= *plp) != nil) {
	if (lp->ino == stp->st_ino) {
	    /* May have seen this link before.  Get it and check. */
	    if (lseek(tfd, lp->off, SEEK_SET) == -1) return nil;
	    if (read(tfd, &dlink, sizeof(dlink)) < 0) return nil;

	    /* Only need to check the device number. */
	    if (dlink.dev == stp->st_dev) {
		if (strcmp(file, dlink.file) == 0) {
		    /* Called twice.  Forget about this link. */
		    *plp= lp->next;
		    free(lp);
		    errno= ENOENT;
		    return nil;
		}

		/* Return the name of the earlier link. */
		return dlink.file;
	    }
	}
	plp= &lp->next;
    }

    /* First time I see this link.  Add it to the store. */
    if (tfd == -1) {
	for (;;) {
	    char *tmp;

	    tmp= tmpnam(nil);
	    tfd= open(tmp, O_RDWR|O_CREAT|O_EXCL, 0600);
	    if (tfd < 0) {
		if (errno != EEXIST) return nil;
	    } else {
		(void) unlink(tmp);
		break;
	    }
	}
    }
    if ((len= strlen(file)) >= PATH_MAX) {
	errno= E2BIG;
	return nil;
    }

    dlink.dev= stp->st_dev;
    strcpy(dlink.file, file);
    len += offsetof(dlink_t, file) + 1;
    if ((off= lseek(tfd, 0, SEEK_END)) == -1) return nil;
    if (write(tfd, &dlink, len) != len) return nil;

    if ((lp= malloc(sizeof(*lp))) == nil) return nil;
    lp->next= nil;
    lp->ino= stp->st_ino;
    lp->off= off;
    *plp= lp;
    errno= ENOENT;
    return nil;
}
Ejemplo n.º 30
0
error_t lcpDumpPacket(const PppPacket *packet, size_t length)
{
   error_t error;
   const char_t *label;

   //Make sure the LCP packet is valid
   if(length < sizeof(PppPacket))
      return ERROR_INVALID_LENGTH;

   //Check the length field
   if(ntohs(packet->length) > length)
      return ERROR_INVALID_LENGTH;
   if(ntohs(packet->length) < sizeof(PppPacket))
      return ERROR_INVALID_LENGTH;

   //Save the length of the LCP packet
   length = ntohs(packet->length);

   //Retrieve the name of the LCP packet
   if(packet->code < arraysize(lcpCodeLabel))
      label = lcpCodeLabel[packet->code];
   else
      label = "Unknown";

   //Dump LCP packet header
   TRACE_DEBUG("  Code = %" PRIu8 " (%s)\r\n", packet->code, label);
   TRACE_DEBUG("  Identifier = %" PRIu8  "\r\n", packet->identifier);
   TRACE_DEBUG("  Length = %" PRIu16 "\r\n", ntohs(packet->length));

   //Configure-Request, Configure-Ack, Configure-Nak or Configure-Reject packet?
   if(packet->code == PPP_CODE_CONFIGURE_REQ ||
      packet->code == PPP_CODE_CONFIGURE_ACK ||
      packet->code == PPP_CODE_CONFIGURE_NAK ||
      packet->code == PPP_CODE_CONFIGURE_REJ)
   {
      //Cast LCP packet
      PppConfigurePacket *p = (PppConfigurePacket *) packet;

      //Valid packet length?
      if(length < sizeof(PppConfigurePacket))
         return ERROR_INVALID_LENGTH;

      //Retrieve the length of the option list
      length -= sizeof(PppConfigurePacket);

      //Dump options
      error = lcpDumpOptions((PppOption *) p->options, length);
      //Any error to report?
      if(error) return error;
   }
   //Terminate-Request or Terminate-Ack packet?
   else if(packet->code == PPP_CODE_TERMINATE_REQ ||
      packet->code == PPP_CODE_TERMINATE_ACK)
   {
      //Cast LCP packet
      PppTerminatePacket *p = (PppTerminatePacket *) packet;

      //Valid packet length?
      if(length < sizeof(PppTerminatePacket))
         return ERROR_INVALID_LENGTH;

      //Retrieve the length of data
      length -= sizeof(PppTerminatePacket);

      //Any data?
      if(length > 0)
      {
         //Dump data
         TRACE_DEBUG("  Data (%" PRIuSIZE " bytes)\r\n", length);
         TRACE_DEBUG_ARRAY("    ", p->data, length);
      }
   }
   //Code-Reject packet?
   else if(packet->code == PPP_CODE_CODE_REJ)
   {
      //Cast LCP packet
      PppCodeRejPacket *p = (PppCodeRejPacket *) packet;

      //Valid packet length?
      if(length < sizeof(PppCodeRejPacket))
         return ERROR_INVALID_LENGTH;

      //Retrieve the length of Rejected-Packet field
      length -= sizeof(PppCodeRejPacket);

      //Rejected-Packet
      TRACE_DEBUG("  Rejected-Packet (%" PRIuSIZE " bytes)\r\n", length);
      TRACE_DEBUG_ARRAY("    ", p->rejectedPacket, length);
   }
   //Protocol-Reject packet?
   else if(packet->code == PPP_CODE_PROTOCOL_REJ)
   {
      //Cast LCP packet
      PppProtocolRejPacket *p = (PppProtocolRejPacket *) packet;

      //Valid packet length?
      if(length < sizeof(PppProtocolRejPacket))
         return ERROR_INVALID_LENGTH;

      //Retrieve the length of Rejected-Information field
      length -= sizeof(PppProtocolRejPacket);

      //Rejected-Protocol
      TRACE_DEBUG("  Rejected-Protocol = %" PRIu16 "\r\n", htons(p->rejectedProtocol));
      //Rejected-Information
      TRACE_DEBUG("  Rejected-Information (%" PRIuSIZE " bytes)\r\n", length);
      TRACE_DEBUG_ARRAY("    ", p->rejectedInfo, length);
   }
   //Echo-Request, Echo-Reply or Discard-Request packet?
   else if(packet->code == PPP_CODE_ECHO_REQ ||
      packet->code == PPP_CODE_ECHO_REP ||
      packet->code == PPP_CODE_DISCARD_REQ)
   {
      //Cast LCP packet
      PppEchoPacket *p = (PppEchoPacket *) packet;

      //Valid packet length?
      if(length < sizeof(PppEchoPacket))
         return ERROR_INVALID_LENGTH;

      //Retrieve the length of data
      length -= sizeof(PppEchoPacket);

      //Magic-Number
      TRACE_DEBUG("  Magic-Number = %" PRIu32 "\r\n", htonl(p->magicNumber));
      //Data
      TRACE_DEBUG("  Data (%" PRIuSIZE " bytes)\r\n", length);
      TRACE_DEBUG_ARRAY("    ", p->data, length);
   }
   //Unknown packet?
   else
   {
      //Retrieve the length of data
      length -= sizeof(PppPacket);

      //Any data?
      if(length > 0)
      {
         //Dump data
         TRACE_DEBUG("  Data (%" PRIuSIZE " bytes)\r\n", length);
         TRACE_DEBUG_ARRAY("    ", packet->data, length);
      }
   }

   //No error to report
   return NO_ERROR;
}