Esempio n. 1
0
// Exec_CrdAction::Execute()
Exec::RetType Exec_CrdAction::Execute(CpptrajState& State, ArgList& argIn) {
# ifdef MPI
  Exec::RetType ret = CpptrajState::OK;
  int err = 0;
  // Create a communicator that just contains the master.
  int ID = MPI_UNDEFINED;
  if (Parallel::TrajComm().IsNull()) {
    if (Parallel::World().Master())
      ID = 0;
  } else if (Parallel::TrajComm().Master())
    ID = Parallel::World().Rank();
  //rprintf("DEBUG: About to create new comm, ID= %i\n", ID);
  trajComm_ = Parallel::World().Split( ID );
  if (ID != MPI_UNDEFINED) {
    mprintf("Warning: '%s' command does not yet use multiple MPI threads.\n", argIn.Command());
    ret = ProcessArgs(State, argIn);
    if (ret != CpptrajState::OK)
      err = 1;
  }
  trajComm_.Reset();
  if (Parallel::World().CheckError( err ))
    ret = CpptrajState::ERR;
  return ret;
# else
  return (ProcessArgs(State, argIn));
# endif
}
Esempio n. 2
0
Error     cmdlineUI::
Init(int32 startup_level)
{
   if ((m_startupLevel = startup_level) == PRIMARY_UI)
   {
    tcgetattr(stdinfd, &::normalTTY);
    :: rawTTY =::normalTTY;
    ::rawTTY.c_lflag &= ~ICANON;
    ::rawTTY.c_lflag &= ~ECHO;
      tcsetattr(stdinfd, TCSANOW, &rawTTY);

      m_propManager = m_context->props;
      m_plm = m_context->plm;
      m_playerEQ = m_context->target;

    keyboardListenThread = Thread::CreateThread();
    keyboardListenThread->Create(cmdlineUI::keyboardServiceFunction, this);

      cout << endl << "Command Line Interface" << endl << endl;
      cout << " * q    Quit" << endl;
      cout << " * +/=  Next Song" << endl;
      cout << " * -    Prev Song" << endl;
      cout << " * p    Pause / UnPause" << endl;
      cout << " * s    Shuffle" << endl << endl;
      cout << " * f    Fast forward 10 seconds" << endl << endl;
      cout << " * b    Skip backwards 10 seconds" << endl << endl;

      m_argc = m_context->argc;
      m_argv = m_context->argv;

      ProcessArgs();
   }
   return kError_NoErr;
}
Esempio n. 3
0
int main(int argc, char *argv[])
{
	if(ProcessArgs(argc,argv)!=kNoArgError) {
		Usage(0);
		exit(0);
	}
	strcpy(gPrevLine,"");	// init the previous line.
	strcpy(srcDigs,"");
	if(gRelocInfo==kTrue) { // need to prime the relocator.
		GetNextCmpAddr();
	}
	while(!feof(gSrcFile)) {	// while not at end of file
		fscanf(gSrcFile,"%s",gSrcLine);
		if(gRelocInfo==kFalse)
			fscanf(gRelocFile,"%s",gCmpLine);
		//printf("%s %s",gSrcLine,gCmpLine);
		if(!AddrCheck(gSrcLine)) {	// good line addr.
			printf("Line in range %d!",line);
			CatCheckSum();
			//fprintf(gDstFile,"%s\n",gPrevLine);
			gSrcLine[strlen(gSrcLine)-2]='\0'; // truncate.
		}
		else {	// we need to process the line.
			ProcessALine(gSrcLine);
			strcpy(gSrcLine,gOutputLine);
		}
		strcpy(gPrevLine,gSrcLine); // update the previous line.
		printf("prev= %s\n",gPrevLine);
		line++;
	}
	FlushLines();
	fclose(gDstFile);
	fclose(gRelocFile);
	fclose(gSrcFile);
}
Esempio n. 4
0
int main(int argc, char** argv)
{
	std::map<std::string, std::string> args = ProcessArgs(argc, argv);

	if (args.size() != 5 || !ValidateArgs(args))
	{
		ShowHelp();
		return -5;
	}

	DesuraId id(args["-i"].c_str(), args["-t"].c_str());

	if (!Login(args["-u"], args["-p"]))
		return -1;

	if (!CreateMcf(id, args["-f"]))
		return -2;

	if (!StartUpload(id))
		return -3;

	if (!UploadMcf())
		return -4;

	return 0;
}
Esempio n. 5
0
int main(int argc, char **argv)
{
    ProcessArgs(argc, argv);
    
    // Allow the ML scripting engine to kill this program. 
    AllowAutoKill ();

    // initialize global variables
    mutex = EnsLockCreate();

    // connect to server
    conn = ens_Init (port);
    if (NULL == conn)
        EnsPanic("Error, could not open connection to server, exiting.");

    // Fixme, we should have a connect call.
    //conn.Connect();

    // Create an endpoint
    Join();

    // start listening to input from Ensemble
    switch (prog) {
    case THROU:
        ThrouMainLoop();
        break;
    case RPC:
        RpcMainLoop();
        break;
    default:
        EnsPanic("You must choose a one of the programs: [rcp|1-n]");
    }
    return 0;
}
Esempio n. 6
0
int main(int argc, char *argv[])
{
  int ret = 0;
  nsresult rv;
  {
    nsCOMPtr<nsIServiceManager> servMan;
    rv = NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
    if (NS_FAILED(rv)) return -1;
    nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
    NS_ASSERTION(registrar, "Null nsIComponentRegistrar");

    /* With no arguments, RegFactory will autoregister */
    if (argc <= 1)
    {
      rv = registrar->AutoRegister(nsnull);
      ret = (NS_FAILED(rv)) ? -1 : 0;
    }
    else
      ret = ProcessArgs(registrar, argc, argv);
  } // this scopes the nsCOMPtrs
  // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
  rv = NS_ShutdownXPCOM( NULL );
  NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");
  return ret;
}
Esempio n. 7
0
int main(int argc, char** argv) {
    int socket;

    int rc;
    uint16_t msg_size = MAX_MSGSIZE;

    char buffer[MAX_MSGSIZE + 1];
    char msg[MAX_MSGSIZE + 1];

#ifdef _WIN32
    WSADATA wsaData;
    rc = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (rc != 0) {
        printf("WSAStartup failed with error: %d\n", rc);
        goto err;
    }	
#endif

    ProcessArgs(argc, argv);
    memset(buffer, 0, MAX_MSGSIZE + 1);
    memset(msg, 0, MAX_MSGSIZE + 1);

    strcpy(msg, "Hello, this is the client!");

    if (bIsServer) {
        socket = announce(OPTRC_FILE);
        if (socket == INVALID_SOCKET) {
            rc = -1;
            goto err;
        }

        rc = recvdata(socket, buffer, &msg_size);
        if (rc == SOCKET_ERROR) {
            goto err;
        }

        printf("%s\n", buffer);
    } else {
        socket = locate(OPTRC_FILE);
        if (socket == INVALID_SOCKET) {
            rc = -1;
            goto err;
        }

        rc = senddata(socket, msg, strlen(msg));
        if (rc == SOCKET_ERROR) {
            goto err;
        }
    }

err:
#ifdef _WIN32
	closesocket(socket);
	WSACleanup();
#else
    close(socket);
#endif
    return rc;
}
Esempio n. 8
0
int __cdecl _tmain (int argc, TCHAR *argv[])
{
    HRESULT result = ProcessArgs(argc, argv);
    if (FAILED(result))
        return result;

    UseImage(QueryContinuously);
    return S_OK;
}
Esempio n. 9
0
int main( int argc, char *argv[] )
{
	OSStatus		err;
	
	debug_initialize( kDebugOutputTypeMetaConsole );
	debug_set_property( kDebugPropertyTagPrintLevel, kDebugLevelVerbose );
	
	err = ProcessArgs( argc, argv );
	return( (int) err );
}
/*
 *  ======== main ========
 */
int main(int argc, char **argv)
{
	INT nStrmMode = 0;
	FILE *inFile = NULL;	/* Input file handle. */
	FILE *outFile = NULL;	/* Output file handle. */
	struct STRMCOPY_TASK strmcopyTask;
	int status = 0;

	DspManager_Open(argc, NULL);

	/* Process command line arguments, open data files: */
	status = ProcessArgs(argc, argv, &inFile, &outFile, &nStrmMode);
	strmcopyTask.hProcessor = NULL;
	strmcopyTask.hNode = NULL;
	strmcopyTask.hInStream = NULL;
	strmcopyTask.hOutStream = NULL;
	strmcopyTask.ppInBufs = NULL;
	strmcopyTask.ppOutBufs = NULL;
	strmcopyTask.nStrmMode = nStrmMode;
	if (DSP_SUCCEEDED(status)) {
		/* Perform processor level initialization. */
		status = InitializeProcessor(&strmcopyTask);
	}
	if (DSP_SUCCEEDED(status)) {
		/* Perform node level initialization. */
		status = InitializeNode(&strmcopyTask);
		if (DSP_SUCCEEDED(status)) {
			/* Perform stream level initialization. */
			status = InitializeStreams(&strmcopyTask);
			if (DSP_SUCCEEDED(status)) {
				/* Run task. */
				status = RunTask(&strmcopyTask, inFile, outFile);
				if (DSP_SUCCEEDED(status)) {
					fprintf(stdout, "RunTask succeeded.\n");
				} else {
					fprintf(stdout, "RunTask failed.\n");
				}
			}
		}
	}
	/* Close opened files. */
	if (inFile) {
		fclose(inFile);
	}
	if (outFile) {
		fclose(outFile);
	}
	CleanupStreams(&strmcopyTask);
	CleanupNode(&strmcopyTask);
	CleanupProcessor(&strmcopyTask);
	DspManager_Close(0, NULL);
	/*printf("Hit enter to exit:  ");
	   (void)getchar(); */
	return (DSP_SUCCEEDED(status) ? 0 : -1);
}
Esempio n. 11
0
static DNSStatus	ProcessPreset( int inPreset )
{
    DNSStatus		err;

    require_action_string( ( inPreset > 0 ) && ( inPreset <= gPresetsCount ), exit, err = kDNSBadParamErr, "invalid preset" );

    err = ProcessArgs( gPresets[ inPreset - 1 ].argc, (char **) gPresets[ inPreset - 1 ].argv );

exit:
    return( err );
}
Esempio n. 12
0
/* --------------------------------------------------------------------- */
int main(int argc, char *argv[])
{
  int	n;
  Arg	args[6];

  Initialize();
  ProcessArgs(argv);
  ReadConfigFile();

  AutoScale();

  if (!Interactive)
    PrintPS((Widget)NULL, (XtPointer)NULL, (XtPointer)NULL);
  else
    {
    AppShell = XtAppInitialize(&appContext, APP_CLASS, NULL, 0, &argc, argv,
                                fallback_resources, NULL, 0);

    XtGetApplicationResources(AppShell, (caddr_t) &iv, resources,
                                XtNumber(resources), NULL, 0);

    n = 0;
    MainShell = XtCreatePopupShell("topLevelShell",
                                topLevelShellWidgetClass, AppShell, args, n);

    MainWindow = CreateMainWindow(MainShell);

    n = 0;
    ControlShell = XtCreatePopupShell("controlShell",
                                topLevelShellWidgetClass, AppShell, args, n);

    CreateControlWindow(ControlShell);

    CreateErrorBox(AppShell);
    CreateQueryBox(AppShell);
    CreateWarningBox(AppShell);
    CreateFileSelectionBox(AppShell);

    if (NumberDataFiles > 0)
      NewDataFile((Widget)NULL, (XtPointer)NULL, (XtPointer)NULL);

    OpenControlWindow(NULL, NULL, NULL);
    XtManageChild(MainWindow);
    XtPopup(XtParent(MainWindow), XtGrabNone);

    if (RealTime)
      XtAppAddTimeOut(appContext, 1000, UpdateDataRT, NULL);

    XtAppMainLoop(appContext);
    }

  return(0);

}	/* END MAIN */
Esempio n. 13
0
/*
 *  ======== main ========
 */
int
main(int argc, char **argv)
{
	struct SCALE_TASK scaleTask;
	int status = 0;

	status = (DBAPI)DspManager_Open(0, NULL);

	if (DSP_FAILED(status)) {
		printf("\nFATAL ERROR: Bridge Initialisation FAILED\n");
		return 0;
	}

	status = ProcessArgs(argc, argv, &scaleTask);

	/* initialize context object */
	scaleTask.hProcessor = NULL;
	scaleTask.hNode = NULL;
	scaleTask.hInStream = NULL;
	scaleTask.hOutStream = NULL;
	scaleTask.pInBuf = NULL;
	scaleTask.pOutBuf = NULL;

	if (DSP_SUCCEEDED(status)) {
		/* do processor level initialization */
		status = InitializeProcessor(&scaleTask);
		if (DSP_SUCCEEDED(status)) {
			/* do node level initialization */
			status = InitializeNode(&scaleTask);
			if (DSP_SUCCEEDED(status)) {
				/* do stream level initialization */
				status = InitializeStreams(&scaleTask);
				if (DSP_SUCCEEDED(status)) {
					/* do processing */
					status = RunTask(&scaleTask);
					if (DSP_SUCCEEDED(status)) {
						fprintf(stdout, "\nRunTask succeeded.\n");
					} else {
						fprintf(stdout, "\nRunTask failed.\n");
					}
				}
			}
		}
	}
	CleanupStreams(&scaleTask);
	CleanupNode(&scaleTask);
	CleanupProcessor(&scaleTask);
	status = DspManager_Close(0, NULL);
	if (DSP_FAILED(status)) {
		printf("\nERROR: Bridge Close FAILED\n");
	}
	return (DSP_SUCCEEDED(status) ? 0 : -1);
}
Esempio n. 14
0
int main(int argc, char **argv) {
	// Process args
	ProcessArgs(argc, argv);

	if (strlen(Commands)) read_from_stdin = 0;

	// if user does not specify a --login, --logout or --attach action, he wants a --login --logout combination
	if (!login && !logout && !attach) login = logout = 1;

	if (attach && !logout) {
	} else if (login && logout) {
	} else {
		// no commands allowed when only logging in or out
		Commands[0] = 0;
		read_from_stdin = 0;
	}

	if (login) {
		int exit = 0;

		if (!strlen(Exchanges)) {
			printf("EXCHANGES NOT SPECIFIED!\n");
			exit = 1;
		}
		if (!strlen(Username)) {
			printf("USERNAME NOT SPECIFIED!\n");
			exit = 1;
		}
		if (!strlen(Password)) {
			printf("PASSWORD NOT SPECIFIED!\n");
			exit = 1;
		}

		if (exit) Done(0);
	}

	timeout_denominator = common_denominator(login_timeout, command_timeout);

	if (*HostPortStr && *HostPortStr != '0') HostPort = atoi(HostPortStr);

	// Attach to ewrecv
	if (connection != (void *)1) {
		AttachConnection();
	} else {
		connection = NULL;
	}

	Init();
	MainProc();
	Done(0);

	return 0;
}
Esempio n. 15
0
int
main (
  int   Argc,
  char  *Argv[]
  )
/*++

Routine Description:

  Call the routine to parse the command-line options, then process the file.

Arguments:

  Standard C main() argc and argv.

Returns:

  0       if successful
  nonzero otherwise

--*/
{
  STATUS  Status;

  //
  // Set the utility name for error reporting purposes
  //
  SetUtilityName (UTILITY_NAME);

  //
  // Process the command-line arguments
  //
  Status = ProcessArgs (Argc, Argv);
  if (Status != STATUS_SUCCESS) {
    return Status;
  }

  //
  // Switch based on args
  //
  if (mGlobals.Mode & MODE_CREATE_HII_RESOURCE_FILE) {
    CreateResourceScript (mGlobals.ResourceFileName, &mGlobals.Guid, mGlobals.PackageFile);
  }

  if (mGlobals.Mode & MODE_CREATE_HII_PACKAGE_LIST) {
    CreatePackageList (mGlobals.PackageListFileName, &mGlobals.Guid, mGlobals.PackageFile);
  }

  FreeGlobals ();

  return GetUtilityStatus ();
}
int
main(int argc, char *argv[])
{
	int numCycles = 128;
	JobScheduler::Policy policy = JobScheduler::Policy::RawDemand;

	ProcessArgs(argc, argv);

	std::cout << "Running miniMesos simulator for " << NumCycles << std::endl;
	TimeWheel mesoWheel(SchedulerPolicy, NumCycles, Verbosity);

	mesoWheel.Simulate();
}
Esempio n. 17
0
File: acc.c Progetto: Edward850/acc
static void Init(void)
{
	short endianTest = 1;

	if (*(char *)&endianTest)
		acs_BigEndianHost = NO;
	else
		acs_BigEndianHost = YES;
	acs_VerboseMode = YES;
	acs_DebugMode = NO;
	acs_DebugFile = NULL;
	TK_Init();
	SY_Init();
	STR_Init();
	ProcessArgs();
	MS_Message(MSG_NORMAL, "Host byte order: %s endian\n",
		acs_BigEndianHost ? "BIG" : "LITTLE");
}
Esempio n. 18
0
int main(int argc, char **argv)
{
    int WaitCount = 0;

    // Process the command line arguments
    ProcessArgs(argc, argv);

    // Request the camera settings packet
    MakeOrionPacket(&PktOut, getOrionCamerasPacketID(), 0);
    OrionCommSend(&PktOut);

    // Wait for confirmation from the gimbal, or 5 seconds - whichever comes first
    while ((++WaitCount < 50) && (ProcessData() == FALSE)) usleep(100000);

    // If we timed out waiting, tell the user and return an error code
    if (WaitCount >= 50) KillProcess("Gimbal failed to respond", -1);

    // Done
    return 0;

}// main
Esempio n. 19
0
int main( int argc, char* argv[] )
{
    DNSStatus		err;

    // Set up DNS Services and install a Console Control Handler to handle things like control-c signals.

    err = DNSServicesInitialize( kDNSFlagAdvertise, 0 );
    require_noerr_string( err, exit, "could not initialize DNSServiceTest" );

#if( __MACH__ )
    signal( SIGINT, SigIntHandler );
#endif

#if( defined( WINVER ) )
    SetConsoleCtrlHandler( ConsoleControlHandler, TRUE );
#endif

    ProcessArgs( argc, argv );

exit:
    DNSServicesFinalize();
    return( err );
}
Esempio n. 20
0
File: wcpc.cpp Progetto: funagi/wcpc
int wmain(int argc, wchar_t* argv[])
{
    SendMessageW( // 设置窗口图标, Just for entertainment
        GetConsoleWindow(), 
        WM_SETICON, 
        ICON_SMALL, 
        (LPARAM)LoadIconW(GetModuleHandleW(NULL), MAKEINTRESOURCEW(IDI_ICON1))
        );

    try {
        ProcessArgs(argc, argv); // 处理命令行参数

        ProcConversion(); // 执行转码

        return 0;
    } catch(const int& e) {
        return e; // 有了资源文件这里就简化了
    } catch(std::bad_alloc&) { // 简单捕捉内存分配问题
        PrintMessage.PrintIt(stderr, IDS_MEMORY_ALLOC_ERROR_STR, Args.getImportFile());
        throw EC_MEMORY_ALLOC_ERROR;
    } catch(...) {
        return EC_UNKNOWN_ERROR;
    }
}
Esempio n. 21
0
int main(int argc, char *argv[])
{
  void *cvode_mem;
  UserData data;
  realtype t, tout;
  N_Vector y;
  int iout, flag, nthreads, nnz;

  realtype pbar[NS];
  int is; 
  N_Vector *yS;
  booleantype sensi, err_con;
  int sensi_meth;

  cvode_mem = NULL;
  data      = NULL;
  y         =  NULL;
  yS        = NULL;

  /* Process arguments */
  ProcessArgs(argc, argv, &sensi, &sensi_meth, &err_con);

  /* User data structure */
  data = (UserData) malloc(sizeof *data);
  if (check_flag((void *)data, "malloc", 2)) return(1);
  data->p[0] = RCONST(0.04);
  data->p[1] = RCONST(1.0e4);
  data->p[2] = RCONST(3.0e7);

  /* Initial conditions */
  y = N_VNew_Serial(NEQ);
  if (check_flag((void *)y, "N_VNew_Serial", 0)) return(1);

  Ith(y,1) = Y1;
  Ith(y,2) = Y2;
  Ith(y,3) = Y3;

  /* Call CVodeCreate to create the solver memory and specify the 
     Backward Differentiation Formula and the use of a Newton iteration */
  cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);
  if (check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(1);

  /* Call CVodeInit to initialize the integrator memory and specify the
     user's right hand side function in y'=f(t,y), the initial time T0, and
     the initial dependent variable vector y. */
  flag = CVodeInit(cvode_mem, f, T0, y);
  if (check_flag(&flag, "CVodeInit", 1)) return(1);

  /* Call CVodeWFtolerances to specify a user-supplied function ewt that sets
     the multiplicative error weights W_i for use in the weighted RMS norm */
  flag = CVodeWFtolerances(cvode_mem, ewt);
  if (check_flag(&flag, "CVodeSetEwtFn", 1)) return(1);

  /* Attach user data */
  flag = CVodeSetUserData(cvode_mem, data);
  if (check_flag(&flag, "CVodeSetUserData", 1)) return(1);

  /* Call CVKLU to specify the CVKLU sparse direct linear solver */
  nthreads = 1;                 /* no. of threads to use when factoring the system*/
  nnz = NEQ * NEQ;              /* max no. of nonzeros entries in the Jac */
  flag = CVSuperLUMT(cvode_mem, nthreads, NEQ, nnz);
  if (check_flag(&flag, "CVSuperLUMT", 1)) return(1);

  /* Set the Jacobian routine to Jac (user-supplied) */
  flag = CVSlsSetSparseJacFn(cvode_mem, Jac);
  if (check_flag(&flag, "CVSlsSetSparseJacFn", 1)) return(1);

  printf("\n3-species chemical kinetics problem\n");

  /* Sensitivity-related settings */
  if (sensi) {

    /* Set parameter scaling factor */
    pbar[0] = data->p[0];
    pbar[1] = data->p[1];
    pbar[2] = data->p[2];

    /* Set sensitivity initial conditions */
    yS = N_VCloneVectorArray_Serial(NS, y);
    if (check_flag((void *)yS, "N_VCloneVectorArray_Serial", 0)) return(1);
    for (is=0;is<NS;is++) N_VConst(ZERO, yS[is]);

    /* Call CVodeSensInit1 to activate forward sensitivity computations
       and allocate internal memory for COVEDS related to sensitivity
       calculations. Computes the right-hand sides of the sensitivity
       ODE, one at a time */
    flag = CVodeSensInit1(cvode_mem, NS, sensi_meth, fS, yS);
    if(check_flag(&flag, "CVodeSensInit", 1)) return(1);

    /* Call CVodeSensEEtolerances to estimate tolerances for sensitivity 
       variables based on the rolerances supplied for states variables and 
       the scaling factor pbar */
    flag = CVodeSensEEtolerances(cvode_mem);
    if(check_flag(&flag, "CVodeSensEEtolerances", 1)) return(1);

    /* Set sensitivity analysis optional inputs */
    /* Call CVodeSetSensErrCon to specify the error control strategy for 
       sensitivity variables */
    flag = CVodeSetSensErrCon(cvode_mem, err_con);
    if (check_flag(&flag, "CVodeSetSensErrCon", 1)) return(1);

    /* Call CVodeSetSensParams to specify problem parameter information for 
       sensitivity calculations */
    flag = CVodeSetSensParams(cvode_mem, NULL, pbar, NULL);
    if (check_flag(&flag, "CVodeSetSensParams", 1)) return(1);

    printf("Sensitivity: YES ");
    if(sensi_meth == CV_SIMULTANEOUS)   
      printf("( SIMULTANEOUS +");
    else 
      if(sensi_meth == CV_STAGGERED) printf("( STAGGERED +");
      else                           printf("( STAGGERED1 +");   
    if(err_con) printf(" FULL ERROR CONTROL )");
    else        printf(" PARTIAL ERROR CONTROL )");

  } else {

    printf("Sensitivity: NO ");

  }
  
  /* In loop over output points, call CVode, print results, test for error */
  
  printf("\n\n");
  printf("===========================================");
  printf("============================\n");
  printf("     T     Q       H      NST           y1");
  printf("           y2           y3    \n");
  printf("===========================================");
  printf("============================\n");

  for (iout=1, tout=T1; iout <= NOUT; iout++, tout *= TMULT) {

    flag = CVode(cvode_mem, tout, y, &t, CV_NORMAL);
    if (check_flag(&flag, "CVode", 1)) break;

    PrintOutput(cvode_mem, t, y);

    /* Call CVodeGetSens to get the sensitivity solution vector after a
       successful return from CVode */
    if (sensi) {
      flag = CVodeGetSens(cvode_mem, &t, yS);
      if (check_flag(&flag, "CVodeGetSens", 1)) break;
      PrintOutputS(yS);
    } 
    printf("-----------------------------------------");
    printf("------------------------------\n");

  }

  /* Print final statistics */
  PrintFinalStats(cvode_mem, sensi);

  /* Free memory */

  N_VDestroy_Serial(y);                    /* Free y vector */
  if (sensi) {
    N_VDestroyVectorArray_Serial(yS, NS);  /* Free yS vector */
  }
  free(data);                              /* Free user data */
  CVodeFree(&cvode_mem);                   /* Free CVODES memory */

  return(0);
}
Esempio n. 22
0
int
main(int argc, char **argv)
{
  char *name;
  const char *lastlabel;
  int arg, f, holdfd[3], label;
  struct bundle *bundle;
  struct prompt *prompt;
  struct switches sw;

  probe_Init();

  /*
   * We open 3 descriptors to ensure that STDIN_FILENO, STDOUT_FILENO and
   * STDERR_FILENO are always open.  These are closed before DoLoop(),
   * but *after* we've avoided the possibility of erroneously closing
   * an important descriptor with close(STD{IN,OUT,ERR}_FILENO).
   */
  if ((holdfd[0] = open(_PATH_DEVNULL, O_RDWR)) == -1) {
    fprintf(stderr, "Cannot open %s !\n", _PATH_DEVNULL);
    return 2;
  }
  for (f = 1; f < sizeof holdfd / sizeof *holdfd; f++)
    holdfd[f] = dup(holdfd[0]);

  name = strrchr(argv[0], '/');
  log_Open(name ? name + 1 : argv[0]);

#ifndef NONAT
  PacketAliasInit();
#endif
  label = ProcessArgs(argc, argv, &sw);

  /*
   * A FreeBSD & OpenBSD hack to dodge a bug in the tty driver that drops
   * output occasionally.... I must find the real reason some time.  To
   * display the dodgy behaviour, comment out this bit, make yourself a large
   * routing table and then run ppp in interactive mode.  The `show route'
   * command will drop chunks of data !!!
   */
  if (sw.mode == PHYS_INTERACTIVE) {
    close(STDIN_FILENO);
    if (open(_PATH_TTY, O_RDONLY) != STDIN_FILENO) {
      fprintf(stderr, "Cannot open %s for input !\n", _PATH_TTY);
      return 2;
    }
  }

  /* Allow output for the moment (except in direct mode) */
  if (sw.mode == PHYS_DIRECT)
    prompt = NULL;
  else
    SignalPrompt = prompt = prompt_Create(NULL, NULL, PROMPT_STD);

  ID0init();
  if (ID0realuid() != 0) {
    char conf[200], *ptr;

    snprintf(conf, sizeof conf, "%s/%s", PPP_CONFDIR, CONFFILE);
    do {
      struct stat sb;

      if (stat(conf, &sb) == 0 && sb.st_mode & S_IWOTH) {
        log_Printf(LogALERT, "ppp: Access violation: Please protect %s\n",
                   conf);
        return -1;
      }
      ptr = conf + strlen(conf)-2;
      while (ptr > conf && *ptr != '/')
        *ptr-- = '\0';
    } while (ptr >= conf);
  }

  if (label < argc)
    for (arg = label; arg < argc; arg++)
      CheckLabel(argv[arg], prompt, sw.mode);
  else
    CheckLabel("default", prompt, sw.mode);

  if (!sw.quiet)
    prompt_Printf(prompt, "Working in %s mode\n", mode2Nam(sw.mode));

  if ((bundle = bundle_Create(TUN_PREFIX, sw.mode, sw.unit)) == NULL)
    return EX_START;

  /* NOTE:  We may now have changed argv[1] via a ``set proctitle'' */

  if (prompt) {
    prompt->bundle = bundle;	/* couldn't do it earlier */
    if (!sw.quiet)
      prompt_Printf(prompt, "Using interface: %s\n", bundle->iface->name);
  }
  SignalBundle = bundle;
  bundle->NatEnabled = sw.nat;
  if (sw.nat)
    opt_enable(bundle, OPT_IFACEALIAS);

  if (system_Select(bundle, "default", CONFFILE, prompt, NULL) < 0)
    prompt_Printf(prompt, "Warning: No default entry found in config file.\n");

  sig_signal(SIGHUP, CloseSession);
  sig_signal(SIGTERM, CloseSession);
  sig_signal(SIGINT, CloseConnection);
  sig_signal(SIGQUIT, CloseSession);
  sig_signal(SIGALRM, SIG_IGN);
  signal(SIGPIPE, SIG_IGN);

  if (sw.mode == PHYS_INTERACTIVE)
    sig_signal(SIGTSTP, TerminalStop);

  sig_signal(SIGUSR1, RestartServer);
  sig_signal(SIGUSR2, BringDownServer);

  lastlabel = argv[argc - 1];
  for (arg = label; arg < argc; arg++) {
    /* In case we use LABEL or ``set enddisc label'' */
    bundle_SetLabel(bundle, lastlabel);
    system_Select(bundle, argv[arg], CONFFILE, prompt, NULL);
  }

  if (label < argc)
    /* In case the last label did a ``load'' */
    bundle_SetLabel(bundle, lastlabel);

  if (sw.mode == PHYS_AUTO &&
      ncprange_family(&bundle->ncp.ipcp.cfg.peer_range) == AF_UNSPEC) {
    prompt_Printf(prompt, "You must ``set ifaddr'' with a peer address "
                  "in auto mode.\n");
    AbortProgram(EX_START);
  }

  if (sw.mode != PHYS_INTERACTIVE) {
    if (sw.mode != PHYS_DIRECT) {
      if (!sw.fg) {
        int bgpipe[2];
        pid_t bgpid;

        if (sw.mode == PHYS_BACKGROUND && pipe(bgpipe)) {
          log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
	  AbortProgram(EX_SOCK);
        }

        bgpid = fork();
        if (bgpid == -1) {
	  log_Printf(LogERROR, "fork: %s\n", strerror(errno));
	  AbortProgram(EX_SOCK);
        }

        if (bgpid) {
	  char c = EX_NORMAL;
          int ret;

	  if (sw.mode == PHYS_BACKGROUND) {
	    close(bgpipe[1]);
	    BGPid = bgpid;
            /* If we get a signal, kill the child */
            signal(SIGHUP, KillChild);
            signal(SIGTERM, KillChild);
            signal(SIGINT, KillChild);
            signal(SIGQUIT, KillChild);

	    /* Wait for our child to close its pipe before we exit */
            while ((ret = read(bgpipe[0], &c, 1)) == 1) {
              switch (c) {
                case EX_NORMAL:
                  if (!sw.quiet) {
	            prompt_Printf(prompt, "PPP enabled\n");
	            log_Printf(LogPHASE, "Parent: PPP enabled\n");
                  }
	          break;
                case EX_REDIAL:
                  if (!sw.quiet)
	            prompt_Printf(prompt, "Attempting redial\n");
                  continue;
                case EX_RECONNECT:
                  if (!sw.quiet)
	            prompt_Printf(prompt, "Attempting reconnect\n");
                  continue;
	        default:
	          prompt_Printf(prompt, "Child failed (%s)\n",
                                ex_desc((int)c));
	          log_Printf(LogPHASE, "Parent: Child failed (%s)\n",
		             ex_desc((int) c));
	      }
	      break;
            }
            if (ret != 1) {
	      prompt_Printf(prompt, "Child exit, no status.\n");
	      log_Printf(LogPHASE, "Parent: Child exit, no status.\n");
	    }
	    close(bgpipe[0]);
	  }
	  return c;
        } else if (sw.mode == PHYS_BACKGROUND) {
	  close(bgpipe[0]);
          bundle->notify.fd = bgpipe[1];
        }

        bundle_ChangedPID(bundle);
        bundle_LockTun(bundle);	/* we have a new pid */
      }

      /* -auto, -dedicated, -ddial, -foreground & -background */
      prompt_Destroy(prompt, 0);
      close(STDOUT_FILENO);
      close(STDERR_FILENO);
      close(STDIN_FILENO);
      if (!sw.fg)
        setsid();
    } else {
      /* -direct - STDIN_FILENO gets used by physical_Open */
      prompt_TtyInit(NULL);
      close(STDOUT_FILENO);
      close(STDERR_FILENO);
    }
  } else {
    /* -interactive */
    close(STDERR_FILENO);
    prompt_TtyInit(prompt);
    prompt_TtyCommandMode(prompt);
    prompt_Required(prompt);
  }

  /* We can get rid of these now */
  for (f = 0; f < sizeof holdfd / sizeof *holdfd; f++)
    close(holdfd[f]);

  log_Printf(LogPHASE, "PPP Started (%s mode).\n", mode2Nam(sw.mode));
  DoLoop(bundle);
  AbortProgram(EX_NORMAL);

  return EX_NORMAL;
}
Esempio n. 23
0
// Program's main thread of execution.
// ----------------------------------------------------------- 
int main(int argc,     // Number of strings in array argv.
	 char *argv[]) // Array of command-line argument 
// NOTE: None of the MSVC compilers will expand wildcard characters
// used in command-line arguments unless linked with the setargv.obj
// library. All the UNIX compliers will expand wildcard characters
// by default.
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  // If no arguments are given print usage message to the screen 
  if(argc < 2) {
    HelpMessage(ProgramName, AS2HTMVersionNumber);
    return 0;
  }

  // Process command ling arguments and files 
  int narg;
  char *arg = argv[narg = 1];
  while (narg < argc) {
    if (arg[0] != '\0') {
      if (arg[0] == '-') { // Look for command line arguments
	if(!ProcessArgs(arg)) return 0; // Exit if argument is not valid
      }
      else { 
	if(futils_isdirectory((const char *)arg)) {
	  // Do not process directories
	  arg = argv[++narg];
	  continue;
	}
	open_file = arg; // Update the open file name pointer
	DiskFileB infile(open_file);
	if(!infile) {
	  GXSTD::cerr << "\n";
	  GXSTD::cerr << "Cannot open file: " << open_file << "\n";
	  GXSTD::cerr << "Exiting..." << "\n";
	  GXSTD::cerr << "\n";
	  return 0;
	}
	num_files++;

	// Process the test file
	if(write_to_file) {
	  if(use_html_ext)
	    GenOutputFileName(".html");
	  else
	    GenOutputFileName(".htm");
	  // Using the ostream classes allows the data to be written
	  // to a file, the stdout, or stderr.
	  GXSTD::fstream outfile(out_file, GXSTD::ios::out|GXSTD::ios::trunc);
	  if(!outfile) {
	    GXSTD::cerr << "\n";
	    GXSTD::cerr << "Cannot write to: " << out_file << "\n";
	    GXSTD::cerr << "Exiting..." << "\n";
	    GXSTD::cerr << "\n";
	    return 0;
	  }
	  ProcessTextFile(infile, outfile); // Write to file
	}
	else 
	  ProcessTextFile(infile, GXSTD::cout); // Write to stdout
      }
      arg = argv[++narg];
    }
  }
  
  if(num_files == 0) {
    GXSTD::cerr << "\n";
    GXSTD::cerr << "You must enter a file name." << "\n";
    GXSTD::cerr << "Exiting..." << "\n";
    GXSTD::cerr << "\n";
    return 0;
  }
  
  return 0;
}
Esempio n. 24
0
int main(int argc, char *argv[])
{
  void *cvode_mem;
  UserData data;
  realtype t, tout;
  N_Vector y;
  int iout, flag;

  realtype pbar[NS];
  int is; 
  N_Vector *yS;
  booleantype sensi, err_con;
  int sensi_meth;

  cvode_mem = NULL;
  data      = NULL;
  y         =  NULL;
  yS        = NULL;

  /* Process arguments */
  ProcessArgs(argc, argv, &sensi, &sensi_meth, &err_con);

  /* User data structure */
  data = (UserData) malloc(sizeof *data);
  if (check_flag((void *)data, "malloc", 2)) return(1);
  data->p[0] = RCONST(0.04);
  data->p[1] = RCONST(1.0e4);
  data->p[2] = RCONST(3.0e7);

  /* Initial conditions */
  y = N_VNew_Serial(NEQ);
  if (check_flag((void *)y, "N_VNew_Serial", 0)) return(1);

  Ith(y,1) = Y1;
  Ith(y,2) = Y2;
  Ith(y,3) = Y3;

  /* Create CVODES object */
  cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);
  if (check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(1);

  /* Allocate space for CVODES */
  flag = CVodeMalloc(cvode_mem, f, T0, y, CV_WF, 0.0, NULL);
  if (check_flag(&flag, "CVodeMalloc", 1)) return(1);

  /* Use private function to compute error weights */
  flag = CVodeSetEwtFn(cvode_mem, ewt, NULL);
  if (check_flag(&flag, "CVodeSetEwtFn", 1)) return(1);

  /* Attach user data */
  flag = CVodeSetFdata(cvode_mem, data);
  if (check_flag(&flag, "CVodeSetFdata", 1)) return(1);

  /* Attach linear solver */
  flag = CVDense(cvode_mem, NEQ);
  if (check_flag(&flag, "CVDense", 1)) return(1);

  flag = CVDenseSetJacFn(cvode_mem, Jac, data);
  if (check_flag(&flag, "CVDenseSetJacFn", 1)) return(1);

  printf("\n3-species chemical kinetics problem\n");

  /* Sensitivity-related settings */
  if (sensi) {

    pbar[0] = data->p[0];
    pbar[1] = data->p[1];
    pbar[2] = data->p[2];

    yS = N_VNewVectorArray_Serial(NS, NEQ);
    if (check_flag((void *)yS, "N_VNewVectorArray_Serial", 0)) return(1);
    for (is=0;is<NS;is++) N_VConst(ZERO, yS[is]);

    flag = CVodeSensMalloc(cvode_mem, NS, sensi_meth, yS);
    if(check_flag(&flag, "CVodeSensMalloc", 1)) return(1);

    flag = CVodeSetSensRhs1Fn(cvode_mem, fS);
    if (check_flag(&flag, "CVodeSetSensRhs1Fn", 1)) return(1);
    flag = CVodeSetSensErrCon(cvode_mem, err_con);
    if (check_flag(&flag, "CVodeSetSensFdata", 1)) return(1);
    flag = CVodeSetSensFdata(cvode_mem, data);
    if (check_flag(&flag, "CVodeSetSensFdata", 1)) return(1);
    flag = CVodeSetSensParams(cvode_mem, NULL, pbar, NULL);
    if (check_flag(&flag, "CVodeSetSensParams", 1)) return(1);

    printf("Sensitivity: YES ");
    if(sensi_meth == CV_SIMULTANEOUS)   
      printf("( SIMULTANEOUS +");
    else 
      if(sensi_meth == CV_STAGGERED) printf("( STAGGERED +");
      else                           printf("( STAGGERED1 +");   
    if(err_con) printf(" FULL ERROR CONTROL )");
    else        printf(" PARTIAL ERROR CONTROL )");

  } else {

    printf("Sensitivity: NO ");

  }
  
  /* In loop over output points, call CVode, print results, test for error */
  
  printf("\n\n");
  printf("===================================================");
  printf("============================\n");
  printf("     T     Q       H      NST                    y1");
  printf("           y2           y3    \n");
  printf("===================================================");
  printf("============================\n");

  for (iout=1, tout=T1; iout <= NOUT; iout++, tout *= TMULT) {

    flag = CVode(cvode_mem, tout, y, &t, CV_NORMAL);
    if (check_flag(&flag, "CVode", 1)) break;

    PrintOutput(cvode_mem, t, y);

    if (sensi) {
      flag = CVodeGetSens(cvode_mem, t, yS);
      if (check_flag(&flag, "CVodeGetSens", 1)) break;
      PrintOutputS(yS);
    } 
    printf("-------------------------------------------------");
    printf("------------------------------\n");

  }

  /* Print final statistics */
  PrintFinalStats(cvode_mem, sensi);

  /* Free memory */

  N_VDestroy_Serial(y);                    /* Free y vector */
  if (sensi) {
    N_VDestroyVectorArray_Serial(yS, NS);  /* Free yS vector */
  }
  free(data);                              /* Free user data */
  CVodeFree(cvode_mem);                    /* Free CVODES memory */

  return(0);
}
Esempio n. 25
0
s32 ProcessWC24(int dlnow)
{
	s32 retval;
	u32 entry_bitmask = 0xf;
	FILE *fdol = NULL, *fver = NULL, *fconfig = NULL;
	int i;
	char *configbuf;
	char *updateinfobuf;
	char *configlines[0x10];
	char *updateinfolines[0x10];
	struct stat dolstats;
	u32 consoleID;
	int dlfreq;
	char **argv;
	#ifdef LAN
	dlfreq = 1;//Set dl frequency to every 2 minutes for LAN, hourly for Internet.
	#else
	dlfreq = 0x3c;
	#endif
	if(dlnow)entry_bitmask = 0xf;

	retval = WC24_CreateWC24DlVFF(0x200000, 0);//2MB
	if(retval<0 && retval!=-105)//Return when VFF creation fails, except when the VFF already exists.
	{
		printf("WC24_CreateWC24DlVFF returned %d\n", retval);
		return retval;
	}
	
	retval = WC24_MountWC24DlVFF();
	if(retval<0)
	{
		printf("WC24_MountWC24DlVFF returned %d\n", retval);
		return retval;
	}
	
	printf("mkdir...\n");
	mkdir("wc24dl.vff:/wc24boottitle", 777);
	printf("done.\n");
	VFF_Unmount("wc24dl.vff");

	retval = ES_GetDeviceID(&consoleID);
	if(retval<0)
	{
		printf("ES_GetDeviceID returned %d\n", retval);
	}
	memset(url_id, 0, 256);
	snprintf(url_id, 255, ".php?cid=%08x", consoleID);

	memset(url, 0, 256);
	snprintf(url, 255, "%swc24boottitle/installer.dol%s", SRVR_BASEURL, url_id);//See the README for note on retrieving server scripts source.
	retval = WC24_FindEntry((u32)curtitleid, "installer.dol", &myent, 1);
	if(retval>=0)
	{
		if(strncmp(myent.url, url, 0xec))
		{
			WC24_DeleteRecord(retval);
			retval = LIBWC24_ENOENT;
		}
		else
		{
			retval = -1;
		}
	}

	if(retval==LIBWC24_ENOENT)//Only create the entry when it doesn't exist. When there's an entry with "installer.dol" for the URL filename but the whole URL doesn't match the one we're going to install, that entry is deleted then we create a new one.
	{
		printf("Creating record+entry for wc24boottitle auto-update installer...\n");
		retval = WC24_CreateRecord(&myrec, &myent, WC24ID, 0, 0x4842, WC24_TYPE_TITLEDATA, WC24_RECORD_FLAGS_DEFAULT, WC24_FLAGS_HB, dlfreq, 0x5a0, 0, url, VFFPATH "installer.dol");
		if(retval<0)
		{
			printf("WC24_CreateRecord returned %d\n", retval);
			VFF_Unmount("wc24dl.vff");
			return retval;
		}
		entry_bitmask |= BIT(0);
	}

	memset(url, 0, 256);
	snprintf(url, 255, "%swc24boottitle/verinfo%s", SRVR_BASEURL, url_id);
	retval = WC24_FindEntry((u32)curtitleid, "verinfo", &myent, 1);
	if(retval>=0)
	{
		if(strncmp(myent.url, url, 0xec))
		{
			WC24_DeleteRecord(retval);
			retval = LIBWC24_ENOENT;
		}
		else
		{
			retval = -1;
		}
	}

	if(retval==LIBWC24_ENOENT)
	{
		printf("Creating record+entry for wc24boottitle auto-update version info...\n");
		retval = WC24_CreateRecord(&myrec, &myent, WC24ID, 0, 0x4842, WC24_TYPE_TITLEDATA, WC24_RECORD_FLAGS_DEFAULT, WC24_FLAGS_HB, dlfreq, 0x5a0, 0, url, VFFPATH "verinfo");
		if(retval<0)
		{
			printf("WC24_CreateRecord returned %d\n", retval);
			VFF_Unmount("wc24dl.vff");
			return retval;
		}
		entry_bitmask |= BIT(1);
	}

	memset(url, 0, 256);
	snprintf(url, 255, "%swc24boottitle/bootmailupd%s", SRVR_BASEURL, url_id);
	retval = WC24_FindEntry((u32)curtitleid, "bootmailupd", &myent, 1);
	if(retval>=0)
	{
		if(strncmp(myent.url, url, 0xec))
		{
			WC24_DeleteRecord(retval);
			retval = LIBWC24_ENOENT;
		}
		else
		{
			retval = -1;
		}
	}

	if(retval==LIBWC24_ENOENT)
	{
		printf("Creating record+entry for wc24boottitle auto-update boot mail...\n");
		retval = WC24_CreateRecord(&myrec, &myent, WC24ID, 0, 0x4842, WC24_TYPE_MSGBOARD, WC24_RECORD_FLAGS_DEFAULT, WC24_FLAGS_HB | WC24_FLAGS_IDLEONLY, dlfreq, 0x5a0, 0, url, NULL);
		if(retval<0)
		{
			printf("WC24_CreateRecord returned %d\n", retval);
			VFF_Unmount("wc24dl.vff");
			return retval;
		}
		entry_bitmask |= BIT(2);
	}

	memset(url, 0, 256);
	snprintf(url, 255, "%swc24boottitle/bootmailbt%s", SRVR_BASEURL, url_id);
	retval = WC24_FindEntry((u32)curtitleid, "bootmailbt", &myent, 1);
	if(retval>=0)
	{
		if(strncmp(myent.url, url, 0xec))
		{
			WC24_DeleteRecord(retval);
			retval = LIBWC24_ENOENT;
		}
		else
		{
			retval = -1;
		}
	}

	if(retval==LIBWC24_ENOENT)
	{
		printf("Creating record+entry for wc24boottitle boot mail...\n");
		retval = WC24_CreateRecord(&myrec, &myent, WC24ID, 0, 0x4842, WC24_TYPE_MSGBOARD, WC24_RECORD_FLAGS_DEFAULT, WC24_FLAGS_HB | WC24_FLAGS_IDLEONLY, dlfreq, 0x5a0, 0, url, NULL);
		if(retval<0)
		{
			printf("WC24_CreateRecord returned %d\n", retval);
			VFF_Unmount("wc24dl.vff");
			return retval;
		}
		entry_bitmask |= BIT(3);
	}

	memset(url, 0, 256);
	snprintf(url, 255, "%swc24boottitle/changelogmail%s", SRVR_BASEURL, url_id);
	retval = WC24_FindEntry((u32)curtitleid, "changelogmail", &myent, 1);
	if(retval>=0)
	{
		if(strncmp(myent.url, url, 0xec))
		{
			WC24_DeleteRecord(retval);
			retval = LIBWC24_ENOENT;
		}
		else
		{
			retval = -1;
		}
	}

	if(retval==LIBWC24_ENOENT)
	{
		printf("Creating record+entry for wc24boottitle changelog mail...\n");
		retval = WC24_CreateRecord(&myrec, &myent, WC24ID, 0, 0x4842, WC24_TYPE_MSGBOARD, WC24_RECORD_FLAGS_DEFAULT, WC24_FLAGS_HB, dlfreq, 0x5a0, 0, url, NULL);
		if(retval<0)
		{
			printf("WC24_CreateRecord returned %d\n", retval);
			VFF_Unmount("wc24dl.vff");
			return retval;
		}
		entry_bitmask |= BIT(4);
	}

	if(entry_bitmask)
	{
		printf("New entries were installed, downloading the content immediately...\n");

		if(entry_bitmask & BIT(0))
		{
			memset(url, 0, 256);
			snprintf(url, 255, "%swc24boottitle/installer.dol%s", SRVR_BASEURL, url_id);
			retval = WC24_FindEntry((u32)curtitleid, url, &myent, 0);
			if(retval<0)
			{
				printf("Failed to find entry for wc24boottitle auto-update installer.\n");
			}
			else
			{
				retval = KD_Download(KD_DOWNLOADFLAGS_MANUAL, (u16)retval, 0x0);
				WC24_ReadEntry(myent.index, &myent);
				if(retval<0)printf("KD_Download for wc24boottitle auto-update installer entry failed: %d\n", retval);
				if(myent.error_code!=0 && myent.error_code!=WC24_EHTTP304)printf("WC24 error code: %d\n", myent.error_code);
				printf("cnt_nextdl: %x\n", (u32)myent.cnt_nextdl);
			}
		}

		if(entry_bitmask & BIT(1))
		{
			memset(url, 0, 256);
			snprintf(url, 255, "%swc24boottitle/verinfo%s", SRVR_BASEURL, url_id);
			retval = WC24_FindEntry((u32)curtitleid, url, &myent, 0);
			if(retval<0)
			{
				printf("Failed to find entry for wc24boottitle auto-update version info.\n");
			}
			else
			{
				retval = KD_Download(KD_DOWNLOADFLAGS_MANUAL, (u16)retval, 0x0);
				WC24_ReadEntry(myent.index, &myent);
				if(retval<0)printf("KD_Download for wc24boottitle auto-update version info entry failed: %d\n", retval);
				if(myent.error_code!=0 && myent.error_code!=WC24_EHTTP304)printf("WC24 error code: %d\n", myent.error_code);
				printf("cnt_nextdl: %x\n", (u32)myent.cnt_nextdl);
			}
		}

		if(entry_bitmask & BIT(2))
		{
			memset(url, 0, 256);
			snprintf(url, 255, "%swc24boottitle/bootmailupd%s", SRVR_BASEURL, url_id);
			retval = WC24_FindEntry((u32)curtitleid, url, &myent, 0);
			if(retval<0)
			{
				printf("Failed to find entry for wc24boottitle auto-update boot mail.\n");
			}
			else
			{
				retval = KD_Download(KD_DOWNLOADFLAGS_MANUAL, (u16)retval, 0x0);
				WC24_ReadEntry(myent.index, &myent);
				if(retval<0)printf("KD_Download for wc24boottitle auto-update boot mail entry failed: %d\n", retval);
				if(myent.error_code!=0 && myent.error_code!=WC24_EHTTP304)printf("WC24 error code: %d\n", myent.error_code);
				printf("cnt_nextdl: %x\n", (u32)myent.cnt_nextdl);
			}
		}

		if(entry_bitmask & BIT(3))
		{
			memset(url, 0, 256);
			snprintf(url, 255, "%swc24boottitle/bootmailbt%s", SRVR_BASEURL, url_id);
			retval = WC24_FindEntry((u32)curtitleid, url, &myent, 0);
			if(retval<0)
			{
				printf("Failed to find entry for wc24boottitle boot mail.\n");
			}
			else
			{
				retval = KD_Download(KD_DOWNLOADFLAGS_MANUAL, (u16)retval, 0x0);
				WC24_ReadEntry(myent.index, &myent);
				if(retval<0)printf("KD_Download for wc24boottitle boot mail entry failed: %d\n", retval);
				if(myent.error_code!=0 && myent.error_code!=WC24_EHTTP304)printf("WC24 error code: %d\n", myent.error_code);
				printf("cnt_nextdl: %x\n", (u32)myent.cnt_nextdl);
			}
		}

		if(entry_bitmask & BIT(4))
		{
			memset(url, 0, 256);
			snprintf(url, 255, "%swc24boottitle/changelogmail%s", SRVR_BASEURL, url_id);
			retval = WC24_FindEntry((u32)curtitleid, url, &myent, 0);
			if(retval<0)
			{
				printf("Failed to find entry for wc24boottitle changelog mail.\n");
			}
			else
			{
				retval = KD_Download(KD_DOWNLOADFLAGS_MANUAL, (u16)retval, 0x0);
				WC24_ReadEntry(myent.index, &myent);
				if(retval<0)printf("KD_Download for wc24boottitle changelog mail entry failed: %d\n", retval);
				if(myent.error_code!=0 && myent.error_code!=WC24_EHTTP304)printf("WC24 error code: %d\n", myent.error_code);
				printf("cnt_nextdl: %x\n", (u32)myent.cnt_nextdl);
			}
		}
	}

	printf("Processing content in wc24dl.vff...\n");
	WC24_MountWC24DlVFF();

	fdol = fopen("wc24dl.vff:/" VFFPATH "installer.dol", "r");
	if(fdol==NULL)
	{
		printf("wc24dl.vff:/" VFFPATH "installer.dol doesn't exist, no update is available.\n");
	}
	else
	{
		fver = fopen("wc24dl.vff:/" VFFPATH "verinfo", "r");
		if(fver==NULL)
		{
			printf("wc24dl.vff:/" VFFPATH "verinfo doesn't exist, no update is available.\n");
		}
		else
		{
			configbuf = (char*)malloc(0x200);
			updateinfobuf = (char*)malloc(0x200);
			memset(configbuf, 0, 0x200);
			memset(updateinfobuf, 0, 0x200);
			for(i=0; i<0x10; i++)
			{
				configlines[i] = &configbuf[i*0x20];
				updateinfolines[i] = &updateinfobuf[i*0x20];
			}
			fread(updateinfobuf, 1, 0x200, fver);
			fclose(fver);

			fconfig = fopen("wc24dl.vff:/" VFFPATH "config", "r+");
			if(fconfig==NULL)
			{
				printf("Config file doesn't exist, creating.\n");
				fconfig = fopen("wc24dl.vff:/" VFFPATH "config", "w+");
				strncpy(configlines[0], WC24BOOTTITLE_VERSION, 0x1f);
				snprintf(configlines[1], 0x1f, "Revision: %d", 0);//SVN beta auto-update isn't implemented yet.
				fwrite(configbuf, 1, 0x200, fconfig);
				fseek(fconfig, 0, SEEK_SET);
			}
			else
			{
				fread(configbuf, 1, 0x200, fconfig);
				fseek(fconfig, 0, SEEK_SET);

				if(strncmp(configlines[0], WC24BOOTTITLE_VERSION, 0x1f)<0)
				{
					printf("The stable version contained in the config is older than the version contained in the title dol, updating the config version...\n");
					strncpy(configlines[0], WC24BOOTTITLE_VERSION, 0x1f);
					fwrite(configbuf, 1, 0x200, fconfig);
					fseek(fconfig, 0, SEEK_SET);
				}
			}

			if(strncmp(configlines[0], updateinfolines[0], 0x1f)<0)
			{
				printf("The stable version contained in the config is older than the version contained in the stable wc24boottitle version info WC24 dl content, updating...\n");
				strncpy(configlines[0], updateinfolines[0], 0x1f);
				fwrite(configbuf, 1, 0x200, fconfig);
				fseek(fconfig, 0, SEEK_SET);

				stat("wc24dl.vff:/" VFFPATH "installer.dol", &dolstats);
				dol_size = dolstats.st_size;
				fread((void*)0x90100000, 1, dol_size, fdol);
				DCFlushRange((void*)0x90100000, dol_size);
				printf("Update size: %x\n", dol_size);

				free(updateinfobuf);
				free(configbuf);
				fclose(fconfig);
				fclose(fdol);
				fclose(fver);
				unlink("wc24dl.vff:/" VFFPATH "installer.dol");
				unlink("wc24dl.vff:/" VFFPATH "verinfo");
				VFF_Unmount("wc24dl.vff");

				argv = (char**)malloc(16);
				memset(argv, 0, 16);
				for(i=0; i<4; i++)
				{
					argv[i] = (char*)malloc(256);
					memset(argv[i], 0, 256);
				}
				strncpy(argv[0], "0001000857434254", 255);
				strncpy(argv[1], "wc24dl.vff:/" VFFPATH "installer.dol", 255);
				strncpy(argv[2], "1", 255);
				strncpy(argv[3], "0", 255);

				ProcessArgs(4, argv, 1);
			}
			else
			{
				printf("Deleting wc24dl.vff:/" VFFPATH "installer.dol and wc24dl.vff:/" VFFPATH "verinfo since no update is available.\n");
				unlink("wc24dl.vff:/" VFFPATH "installer.dol");
				unlink("wc24dl.vff:/" VFFPATH "verinfo");
			}

			free(updateinfobuf);
			free(configbuf);
			fclose(fconfig);
		}
	}

	if(fdol)fclose(fdol);
	if(fver)fclose(fver);
	VFF_Unmount("wc24dl.vff");

	return 0;
}
Esempio n. 26
0
int main(int argc, char *argv[])
{
  void *cvode_mem;
  UserData data;
  realtype abstol, reltol, t, tout;
  N_Vector y;
  int iout, flag;

  realtype *pbar;
  int is, *plist;
  N_Vector *uS;
  booleantype sensi, err_con;
  int sensi_meth;

  pbar = NULL;
  plist = NULL;
  uS = NULL;
  y = NULL;
  data = NULL;
  cvode_mem = NULL;

  /* Process arguments */
  ProcessArgs(argc, argv, &sensi, &sensi_meth, &err_con);

  /* Problem parameters */
  data = AllocUserData();
  if(check_flag((void *)data, "AllocUserData", 2)) return(1);
  InitUserData(data);

  /* Initial states */
  y = N_VNew_Serial(NEQ);
  if(check_flag((void *)y, "N_VNew_Serial", 0)) return(1);
  SetInitialProfiles(y, data->dx, data->dz);
  
  /* Tolerances */
  abstol=ATOL; 
  reltol=RTOL;

  /* Create CVODES object */
  cvode_mem = CVodeCreate(CV_BDF, CV_NEWTON);
  if(check_flag((void *)cvode_mem, "CVodeCreate", 0)) return(1);

  flag = CVodeSetFdata(cvode_mem, data);
  if(check_flag(&flag, "CVodeSetFdata", 1)) return(1);

  flag = CVodeSetMaxNumSteps(cvode_mem, 2000);
  if(check_flag(&flag, "CVodeSetMaxNumSteps", 1)) return(1);

  /* Allocate CVODES memory */
  flag = CVodeMalloc(cvode_mem, f, T0, y, CV_SS, reltol, &abstol);
  if(check_flag(&flag, "CVodeMalloc", 1)) return(1);

  /* Attach CVSPGMR linear solver */
  flag = CVSpgmr(cvode_mem, PREC_LEFT, 0);
  if(check_flag(&flag, "CVSpgmr", 1)) return(1);

  flag = CVSpilsSetPreconditioner(cvode_mem, Precond, PSolve, data);
  if(check_flag(&flag, "CVSpilsSetPreconditioner", 1)) return(1);

  printf("\n2-species diurnal advection-diffusion problem\n");

  /* Forward sensitivity analysis */
  if(sensi) {

    plist = (int *) malloc(NS * sizeof(int));
    if(check_flag((void *)plist, "malloc", 2)) return(1);
    for(is=0; is<NS; is++) plist[is] = is;

    pbar = (realtype *) malloc(NS * sizeof(realtype));
    if(check_flag((void *)pbar, "malloc", 2)) return(1);
    for(is=0; is<NS; is++) pbar[is] = data->p[plist[is]];

    uS = N_VCloneVectorArray_Serial(NS, y);
    if(check_flag((void *)uS, "N_VCloneVectorArray_Serial", 0)) return(1);
    for(is=0;is<NS;is++)
      N_VConst(ZERO,uS[is]);

    flag = CVodeSensMalloc(cvode_mem, NS, sensi_meth, uS);
    if(check_flag(&flag, "CVodeSensMalloc", 1)) return(1);

    flag = CVodeSetSensErrCon(cvode_mem, err_con);
    if(check_flag(&flag, "CVodeSetSensErrCon", 1)) return(1);

    flag = CVodeSetSensRho(cvode_mem, ZERO);
    if(check_flag(&flag, "CVodeSetSensRho", 1)) return(1);

    flag = CVodeSetSensParams(cvode_mem, data->p, pbar, plist);
    if(check_flag(&flag, "CVodeSetSensParams", 1)) return(1);

    printf("Sensitivity: YES ");
    if(sensi_meth == CV_SIMULTANEOUS)   
      printf("( SIMULTANEOUS +");
    else 
      if(sensi_meth == CV_STAGGERED) printf("( STAGGERED +");
      else                           printf("( STAGGERED1 +");   
    if(err_con) printf(" FULL ERROR CONTROL )");
    else        printf(" PARTIAL ERROR CONTROL )");
    
  } else {

    printf("Sensitivity: NO ");

  }

  /* In loop over output points, call CVode, print results, test for error */

  printf("\n\n");
  printf("========================================================================\n");
  printf("     T     Q       H      NST                    Bottom left  Top right \n");
  printf("========================================================================\n");

  for (iout=1, tout = TWOHR; iout <= NOUT; iout++, tout += TWOHR) {
    flag = CVode(cvode_mem, tout, y, &t, CV_NORMAL);
    if(check_flag(&flag, "CVode", 1)) break;
    PrintOutput(cvode_mem, t, y);
    if (sensi) {
      flag = CVodeGetSens(cvode_mem, t, uS);
      if(check_flag(&flag, "CVodeGetSens", 1)) break;
      PrintOutputS(uS);
    }
    
    printf("------------------------------------------------------------------------\n");

  }

  /* Print final statistics */
  PrintFinalStats(cvode_mem, sensi);

  /* Free memory */
  N_VDestroy_Serial(y);
  if (sensi) {
    N_VDestroyVectorArray_Serial(uS, NS);
    free(pbar);
    free(plist);
  }
  FreeUserData(data);
  CVodeFree(&cvode_mem);

  return(0);
}
Esempio n. 27
0
int
main(int argc, char **argv, char **envp)
{
#ifdef XP_MACOSX
    InitAutoreleasePool();
#endif
    JSRuntime *rt;
    JSContext *cx;
    JSObject *glob, *envobj;
    int result;
    nsresult rv;

    // unbuffer stdout so that output is in the correct order; note that stderr
    // is unbuffered by default
    setbuf(stdout, 0);

    gErrFile = stderr;
    gOutFile = stdout;
    {
        nsCOMPtr<nsIServiceManager> servMan;
        rv = NS_InitXPCOM2(getter_AddRefs(servMan), nsnull, nsnull);
        if (NS_FAILED(rv)) {
            printf("NS_InitXPCOM failed!\n");
            return 1;
        }
        {
            nsCOMPtr<nsIComponentRegistrar> registrar = do_QueryInterface(servMan);
            NS_ASSERTION(registrar, "Null nsIComponentRegistrar");
            if (registrar)
                registrar->AutoRegister(nsnull);
        }

        nsCOMPtr<nsIJSRuntimeService> rtsvc = do_GetService("@mozilla.org/js/xpc/RuntimeService;1");
        // get the JSRuntime from the runtime svc
        if (!rtsvc) {
            printf("failed to get nsJSRuntimeService!\n");
            return 1;
        }
    
        if (NS_FAILED(rtsvc->GetRuntime(&rt)) || !rt) {
            printf("failed to get JSRuntime from nsJSRuntimeService!\n");
            return 1;
        }

        JS_SetContextCallback(rt, ContextCallback);

        cx = JS_NewContext(rt, 8192);
        if (!cx) {
            printf("JS_NewContext failed!\n");
            return 1;
        }

        nsCOMPtr<nsIXPConnect> xpc = do_GetService(nsIXPConnect::GetCID());
        if (!xpc) {
            printf("failed to get nsXPConnect service!\n");
            return 1;
        }

        // Since the caps security system might set a default security manager
        // we will be sure that the secman on this context gives full trust.
        nsRefPtr<FullTrustSecMan> secman = new FullTrustSecMan();
        xpc->SetSecurityManagerForJSContext(cx, secman, 0xFFFF);

#ifndef XPCONNECT_STANDALONE
        // Fetch the system principal and store it away in a global, to use for
        // script compilation in Load() and ProcessFile() (including interactive
        // eval loop)
        {
            nsCOMPtr<nsIPrincipal> princ;

            nsCOMPtr<nsIScriptSecurityManager> securityManager =
                do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
            if (NS_SUCCEEDED(rv) && securityManager) {
                rv = securityManager->GetSystemPrincipal(getter_AddRefs(princ));
                if (NS_FAILED(rv)) {
                    fprintf(gErrFile, "+++ Failed to obtain SystemPrincipal from ScriptSecurityManager service.\n");
                } else {
                    // fetch the JS principals and stick in a global
                    rv = princ->GetJSPrincipals(cx, &gJSPrincipals);
                    if (NS_FAILED(rv)) {
                        fprintf(gErrFile, "+++ Failed to obtain JS principals from SystemPrincipal.\n");
                    }
                    secman->SetSystemPrincipal(princ);
                }
            } else {
                fprintf(gErrFile, "+++ Failed to get ScriptSecurityManager service, running without principals");
            }
        }
#endif

#ifdef TEST_TranslateThis
        nsCOMPtr<nsIXPCFunctionThisTranslator>
            translator(new nsXPCFunctionThisTranslator);
        xpc->SetFunctionThisTranslator(NS_GET_IID(nsITestXPCFunctionCallback), translator, nsnull);
#endif
    
        nsCOMPtr<nsIJSContextStack> cxstack = do_GetService("@mozilla.org/js/xpc/ContextStack;1");
        if (!cxstack) {
            printf("failed to get the nsThreadJSContextStack service!\n");
            return 1;
        }

        if(NS_FAILED(cxstack->Push(cx))) {
            printf("failed to push the current JSContext on the nsThreadJSContextStack!\n");
            return 1;
        }

        nsCOMPtr<nsIXPCScriptable> backstagePass;
        nsresult rv = rtsvc->GetBackstagePass(getter_AddRefs(backstagePass));
        if (NS_FAILED(rv)) {
            fprintf(gErrFile, "+++ Failed to get backstage pass from rtsvc: %8x\n",
                    rv);
            return 1;
        }

        nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
        rv = xpc->InitClassesWithNewWrappedGlobal(cx, backstagePass,
                                                  NS_GET_IID(nsISupports),
                                                  nsIXPConnect::
                                                      FLAG_SYSTEM_GLOBAL_OBJECT,
                                                  getter_AddRefs(holder));
        if (NS_FAILED(rv))
            return 1;
        
        rv = holder->GetJSObject(&glob);
        if (NS_FAILED(rv)) {
            NS_ASSERTION(glob == nsnull, "bad GetJSObject?");
            return 1;
        }

        JS_BeginRequest(cx);

        if (!JS_DefineFunctions(cx, glob, glob_functions)) {
            JS_EndRequest(cx);
            return 1;
        }

        envobj = JS_DefineObject(cx, glob, "environment", &env_class, NULL, 0);
        if (!envobj || !JS_SetPrivate(cx, envobj, envp)) {
            JS_EndRequest(cx);
            return 1;
        }

        argc--;
        argv++;

        result = ProcessArgs(cx, glob, argv, argc);


//#define TEST_CALL_ON_WRAPPED_JS_AFTER_SHUTDOWN 1

#ifdef TEST_CALL_ON_WRAPPED_JS_AFTER_SHUTDOWN
        // test of late call and release (see below)
        nsCOMPtr<nsIJSContextStack> bogus;
        xpc->WrapJS(cx, glob, NS_GET_IID(nsIJSContextStack),
                    (void**) getter_AddRefs(bogus));
#endif

        JSPRINCIPALS_DROP(cx, gJSPrincipals);
        JS_ClearScope(cx, glob);
        JS_GC(cx);
        JSContext *oldcx;
        cxstack->Pop(&oldcx);
        NS_ASSERTION(oldcx == cx, "JS thread context push/pop mismatch");
        cxstack = nsnull;
        JS_GC(cx);
        JS_DestroyContext(cx);
        xpc->SyncJSContexts();
    } // this scopes the nsCOMPtrs
    // no nsCOMPtrs are allowed to be alive when you call NS_ShutdownXPCOM
    rv = NS_ShutdownXPCOM( NULL );
    NS_ASSERTION(NS_SUCCEEDED(rv), "NS_ShutdownXPCOM failed");

#ifdef TEST_CALL_ON_WRAPPED_JS_AFTER_SHUTDOWN
    // test of late call and release (see above)
    JSContext* bogusCX;
    bogus->Peek(&bogusCX);
    bogus = nsnull;
#endif

#ifdef XP_MACOSX
    FinishAutoreleasePool();
#endif

    return result;
}
Esempio n. 28
0
// important: this function makes no attempt to close open file descriptors.
// if you have a file descriptor, it WILL be available to the child process unless you flag it close-on-exec.
void IOProcess::Exec(std::string program, std::vector<String> arguments)
{
	Exec(ProcessArgs(program, arguments));
}
Esempio n. 29
0
//---------------------------------------------------------------------------------
int main(int argc, char **argv) {
//---------------------------------------------------------------------------------
	s32 retval;

	// Initialise the video system
	VIDEO_Init();
	
	// This function initialises the attached controllers
	WPAD_Init();
	
	// Obtain the preferred video mode from the system
	// This will correspond to the settings in the Wii menu
	rmode = VIDEO_GetPreferredMode(NULL);

	// Allocate memory for the display in the uncached region
	xfb = MEM_K0_TO_K1(SYS_AllocateFramebuffer(rmode));
	
	// Initialise the console, required for printf
	console_init(xfb,20,20,rmode->fbWidth,rmode->xfbHeight,rmode->fbWidth*VI_DISPLAY_PIX_SZ);
	
	// Set up the video registers with the chosen mode
	VIDEO_Configure(rmode);
	
	// Tell the video hardware where our display memory is
	VIDEO_SetNextFramebuffer(xfb);
	
	// Make the display visible
	VIDEO_SetBlack(FALSE);

	// Flush the video register changes to the hardware
	VIDEO_Flush();

	// Wait for Video setup to complete
	VIDEO_WaitVSync();
	if(rmode->viTVMode&VI_NON_INTERLACE) VIDEO_WaitVSync();
	if(usb_isgeckoalive(1))CON_EnableGecko(1, 1);

	log_buffer = (char*)malloc(0x4000);
	memset(log_buffer, 0, 0x4000);

	printf("Initializing WC24...\n");
	retval = WC24_Init();
	if(retval<0)
	{
		printf("WC24_Init returned %d\n", retval);
		return retval;
	}
	curtitleid = WC24_GetTitleID();

	printf("\n\n");
	printf("Getting NANDBOOTINFO argv...\n");
	argv = WII_GetNANDBootInfoArgv(&argc, &launchcode);
	#ifdef WIILOADAPPDEBUG
		#ifdef WIILOADTEST_BOOTDISC	
		argc = 1;
		launchcode = 2;
		#endif

		#ifdef WIILOADTEST_BOOTHB	
		launchcode = 1;
		argc = 2;
		argv[1] = WIILOADTEST_BOOTHB;
		#endif
	#endif

	ResetWakeup_Timestamp();
	#ifndef WIILOADAPPDEBUG
	retval = ProcessWC24(launchcode & BIT(25));//Don't do any WC24 stuff with HBC wiiload, only with the actual installed wc24boottitle.
	#endif
	launchcode &= ~(BIT(25));
	ProcessArgs(argc, argv, 0);
	printf("Shutting down WC24...\n");
	WC24_Shutdown();
	FlushLog();

	return 0;
}
Esempio n. 30
0
int
main(int argc, char **argv)
{
    int stackDummy;
    SG_error err;
    SG_context * pCtx = NULL;
    JSRuntime *rt;
    JSContext *cx;
    SG_log_console__data cLogStdData;
    SG_log_text__data cLogFileData;
    SG_log_text__writer__daily_path__data cLogFileWriterData;
    JSObject *glob;
    int result;
    SG_bool skipModules = SG_FALSE;

    SG_zero(cLogStdData);
    SG_zero(cLogFileData);
    SG_zero(cLogFileWriterData);

    CheckHelpMessages();
    setlocale(LC_ALL, "");

    gStackBase = (jsuword)&stackDummy;

#ifdef XP_OS2
   /* these streams are normally line buffered on OS/2 and need a \n, *
    * so we need to unbuffer then to get a reasonable prompt          */
    setbuf(stdout,0);
    setbuf(stderr,0);
#endif

    gErrFile = stderr;
    gOutFile = stdout;

    argc--;
    argv++;

    err = SG_context__alloc(&pCtx);
    if (SG_IS_ERROR(err))
        return 1;
    SG_lib__global_initialize(pCtx);
    if (SG_context__has_err(pCtx))
    {
        _vscript_context_teardown(&pCtx);
        return 1;
    }

    _checkSkipModules(pCtx, &argc, argv, &skipModules);
    if (SG_context__has_err(pCtx))
    {
        _vscript_context_teardown(&pCtx);
        return 1;
    }

    SG_jscore__new_runtime(pCtx, ContextCallback, shell_functions, skipModules, &rt);
    if (SG_context__has_err(pCtx))
    {
        _vscript_context_teardown(&pCtx);
        return 1;
    }

    SG_jscore__new_context(pCtx, &cx, &glob, NULL);
    if (SG_context__has_err(pCtx))
    {
        _vscript_context_teardown(&pCtx);
        return 1;
    }

    JS_SetGlobalObject(cx, glob);

    //////////////////////////////////////////////////////////////////
    // Allocate and initialize the SG_context.
    _set_up_logging(pCtx, &cLogStdData, &cLogFileData, &cLogFileWriterData);

    result = ProcessArgs(cx, glob, argv, argc);

    _clean_up_logging(pCtx, &cLogStdData, &cLogFileData, &cLogFileWriterData);

    // TODO 2011/09/30 The following call removes "pCtx" from
    // TODO            the private data in the "cx".  This was
    // TODO            done for neatness before we destroy it.
    // TODO            And this has worked fine for years.
    // TODO
    // TODO            I have commented this out as an experiment
    // TODO            so that the "pCtx" is still available for
    // TODO            use in any GC/Finalize callbacks.
    // TODO
    // TODO SG_jsglue__set_sg_context(NULL, cx);
    JS_EndRequest(cx);
    JS_DestroyContext(cx);

    // End of SG_context post-processing.
    //////////////////////////////////////////////////////////////////

    result = result + _vscript_context_teardown(&pCtx);

    return result;
}