示例#1
0
文件: mprAlloc.c 项目: sangfo/WMI_cmd
int mprPrintAllocBlocks(MprCtx ptr, int indent)
{
    MprBlk		*bp, *firstChild, *cp;
    const char	*location;
    int			subTotal, size, indentSpaces, code;

    subTotal = 0;

    bp = GET_HDR(ptr);

    if (! (bp->flags & ALLOC_FLAGS_REQUIRED)) {
        size = bp->size + HDR_SIZE;

        /*
         *	Take one level off because we don't trace app
         */
        indentSpaces = indent;

        if (bp->flags & ALLOC_FLAGS_REQUIRED) {
            code = 'R';
        } else if (bp->flags & ALLOC_FLAGS_IS_SLAB) {
            code = 'S';
        } else {
            code = ' ';
        }

#if BLD_FEATURE_ALLOC_LEAK_TRACK
        location = bp->location;
#else
        location = "";
#endif
        mprLog(bp->app, 0,
               "%c %.*s %-16s %.*s size %5d has %3d deps, total %6d", code,
               indentSpaces, "                   ",
               mprGetBaseName(location),
               8 - indent, "          ",
               size,
               mprGetAllocBlockCount(GET_PTR(bp)),
               mprGetAllocBlockMemory(GET_PTR(bp))
               /* (uint) bp */
              );

        subTotal += size;
    }

    if ((firstChild = bp->children) != 0) {
        cp = firstChild;
        do {
            subTotal += mprPrintAllocBlocks(GET_PTR(cp), indent + 2);
            cp = cp->next;
        } while (cp != firstChild);
    }

    return subTotal;
}
示例#2
0
文件: os.cpp 项目: embedthis/appweb-2
int Mpr::loadDll(char *path, char *fnName, void *arg, void **handlePtr)
{
	MprDllEntryProc	fn;
	char			localPath[MPR_MAX_FNAME], dir[MPR_MAX_FNAME];
    void			*handle;
	char			*cp;
	int				rc;

	mprAssert(path && *path);
	mprAssert(fnName && *fnName);

	mprGetDirName(dir, sizeof(dir), path);
	mprSetModuleSearchPath(dir);

	mprStrcpy(localPath, sizeof(localPath), path);
	//	TODO - good to have a x-platform method for this.
	for (cp = localPath; *cp; cp++) {
		if (*cp == '/') {
			*cp = '\\';
		}
	}

    if ((handle = GetModuleHandle(mprGetBaseName(localPath))) == 0) {
		if ((handle = LoadLibraryEx(localPath, 0, LOAD_WITH_ALTERED_SEARCH_PATH)) == 0) {
			char cwd[1024], *env;
			getcwd(cwd, sizeof(cwd) - 1);
			env = getenv("PATH");
			mprLog(0, "ERROR %d\n", GetLastError());
			mprLog(0, "Can't load %s\nReason: \"%d\"\n", path, mprGetOsError());
			mprLog(0, "CWD %s\n PATH %s\n", cwd, env);
			return MPR_ERR_CANT_OPEN;
		}
    }

	fn = (MprDllEntryProc) GetProcAddress((HINSTANCE) handle, fnName);
	if (fn == 0) {
		FreeLibrary((HINSTANCE) handle);
		mprLog(0, "Can't load %s\nReason: can't find function \"%s\"\n", 
			localPath, fnName);
		return MPR_ERR_NOT_FOUND;
	}
	mprLog(MPR_INFO, "Loading DLL %s\n", path);

	if ((rc = (fn)(arg)) < 0) {
		FreeLibrary((HINSTANCE) handle);
		mprError(MPR_L, MPR_LOG, "Initialization for %s failed.", path);
		return MPR_ERR_CANT_INITIALIZE;
	}
	if (handlePtr) {
		*handlePtr = handle;
	}
	return rc;
}
示例#3
0
文件: os.cpp 项目: OPSF/uClinux
int Mpr::loadDll(char *path, char *fnName, void *arg, void **handlePtr)
{
	MprEntryProc	fn;
	char			localPath[MPR_MAX_FNAME];
    void			*handle;
	char			*cp;
	int				rc;

	mprAssert(path && *path);
	mprAssert(fnName && *fnName);

	mprStrcpy(localPath, sizeof(localPath), path);
	for (cp = localPath; *cp; cp++) {
		if (*cp == '/') {
			*cp = '\\';
		}
	}
    if ((handle = GetModuleHandle(mprGetBaseName(localPath))) == 0) {
		if ((handle = LoadLibrary(localPath)) == 0) {
			mprLog(0, "Can't load %s\nReason: \"%d\"\n", path, mprGetOsError());
			return MPR_ERR_CANT_OPEN;
		}
    }

	if ((fn = (MprEntryProc) GetProcAddress((HINSTANCE) handle, fnName)) == 0) {
		FreeLibrary((HINSTANCE) handle);
		mprLog(0, "Can't load %s\nReason: can't find function \"%s\"\n", 
			localPath, fnName);
		return MPR_ERR_NOT_FOUND;
	}
	if ((rc = (fn)(arg)) < 0) {
		FreeLibrary((HINSTANCE) handle);
		return MPR_ERR_CANT_INITIALIZE;
	}
	mprLog(MPR_INFO, "Loading DLL %s\n", path);
	if (handlePtr) {
		*handlePtr = handle;
	}
	return rc;
}
示例#4
0
int main(int argc, char *argv[])
{
	time_t		now;
	struct tm	*t;
	char		path[2048], cwd[2048], dirName[2048], parent[2048];
	char		*ext, *previous, *cp;
	int 		errors, c, j, i, levels, upLevel, incJava;

	errors = 0;
	program = mprGetBaseName(argv[0]);
	quiet = 0;

	while ((c = getopt(argc, argv, "?I:o:q")) != EOF) {
		switch(c) {
		case 'I':
			if (numIncludeDir >= MAX_INC) {
				fprintf(stderr, "Too many include directories\n");
				exit(1);
			}
			includeDir[numIncludeDir++] = strdup(optarg);
			break;
	
		case 'q':
			quiet++;
			break;

		case '?':
			errors++;
			break;
		}
	}
	if (errors) {
		fprintf(stderr, 
			"%s: usage: [-q] [-I includeDir] files...\n", program);
		exit(2);
	}

	includeDir[numIncludeDir++] = strdup(".");
#if !WIN && !_WIN32
	includeDir[numIncludeDir++] = strdup("/usr/include");
#endif

	openSignals();
	if ((fp = fopen("make.dep", "w")) == 0) {
		fprintf(stderr, "Cant open make.dep\n");
		exit(255);
	}

	now = time(0);
	t = localtime(&now);
	fprintf(fp, "#\n#	make.dep -- Makefile dependencies. Generated by genDepend.\n#\n\n");

	getcwd(cwd, sizeof(cwd));
	mapDelimiters(cwd);

	fprintf(fp, "all: compile\n\n");

	fprintf(fp, "BLD_TOP := ");
	strcpy(dirName, cwd);

	for (i = 0, levels = 0; *dirName; i++) {
		sprintf(path, "%s/build/make/make.rules", dirName);
		if (access(path, R_OK) == 0) {
			break;
		}
		mprGetDirName(parent, sizeof(parent), dirName);
		strcpy(dirName, parent);
		if (i > 0) {
			fprintf(fp, "/..");
		} else {
			fprintf(fp, "..");
		}
		levels++;
	}
	if (i == 0) {
		fprintf(fp, ".");
	}
	fprintf(fp, "\n");

	/*
	 *	Extract a src path for Java. Go up N levels less one for the "java"
	 *	directory.
	 */
	strcpy(dirName, cwd);
	cp = &dirName[strlen(dirName) - 1];
	for (upLevel = 1; upLevel < levels && cp > dirName; cp--) {
		if (*cp == '/') {
			upLevel++;
		}
	}

	if (levels > 1) {
		if (cp[0] != '\0' && cp[1] != '\0' && cp[2] != '\0') {
			cp += 2;
		}
		if (*cp == '\0') {
			cp = ".";
		}
		fprintf(fp, "SRC_PATH := %s\n\n", cp);

	} else {
		fprintf(fp, "SRC_PATH := .\n\n");
	}

	fprintf(fp, "#\n#	Read the build configuration settings and make"
				"variable definitions.\n#\n"); 
	fprintf(fp, "include $(BLD_TOP)/buildConfig.make\n\n");

	incJava = 0;
	for (i = optind; i < argc; i++) {
		if (strstr(argv[i], ".java") != 0 && strcmp(argv[i], "*.java") != 0) {
			incJava++;
			// fprintf(fp, "include $(BLD_TOP)/build/make/make.java\n");
			break;
		}
	}
	if (incJava) {
		fprintf(fp, "HAS_JAVA = 1\n\n");
	}

	fprintf(fp, "SRC =");
	for (i = optind; i < argc; i++) {
		if (access(argv[i], R_OK) != 0) {
			continue;
		}
		strncpy(path, argv[i], sizeof(path));
		fprintf(fp, " \\\n\t%s", mprGetBaseName(path));
	}
	fprintf(fp, "\n\n");

	fprintf(fp, "PROCESSED_SRC =");
	for (i = optind; i < argc; i++) {
		if (access(argv[i], R_OK) != 0) {
			continue;
		}
		strncpy(path, argv[i], sizeof(path));
		ext = mapExtension(path);
		if (strcmp(ext, ".java") == 0) {
			fprintf(fp, " \\\n\t$(BLD_OBJ_DIR)/src/$(SRC_PATH)/%s", 
				mprGetBaseName(argv[i]));
		}
	}
	fprintf(fp, "\n\n");

	fprintf(fp, "FILES =");
	for (i = optind; i < argc; i++) {
		if (access(argv[i], R_OK) != 0) {
			continue;
		}
		strncpy(path, argv[i], sizeof(path));
		ext = mapExtension(path);
		if (strcmp(ext, ".java") == 0) {
			fprintf(fp, " \\\n\t$(BLD_OBJ_DIR)/classes/$(SRC_PATH)/%s", 
				mprGetBaseName(path));
		} else {
			fprintf(fp, " \\\n\t$(BLD_OBJ_DIR)/%s", mprGetBaseName(path));
		}
	}
	fprintf(fp, "\n");

	for (i = optind; !finished && i < argc; i++) {
		if (*argv[i] == '*') {
			continue;
		}
		strcpy(path, argv[i]);
		ext = mapExtension(path);
		if (strcmp(ext, ".java") == 0) {
			fprintf(fp, "\n$(BLD_OBJ_DIR)/classes/$(SRC_PATH)/%s: ", 
				mprGetBaseName(path));
		} else {
			fprintf(fp, "\n$(BLD_OBJ_DIR)/%s: ", mprGetBaseName(path));
		}

		numDependencies = 0;
		findDependencies(fp, argv[i]);
		qsort(dependencies, numDependencies, sizeof(char*), depSort);

		previous = "";
		for (j = 0; j < numDependencies; j++) {
			if (strcmp(previous, dependencies[j]) != 0) {
				fprintf(fp, " \\\n\t%s", dependencies[j]);
			}
			previous = dependencies[j];
		}
		for (j = 0; j < numDependencies; j++) {
			free(dependencies[j]);
		}
		fprintf(fp, "\n");
	}

	fprintf(fp, "\n#\n#	Read the Makefile rules\n#\n");
	fprintf(fp, "include $(BLD_TOP)/build/make/make.rules\n\n");

	fprintf(fp, "ifeq ($(BUILDING_CROSS),1)\n");
	fprintf(fp, "	include $(BLD_TOP)/build/make/make.os.$(BLD_HOST_OS)\n");
	fprintf(fp, "else\n");
	fprintf(fp, "	include $(BLD_TOP)/build/make/make.os.$(BLD_BUILD_OS)\n");
	fprintf(fp, "endif\n\n");

	fclose(fp);

	return 0;
}
示例#5
0
int main(int argc, char *argv[])
{
	double			elapsed;
	char			*programName, *argp, *logSpec;
	int				c, errflg, start;
#if BLD_FEATURE_LOG
	MprLogToFile	*logger;
#endif
#if BLD_FEATURE_MULTITHREAD
	MprThread		*threadp;
#endif

	programName = mprGetBaseName(argv[0]);
	method = "GET";
	fileList = cmpDir = writeDir = 0;
	verbose = continueOnErrors = outputHeader = errflg = 0;
	poolThreads = 4;			// Need at least one to run efficiently
	httpVersion = 1;			// HTTP/1.1
	success = 1;
	trace = 0;
	host = "localhost";
	logSpec = "stdout:1";
	postData = 0;
	postLen = 0;
	retries = MPR_HTTP_CLIENT_RETRIES;
	iterations = HTTP_DEFAULT_ITERATIONS;
	loadThreads = HTTP_DEFAULT_LOAD_THREADS;
	timeout = MPR_HTTP_CLIENT_TIMEOUT;

#if BLD_FEATURE_MULTITHREAD
	mutex = new MprMutex();
#endif

	//
	//	FUTURE: switch to GNU style --args with a better usage message
	//
	MprCmdLine	cmdLine(argc, argv, "bC:cDd:f:Hh:i:l:M:mqo:r:st:T:vV:w:");
	while ((c = cmdLine.next(&argp)) != EOF) {
		switch(c) {
		case 'b':
			benchmark++;
			break;

		case 'c':
			continueOnErrors++;
			break;

		case 'C':
			cmpDir = argp;
			break;

		case 'd':
			postData = argp;
			postLen = strlen(postData);
			break;

		case 'D':
			mprSetDebugMode(1);
			break;

		case 'f':
			fileList = argp;
			break;

		case 'h':
			host = argp;
			break;

		case 'H':
			outputHeader++;
			break;

		case 'i':
			iterations = atoi(argp);
			break;

		case 'l':
			logSpec = argp;
			break;

		case 'm':
			mprRequestMemStats(1);
			break;

		case 'M':
			method = argp;
			break;

		case 'o':
			timeout = atoi(argp);
			break;

		case 'q':
			quietMode++;
			break;

		case 'r':
			retries = atoi(argp);
			break;

		case 's':
			singleStep++;
			break;

		case 't':
			loadThreads = atoi(argp);
			break;

		case 'T':
			poolThreads = atoi(argp);
			break;

		case 'v':
			verbose++;
			trace++;
			break;

		case 'V':
			httpVersion = atoi(argp);
			break;

		case 'w':
			writeDir = argp;
			break;

		default:
			errflg++;
			break;
		}
	}
	if (writeDir && (loadThreads > 1)) {
		errflg++;
	}

	if (errflg) {
		mprFprintf(MPR_STDERR, 
			"usage: %s [-bcHMmqsTv] [-C cmpDir] [-d postData] [-f fileList]\n"
			"	[-i iterations] [-l logSpec] [-M method] [-o timeout]\n"
			"	[-h host] [-r retries] [-t threads] [-T poolThreads]\n"
			"	[-V httpVersion] [-w writeDir] [urls...]\n", programName);
		exit(2);
	}
	saveArgc = argc - cmdLine.firstArg();
	saveArgv = &argv[cmdLine.firstArg()];

	mpr = new Mpr(programName);

#if BLD_FEATURE_LOG
	tMod = new MprLogModule("httpClient");
	logger = new MprLogToFile();
	mpr->addListener(logger);
	if (mpr->setLogSpec(logSpec) < 0) {
		mprFprintf(MPR_STDERR, "Can't open log file %s\n", logSpec);
		exit(2);
	}
#endif

	//
	//	Alternatively, set the configuration manually
	//
	mpr->setAppTitle("Embedthis HTTP Client");
#if BLD_FEATURE_MULTITHREAD
	mpr->setMaxPoolThreads(poolThreads);
#endif

	//
	//	Start the Timer, Socket and Pool services
	//
	if (mpr->start(MPR_SERVICE_THREAD) < 0) {
		mprError(MPR_L, MPR_USER, "Can't start MPR for %s", mpr->getAppTitle());
		delete mpr;
		exit(2);
	}

	//
	//	Create extra test threads to run the tests as required. We use
	//	the main thread also (so start with j==1)
	//
	start = mprGetTime(0);
#if BLD_FEATURE_MULTITHREAD
	activeLoadThreads = loadThreads;
	for (int j = 1; j < loadThreads; j++) {
		char name[64];
		mprSprintf(name, sizeof(name), "t.%d", j - 1);
		threadp = new MprThread(doTests, MPR_NORMAL_PRIORITY, (void*) j, name); 
		threadp->start();
	}
#endif

	doTests(0, 0);

	//
	//	Wait for all the threads to complete (simple but effective). Keep 
	//	servicing events as we wind down.
	//
	while (activeLoadThreads > 1) {
		mprSleep(100);
	}

	if (benchmark && success) {
		elapsed = (mprGetTime(0) - start);
		if (fetchCount == 0) {
			elapsed = 0;
			fetchCount = 1;
		}
		mprPrintf("\tThreads %d, Pool Threads %d   \t%13.2f\t%12.2f\t%6d\n", 
			loadThreads, poolThreads, elapsed * 1000.0 / fetchCount, 
			elapsed / 1000.0, fetchCount);

		mprPrintf("\nTime elapsed:        %13.4f sec\n", elapsed / 1000.0);
		mprPrintf("Time per request:    %13.4f sec\n", elapsed / 1000.0 
			/ fetchCount);
		mprPrintf("Requests per second: %13.4f\n", fetchCount * 1.0 / 
			(elapsed / 1000.0));
	}
	if (! quietMode) {
		mprPrintf("\n");
	}

	mpr->stop(0);

#if BLD_FEATURE_MULTITHREAD
	delete mutex;
#endif
#if BLD_FEATURE_LOG
	delete tMod;
#endif

	delete mpr;
#if BLD_FEATURE_LOG
	delete logger;
#endif
	mprMemClose();
	return (success) ? 0 : 255;
}
示例#6
0
int main(int argc, char **argv)
{
    cchar   *searchPath, *argp, *program;
    int     nextArg, err;

    /*
     *  Create the Embedthis Portable Runtime (MPR) and setup a memory failure handler
     */
    mpr = mprCreate(argc, argv, ejsMemoryFailure);
    program = mprGetBaseName(argv[0]);
    mprSetAppName(mpr, program, 0, 0);

    if (strcmp(program, "ejscgi-debug") == 0) {
        debug++;
    }

    if (mprStart(mpr, 0) < 0) {
        mprError(mpr, "Can't start mpr services");
        return EJS_ERR;
    }

    for (err = 0, nextArg = 1; nextArg < argc; nextArg++) {
        argp = argv[nextArg];
        if (*argp != '-') {
            break;
        }

        if (strcmp(argp, "--debug") == 0 || strcmp(argp, "-d") == 0) {
            debug++;

#if BLD_DEBUG
        } else if (strcmp(argp, "--dummy") == 0) {
            dummy++;
#endif
        } else if (strcmp(argp, "--log") == 0 || strcmp(argp, "-l") == 0) {
            if (nextArg >= argc) {
                err++;
            } else {
                ejsStartLogging(mpr, argv[++nextArg]);
            }

        } else if (strcmp(argp, "--searchpath") == 0) {
            if (nextArg >= argc) {
                err++;
            } else {
                searchPath = argv[++nextArg];
            }

        } else if (strcmp(argp, "--version") == 0 || strcmp(argp, "-V") == 0) {
            mprErrorPrintf(mpr, "%s %s\n"
                "Copyright (C) Embedthis Software 2003-2009\n"
                "Copyright (C) Michael O'Brien 2003-2009\n",
               BLD_NAME, BLD_VERSION);
            exit(0);

        } else {
            err++;
            break;
        }
    }

    if (err) {
        mprErrorPrintf(mpr,
            "Usage: %s [options]\n"
            "  Options:\n"
            "  --log logSpec            # Diagnostic trace\n"
            "  --searchpath ejsPath     # Module search path\n"
            "  --version                # Emit the program version information\n\n",
            mpr->name);
        return -1;
    }

    if (initControlBlock() < 0) {
        error(NULL, 0, "Can't initialize control block");
        exit(1);
    }

    //  FAST CGI must update this
    currentDate = getDateString(0);

    if (getRequest() < 0) {
        error(NULL, 0, "Can't get request");
    } else {
        processRequest();
    }

    if (responseCode && responseMsg) {
        fprintf(stderr, "ejscgi: ERROR: %s\n", responseMsg);
    }

    return 0;
}
示例#7
0
static int realMain(MprCmdLine *cmdLine)
{
	MaHttp		*http;
	char        portNumBuf[MPR_MAX_IP_PORT];
	char		*argp, *logSpec;
	int			c, errflg, kill, poolThreads, outputVersion;

	mprSetMemHandler(memoryFailure);
	mprCreateMemHeap(0, 16 * 1024, MAXINT);
	program = mprGetBaseName(cmdLine->getArgv()[0]);

	poolThreads = -1;
	kill = errflg = 0;
	logSpec = 0;
	outputVersion = 0;
	autoScan = 1;
	background = 0;

	serverRoot = 0;
	docRoot = "web";

#if !WIN && !WINCE && !VXWORKS
	if (getuid()) {
		ipAddr = mprStrdup("4000");

	} else {
		mprSprintf(portNumBuf, sizeof(portNumBuf), "%d", 
			MA_SERVER_DEFAULT_PORT_NUM);
		ipAddr = mprStrdup(portNumBuf);
	}
#else
	mprSprintf(portNumBuf, sizeof(portNumBuf), "%d", 
		MA_SERVER_DEFAULT_PORT_NUM);
	    
	ipAddr = mprStrdup(portNumBuf);
#endif

	while ((c = cmdLine->next(&argp)) != EOF) {
		switch(c) {
		case 'A':
			autoScan = 0;
			break;

		case 'a':
			mprFree(ipAddr);
			ipAddr = mprStrdup(argp);
			break;
			
		case 'b':
			background++;
			break;

		case 'c':
			/* Ignored */
			break;

		case 'D':
			mprSetDebugMode(1);
			break;

		case 'd':
			docRoot = argp;
			break;

		case 'f':
#if BLD_FEATURE_CONFIG_PARSE
			configFile = argp;
			autoScan = 0;
#else
			errflg++;
#endif
			break;

		case 'k':
			kill++;
			logSpec = 0;
			break;

		case 'l':
			logSpec = (*argp) ? argp : 0;
			break;

		case 'm':
			mprRequestMemStats(1);
			break;

		case 'r':
			serverRoot = argp;
			break;
		
		case 't':
			poolThreads = atoi(argp);
			break;

			//
			//	FUTURE -- just for test. Will be removed
			//
		case 'w':
			writeFile = argp;
			break;

		case 'v':
			outputVersion++;
			break;
		
#if WIN && BLD_FEATURE_RUN_AS_SERVICE
		case 'i':
			serviceOp = MPR_INSTALL_SERVICE;
			if (strcmp(argp, "none") == 0) {
				serviceCmdLine = "";
			} else if (strcmp(argp, "default") == 0) {
				serviceCmdLine = "-b -c -f " BLD_PRODUCT ".conf";
			} else {
				serviceCmdLine = argp;
			}
			break;

		case 'g':
			serviceOp = MPR_GO_SERVICE;
			break;

		case 's':
			serviceOp = MPR_STOP_SERVICE;
			break;

		case 'u':
			serviceOp = MPR_UNINSTALL_SERVICE;
			break;

#endif
		default:
			errflg++;
			break;
		}
	}

	if (errflg) {
		printUsage(program);
		return MPR_ERR_BAD_SYNTAX;
	}	

	mp = new Mpr(program);
	mp->setAppName(BLD_PRODUCT);
	mp->setAppTitle(BLD_NAME);
	mp->setHeadless(isService || background);

#if BLD_HOST_UNIX || VXWORKS
	initSignals();
#endif

	if (kill) {
		mp->killMpr();
		delete mp;
		exit(0);
	}

	if (outputVersion) {
		printVersion();
		delete mp;
		exit(0);
	}

	//
	//	Create the top level HTTP service and default HTTP server
	//
	http = new MaHttp();
	server = new MaServer(http, "default");
	setupFileSystem();
	
	setLogging(logSpec);

	//
	//	Confirm the location of the server root
	//
	if (locateServerRoot(serverRoot) < 0) {
		mprError(MPR_L, MPR_USER, "Can't start server, exiting.");
		exit(2);
	}

	if (securityChecks(cmdLine->getArgv()[0]) < 0) {
		exit(3);
	}

#if WIN
#if BLD_FEATURE_RUN_AS_SERVICE
	if (serviceOp) {
		windowsServiceOps();
		delete mp;
		return 0;
	}
#endif
	if (windowsInit() < 0) {
		delete mp;
		return MPR_ERR_CANT_INITIALIZE;
	}
#endif

	//
	//	Start the MPR. This starts Timer, Socket and Pool services
	//
	if (mp->start(MPR_KILLABLE) < 0) {
		mprError(MPR_L, MPR_USER, "Can't start MPR for %s", mp->getAppTitle());
		delete mp;
		return MPR_ERR_CANT_INITIALIZE;
	}

	//
	//	Load the statically linked modules
	//
	maLoadStaticModules();

	if (setupServer(http, poolThreads) < 0) {
		mprError(MPR_L, MPR_USER, "Can't configure the server, exiting.");
		exit(6);
	}

#if BLD_FEATURE_CONFIG_SAVE
	if (writeFile) {
		server->saveConfig(writeFile);
		mprLog(0, "Configuration saved to %s\nExiting ...\n", writeFile);
		exit(0);
	}
#endif

	if (http->start() < 0) {
		mprError(MPR_L, MPR_USER, "Can't start server, exiting.");
		exit(7); 

	} else {
#if LINUX && BLD_FEATURE_RUN_AS_SERVICE
		if (background && mp->makeDaemon(1) < 0) {
			mprError(MPR_L, MPR_USER, "Could not run in the background");
		} else 
#endif
		{
#if BLD_FEATURE_MULTITHREAD
			mprLog(MPR_CONFIG, 
				"HTTP services are ready with %d pool threads\n",
				http->getLimits()->maxThreads);
#else
			mprLog(MPR_CONFIG, 
				"HTTP services are ready (single-threaded).\n");
#endif
		}
		mp->setHeadless(1);

		eventLoop();

		mprLog(MPR_WARN, "Stopping HTTP services.\n");
		http->stop();
	}

#if WIN
	if (trayIcon > 0) {
		closeTrayIcon();
	}
	if (trayTimer) {
		trayTimer->stop(MPR_TIMEOUT_STOP);
		trayTimer->dispose();
		trayTimer = 0;
	}
#endif

	mprLog(MPR_WARN, "Stopping MPR services.\n");
	mp->stop(0);
	maUnloadStaticModules();
	delete server;
	delete http;
	delete mp;

	mprFree(ipAddr);

#if BLD_FEATURE_ROMFS
	delete romFileSystem;
#endif

#if BLD_FEATURE_LOG
	mprLog(MPR_WARN, "Closing log.\n");
	if (logger) {
		delete logger;
	}
#if WIN
	if (dialog) {
		delete dialog;
	}
#endif
#endif
	return 0;
}
示例#8
0
文件: ejsDb.c 项目: jsjohnst/ejscript
/*
 *  DB Constructor and also used for constructor for sub classes.
 *
 *  function DB(connectionString: String)
 */
static EjsVar *dbConstructor(Ejs *ejs, EjsDb *db, int argc, EjsVar **argv)
{
    sqlite3     *sdb;
    EjsDb       **dbp;
    char        *path;

    path = ejsGetString(argv[0]);    
    
    /*
     *  Create a memory context for use by sqlite. This is a virtual paged memory region.
     *  TODO - this is not ideal for long running applications.
     */
    db->arena = mprAllocArena(ejs, "sqlite", EJS_MAX_DB_MEM, 0, 0);
    if (db->arena == 0) {
        return 0;
    }
    
    /*
     *  Create a destructor object so we can cleanup and close the database. Must create after the arena so it will be
     *  invoked before the arena is freed. 
     */
    if ((dbp = mprAllocObject(ejs, 1, (MprDestructor) dbDestructor)) == 0) {
        ejsThrowMemoryError(ejs);
        return 0;
    }
    *dbp = db;
    
    db->tls = mprCreateThreadLocal(db->arena);
    if (db->tls == 0) {
        return 0;
    }
    ejsSetDbMemoryContext(db->tls, db->arena);

    sdb = 0;
    if (sqlite3_open(path, &sdb /* TODO remove , SQLITE_OPEN_READWRITE, 0 */) != SQLITE_OK) {
        ejsThrowIOError(ejs, "Can't open database %s", path);
        return 0;
    }
    db->sdb = sdb;

    sqlite3_busy_timeout(sdb, 15000);

    /*
     *  Query or change the count-changes flag. Normally, when the count-changes flag is not set, INSERT, UPDATE and
     *  DELETE statements return no data. When count-changes is set, each of these commands returns a single row of
     *  data consisting of one integer value - the number of rows inserted, modified or deleted by the command. The
     *  returned change count does not include any insertions, modifications or deletions performed by triggers.
     */
//  sqlite3_exec(sdb, "PRAGMA count_changes = OFF", NULL, NULL, NULL);

    ejsSetProperty(ejs, (EjsVar*) db, ES_ejs_db_Database__connection, (EjsVar*) ejsCreateString(ejs, path));
    ejsSetProperty(ejs, (EjsVar*) db, ES_ejs_db_Database__name, (EjsVar*) ejsCreateString(ejs, mprGetBaseName(path)));
    
    return 0;
}
示例#9
0
文件: edep.c 项目: embedthis/appweb-3
int main(int argc, char *argv[])
{
    char        path[2048], cwd[2048], dirName[2048], parent[2048];
    char        *ext, *previous, *cp, *argp;
    int         errors, j, i, levels, upLevel, incJava, nextArg;

    errors = 0;
    program = mprGetBaseName(argv[0]);
    quiet = 0;

    for (nextArg = 1; nextArg < argc; nextArg++) {
        argp = argv[nextArg];
        if (*argp != '-') {
            break;
        }
        if (strncmp(argp, "-I", 2) == 0) {
            if (numIncludeDir >= MAX_INC) {
                fprintf(stderr, "Too many include directories\n");
                exit(1);
            }
            includeDir[numIncludeDir++] = strdup(&argp[2]);

        } else if (strcmp(argp, "-q") == 0) {
            quiet++;
        }
    }
    if (errors) {
        fprintf(stderr, "%s: usage: [-q] [-I includeDir] files...\n", program);
        exit(2);
    }

    includeDir[numIncludeDir++] = strdup(".");
#if !BLD_WIN_LIKE && !_WIN32
    includeDir[numIncludeDir++] = strdup("/usr/include");
#endif

    openSignals();
    if ((fp = fopen("make.newdep", "w")) == 0) {
        fprintf(stderr, "Cant open make.newdep\n");
        exit(255);
    }
    fprintf(fp, "#\n#   .makedep -- Makefile dependencies. Generated by edep.\n#\n\n");

    if (getcwd(cwd, sizeof(cwd)) == 0) {
        fprintf(stderr, "Can't get working directory");
        exit(255);
    }
    mapDelimiters(cwd);

    fprintf(fp, "all: compile\n\n");

    fprintf(fp, "BLD_TOP := ");
    strcpy(dirName, cwd);

    for (i = 0, levels = 0; *dirName; i++) {
        sprintf(path, "%s/build/make/make.rules", dirName);
        if (access(path, R_OK) == 0) {
            break;
        }
        mprGetDirName(parent, sizeof(parent), dirName);
        strcpy(dirName, parent);
        if (i > 0) {
            fprintf(fp, "/..");
        } else {
            fprintf(fp, "..");
        }
        levels++;
    }
    if (i == 0) {
        fprintf(fp, ".");
    }
    fprintf(fp, "\n");

    /*
     *  Extract a src path for Java. Go up N levels less one for the "java" directory.
     */
    strcpy(dirName, cwd);
    cp = &dirName[strlen(dirName) - 1];
    for (upLevel = 1; upLevel < levels && cp > dirName; cp--) {
        if (*cp == '/') {
            upLevel++;
        }
    }

    if (levels > 1) {
        if (cp[0] != '\0' && cp[1] != '\0' && cp[2] != '\0') {
            cp += 2;
        }
        if (*cp == '\0') {
            cp = ".";
        }
        fprintf(fp, "SRC_PATH := %s\n\n", cp);

    } else {
        fprintf(fp, "SRC_PATH := .\n\n");
    }

    fprintf(fp, "#\n#   Read the build configuration settings and make variable definitions.\n#\n"); 
    fprintf(fp, "include $(BLD_TOP)/buildConfig.make\n\n");

    incJava = 0;
    for (i = nextArg; i < argc; i++) {
        if (strstr(argv[i], ".java") != 0 && strcmp(argv[i], "*.java") != 0) {
            incJava++;
            /* fprintf(fp, "include $(BLD_TOP)/build/make/make.java\n"); */
            break;
        }
    }
    if (incJava) {
        fprintf(fp, "HAS_JAVA = 1\n\n");
    }

    fprintf(fp, "SRC =");
    for (i = nextArg; i < argc; i++) {
        if (access(argv[i], R_OK) != 0) {
            continue;
        }
        strncpy(path, argv[i], sizeof(path));
        fprintf(fp, " \\\n\t%s", mprGetBaseName(path));
    }
    fprintf(fp, "\n\n");

    fprintf(fp, "PROCESSED_SRC =");
    for (i = nextArg; i < argc; i++) {
        if (access(argv[i], R_OK) != 0) {
            continue;
        }
        strncpy(path, argv[i], sizeof(path));
        ext = mapExtension(path);
        if (strcmp(ext, ".java") == 0) {
            fprintf(fp, " \\\n\t$(BLD_OBJ_DIR)/src/$(SRC_PATH)/%s", 
                mprGetBaseName(argv[i]));
        }
    }
    fprintf(fp, "\n\n");

    fprintf(fp, "OBJECTS =");
    for (i = nextArg; i < argc; i++) {
        if (access(argv[i], R_OK) != 0) {
            continue;
        }
        strncpy(path, argv[i], sizeof(path));
        ext = mapExtension(path);
        if (strcmp(ext, ".java") == 0) {
            fprintf(fp, " \\\n\t$(BLD_OBJ_DIR)/classes/$(SRC_PATH)/%s", 
                mprGetBaseName(path));
        } else {
            fprintf(fp, " \\\n\t$(BLD_OBJ_DIR)/%s", mprGetBaseName(path));
        }
    }
    fprintf(fp, "\n");

    for (i = nextArg; !finished && i < argc; i++) {
        if (*argv[i] == '*') {
            continue;
        }
        strcpy(path, argv[i]);
        ext = mapExtension(path);
        if (strcmp(ext, ".java") == 0) {
            fprintf(fp, "\n$(BLD_OBJ_DIR)/classes/$(SRC_PATH)/%s: ", 
                mprGetBaseName(path));
        } else {
            fprintf(fp, "\n$(BLD_OBJ_DIR)/%s: ", mprGetBaseName(path));
        }

        numDependencies = 0;
        findDependencies(fp, argv[i]);
        qsort(dependencies, numDependencies, sizeof(char*), depSort);

        previous = "";
        for (j = 0; j < numDependencies; j++) {
            if (strcmp(previous, dependencies[j]) != 0) {
                fprintf(fp, " \\\n\t%s", dependencies[j]);
            }
            previous = dependencies[j];
        }
        for (j = 0; j < numDependencies; j++) {
            free(dependencies[j]);
        }
        fprintf(fp, "\n");
    }

    fprintf(fp, "\n#\n# Read the Makefile rules\n#\n");
    fprintf(fp, "include $(BLD_TOP)/build/make/make.rules\n\n");

    fprintf(fp, "ifeq ($(BUILDING_CROSS),1)\n");
    fprintf(fp, "   include $(BLD_TOP)/build/make/make.$(BLD_HOST_OS)\n");
    fprintf(fp, "else\n");
    fprintf(fp, "   include $(BLD_TOP)/build/make/make.$(BLD_BUILD_OS)\n");
    fprintf(fp, "endif\n\n");

    fclose(fp);

    unlink("make.dep");
    unlink(".makedep");
    if (rename("make.newdep", ".makedep") != 0) {
        fprintf(stderr, "Cant rename make.newdep to .makedep\n");
        exit(255);
    }

    return 0;
}
示例#10
0
int MaCgiHandler::run(MaRequest *rq)
{
	MprVar		*vp, *variables;
	char		**argv, **envv, **ep, *fileName, *baseName;
	int			i, index, argc, numItems;

	if (rq->getFlags() & MPR_HTTP_POST_REQUEST && rq->getRemainingContent() > 0) {
		//
		//	When all the post data is received the run method will be recalled
		//	by the postData method.
		//
		return MPR_HTTP_HANDLER_FINISHED_PROCESSING;
	}

	argv = 0;
	variables = 0;
	argc = 0;

	hitCount++;
	rq->setResponseCode(200);
	rq->setHeaderFlags(MPR_HTTP_DONT_CACHE, 0);
	rq->insertDataStream(rq->getDynBuf());

	//
	//	Build the commmand line arguments
	//
	argc = 1;									// argv[0] == programName
	buildArgs(&argc, &argv, cmd, rq);
	fileName = argv[0];

	rq->setResponseMimeType("text/html");

	baseName = mprGetBaseName(fileName);
	if (strncmp(baseName, "nph-", 4) == 0) {
		cgiFlags |= MPR_CGI_NON_PARSED_HEADER;
	}
	if (strlen(baseName) > 4 && 
			strcmp(&baseName[strlen(baseName) - 4], "-nph") == 0) {
		cgiFlags |= MPR_CGI_NON_PARSED_HEADER;
	}

	//
	//	Build environment variables
	//
	variables = rq->getVariables();
	numItems = rq->getNumEnvProperties() + 1;

	//
	//	Export the PATH and LD_LIBRARY_PATH also if Unix
	//
#if BLD_HOST_UNIX
	numItems += 2;
#endif
	envv = (char**) mprMalloc((numItems + 1) * sizeof(char*));

	index = 0;
	for (i = 0; i < MA_HTTP_OBJ_MAX; i++) {
		if (variables[i].type == MPR_TYPE_OBJECT) {
			vp = mprGetFirstProperty(&variables[i], MPR_ENUM_DATA);
			while (vp) {
				mprAllocSprintf(&envv[index], MPR_HTTP_MAX_HEADER, "%s=%s", 
					vp->name, vp->string);
				index++;
				vp = mprGetNextProperty(&variables[i], vp, MPR_ENUM_DATA);
			}
		}
	}

#if BLD_HOST_UNIX
{
	char	*cp;
	if ((cp = getenv("PATH")) != 0) {
		mprAllocSprintf(&envv[index++], MPR_MAX_FNAME, "PATH=%s", cp);
	}
	if ((cp = getenv("LD_LIBRARY_PATH")) != 0) {
		mprAllocSprintf(&envv[index++], MPR_MAX_FNAME, "LD_LIBRARY_PATH=%s", cp);
	}
}
#endif
    mprAllocSprintf(&envv[index++], MPR_MAX_FNAME, "REDIRECT_STATUS=302");

	envv[index] = 0;
	mprAssert(index <= numItems);

	mprLog(4, log, "%d: running program: %s\n", rq->getFd(), fileName);

	if (cmd->start(fileName, argv, envv, cgiOutputData, (void*) rq, 
			MPR_CMD_CHDIR) < 0) {
		rq->requestError(503, "Can't run CGI process: %s, URI %s",
			rq->getScriptName(), rq->getOriginalUri());
		rq->finishRequest();
		goto exit;
	}

exit:
	for (i = 0; i < argc; i++) {
		mprFree(argv[i]);
	}
	for (ep = envv; *ep; ep++) {
		mprFree(*ep);
	}
	mprFree(argv);
	mprFree(envv);

	return MPR_HTTP_HANDLER_FINISHED_PROCESSING;
}
示例#11
0
int MprTestSession::setupTests(MprTestResult *result, Mpr *mpr, int argc, 
	char *argv[], char *switches)
{
	char			switchBuf[80];
	char			*programName, *argp;
	int				errflg, c, i, l;
#if BLD_FEATURE_LOG
	char			*logSpec;
#endif

	this->mpr = mpr;
	programName = mprGetBaseName(argv[0]);
	errflg = 0;
#if BLD_FEATURE_LOG
	logSpec = "stdout:1";
	logger = new MprLogToFile();
#endif

	switchBuf[0] = '\0';
	mprStrcat(switchBuf, sizeof(switchBuf), 0, "cDeg:i:l:n:msT:t:v?", 
		switches, (void*) 0);
	MprCmdLine	cmdLine(argc, argv, switchBuf);

	while ((c = cmdLine.next(&argp)) != EOF) {
		switch(c) {
		case 'c':
			result->setContinueOnFailures(1);
			break;

		case 'D':
			mprSetDebugMode(1);
			result->setDebugOnFailures(1);
			break;

		case 'e':
			needEventsThread = 1;
			break;

		case 'g':
			testGroups->parse(argp);
			break;

		case 'i':
			iterations = atoi(argp);
			break;

		case 'l':
#if BLD_FEATURE_LOG
			logSpec = argp;
#endif
			break;

		case 'n':
			l = atoi(argp);
			if (l == 0) {
				sessionLevel = MPR_BASIC;
			} else if (l == 1) {
				sessionLevel = MPR_THOROUGH;
			} else {
				sessionLevel = MPR_DEDICATED;
			}
			break;

		case 'm':
			mprRequestMemStats(1);
			break;

		case 's':
			result->setSingleStep(1);
			break;

		case 't':
			i = atoi(argp);
			if (i <= 0 || i > 100) {
				mprFprintf(MPR_STDERR, "%s: Bad number of threads (0-100)\n", 
					programName);
				exit(2);
			
			}
#if BLD_FEATURE_MULTITHREAD
			numThreads = i;
#endif
			break;

		case 'T':
#if BLD_FEATURE_MULTITHREAD
			poolThreads = atoi(argp);
#endif
			break;

		case 'v':
			verbose++;
			break;

		default:
			//
			//	Ignore args we don't understand
			//
			break;

		case '?':
			errflg++;
			break;
		}
	}
	if (errflg) {
		mprFprintf(MPR_STDERR, 
			"usage: %s [-cDemsv] [-g groups] [-i iterations] "
			"[-l logSpec] [-n testLevel] [-T poolThreads] [-t threads]\n", 
			programName);
		exit(2);
	}

#if !BLD_FEATURE_MULTITHREAD
	needEventsThread = 0;
#endif

#if BLD_FEATURE_LOG
	mpr->addListener(logger);
	mpr->setLogSpec(logSpec);
#endif

	initSignals();

	this->argc = argc;
	this->argv = argv;
	this->firstArg = cmdLine.firstArg();

#if BLD_FEATURE_MULTITHREAD
	mpr->setMaxPoolThreads(poolThreads);
#endif
	if (mpr->start(needEventsThread ? MPR_SERVICE_THREAD : 0) < 0) {
		return MPR_ERR_CANT_INITIALIZE;
	}

	result->adjustThreadCount(numThreads);
	result->setVerbosity(verbose);
	if (result->getListenerCount() == 0) {
		result->addListener(new MprTestListener("__default__"));
	}

	if (verbose) {
		mprFprintf(MPR_STDOUT, 
			"Testing: iterations %d, threads %d, pool %d, service thread %d\n", 
			iterations, numThreads, poolThreads, needEventsThread);
	}

	//
	//	Use current session object for the main thread
	//
	sessions = (MprTestSession**) mprMalloc(sizeof(MprTestSession*) * 
		numThreads);
	sessions[0] = this;
	if (sessions[0]->initializeClasses(result) < 0) {
		exit(3);
	}

#if BLD_FEATURE_MULTITHREAD
	//
	//	Now clone this session object for all other threads
	//
	for (i = 1; i < numThreads; i++) {
		char tName[64];
		sessions[i] = this->newSession();
		sessions[i]->setResult(result);
		sessions[i]->cloneSettings(this);
		mprSprintf(tName, sizeof(tName), "test.%d", i);
	}
#endif
	return 0;
}
示例#12
0
int main(int argc, char *argv[])
{
	char	*password, *passFile, *userName;
	char	*encodedPassword, *argp, *realm;
	char	passBuf[MPR_HTTP_MAX_PASS], buf[MPR_HTTP_MAX_PASS * 2];
	int		c, errflg, create, nextArg;
	bool	enable;

	programName = mprGetBaseName(argv[0]);
	userName = 0;
	create = errflg = 0;
	password = 0;
	enable = 1;

#if BLD_FEATURE_LOG
	MprLogService *ls = new MprLogService();
	ls->addListener(new MprLogToFile());
	ls->setLogSpec("stdout:0");
#endif

	MprCmdLine cmdLine(argc, argv, "cdep:");
	while ((c = cmdLine.next(&argp)) != EOF) {
		switch(c) {
		case 'c':
			create++;
			break;

		case 'e':
			enable = 1;
			break;

		case 'd':
			enable = 0;
			break;

		case 'p':
			password = argp;
			break;

		default:
			errflg++;
			break;
		}
	}
	nextArg = cmdLine.firstArg();
	if ((nextArg + 3) > argc) {
		errflg++;
	}

	if (errflg) {
		printUsage(argv[0]);
		exit(2);
	}	

	passFile = argv[nextArg++];
	realm = argv[nextArg++];
	userName = argv[nextArg++];

	if (!create) {
		if (readPassFile(passFile) < 0) {
			exit(2);
		}
		if (access(passFile, R_OK) != 0) {
			mprError(MPR_L, MPR_USER, "Can't find %s\n", passFile);
			exit(3);
		}
		if (access(passFile, W_OK) < 0) {
			mprError(MPR_L, MPR_USER, "Can't write to %s\n", passFile);
			exit(4);
		}
	} else {
		if (access(passFile, R_OK) == 0) {
			mprError(MPR_L, MPR_USER, "Can't create %s, already exists\n", 
				passFile);
			exit(5);
		}
	}

	if (password == 0) {
		password = getPassword(passBuf, sizeof(passBuf));
		if (password == 0) {
			exit(1);
		}
	}

	mprSprintf(buf, sizeof(buf), "%s:%s:%s", userName, realm, password);
	encodedPassword = maMD5(buf);

	addUser(userName, realm, encodedPassword, enable);

	if (updatePassFile(passFile) < 0) {
		exit(6);
	}
	mprFree(encodedPassword);
	
	return 0;
}