Exemplo n.º 1
0
void CSocketClient::OnError( const _tstring &message )
{
	Output( message );
}
Exemplo n.º 2
0
int main(int argc, char* argv[])
{
  PRTime start = _PR_Now();
  char exePath[MAXPATHLEN];

#ifdef XP_MACOSX
  TriggerQuirks();
#endif

  nsresult rv = mozilla::BinaryPath::Get(argv[0], exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't calculate the application directory.\n");
    return 255;
  }

  char *lastSlash = strrchr(exePath, XPCOM_FILE_PATH_SEPARATOR[0]);
  if (!lastSlash || (size_t(lastSlash - exePath) > MAXPATHLEN - sizeof(XPCOM_DLL) - 1))
    return 255;

  strcpy(++lastSlash, XPCOM_DLL);

  int gotCounters;
#if defined(XP_UNIX)
  struct rusage initialRUsage;
  gotCounters = !getrusage(RUSAGE_SELF, &initialRUsage);
#elif defined(XP_WIN)
  IO_COUNTERS ioCounters;
  gotCounters = GetProcessIoCounters(GetCurrentProcess(), &ioCounters);
#endif

  // We do this because of data in bug 771745
  XPCOMGlueEnablePreload();

  rv = XPCOMGlueStartup(exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XPCOM.\n");
    return 255;
  }
  // Reset exePath so that it is the directory name and not the xpcom dll name
  *lastSlash = 0;

  rv = XPCOMGlueLoadXULFunctions(kXULFuncs);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XRE functions.\n");
    return 255;
  }

  XRE_StartupTimelineRecord(mozilla::StartupTimeline::START, start);

#ifdef XRE_HAS_DLL_BLOCKLIST
  XRE_SetupDllBlocklist();
#endif

  if (gotCounters) {
#if defined(XP_WIN)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_OPS,
                            int(ioCounters.ReadOperationCount));
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_TRANSFER,
                            int(ioCounters.ReadTransferCount / 1024));
    IO_COUNTERS newIoCounters;
    if (GetProcessIoCounters(GetCurrentProcess(), &newIoCounters)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_OPS,
                              int(newIoCounters.ReadOperationCount - ioCounters.ReadOperationCount));
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_TRANSFER,
                              int((newIoCounters.ReadTransferCount - ioCounters.ReadTransferCount) / 1024));
    }
#elif defined(XP_UNIX)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_HARD_FAULTS,
                            int(initialRUsage.ru_majflt));
    struct rusage newRUsage;
    if (!getrusage(RUSAGE_SELF, &newRUsage)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_HARD_FAULTS,
                              int(newRUsage.ru_majflt - initialRUsage.ru_majflt));
    }
#endif
  }

  int result;
  {
    ScopedLogging log;
    result = do_main(argc, argv);
  }

  XPCOMGlueShutdown();
  return result;
}
Exemplo n.º 3
0
void UserComment (const char* Comment)
/* Output a comment line */
{
    Output ("; %s", Comment);
    LineFeed ();
}
Exemplo n.º 4
0
void SecularUpdateLast
( bool  initialize,
  const Real& rho,
  const Matrix<Real>& z,
        LastState<Real>& state,
  const SecularEVDCtrl<Real>& ctrl )
{
    DEBUG_CSE
    const Real zero(0);
    const Int n = state.dMinusShift.Height();
    const Int origin = n-1;

    if( state.secular <= zero )
        state.rootRelLowerBound =
          Max( state.rootRelLowerBound, state.rootRelEst );
    else
        state.rootRelUpperBound =
          Min( state.rootRelUpperBound, state.rootRelEst );
    if( ctrl.progress )
        Output
        ("Relative interval is [",state.rootRelLowerBound,",",
         state.rootRelUpperBound,"]");

    const Real kGap = state.dMinusShift(origin);
    const Real km1Gap = state.dMinusShift(origin-1);

    Real a = state.secular - km1Gap*state.psiMinusDeriv -
      kGap*state.psiOriginDeriv;

    Real eta;
    if( initialize )
    {
        // Force flipping always?
        if( ctrl.negativeFix == CLIP_NEGATIVES )
            a = Max( a, zero );
        else
            a = Abs( a );

        if( a == zero )
        {
            // TODO(poulson): Explain this special case.
            //
            // Note that LAPACK's {s,d}lasd4 [CITATION] uses the equivalent of 
            //
            //     eta = rho - rootEst,
            //
            // while LAPACK's {s,d}laed4 [CITATION] has such an updated
            // commented out and
            // instead performs the following.
            eta = state.rootRelUpperBound - state.rootRelEst;
        }
        else
        {
            // We Approach From the Right with psi_{n-2}(x) osculatorally
            // interpolated as G(x; d(n-2)^2, r, s) and phi_{n-2}(x) exactly
            // represented as F(x; p, q). See the discussion surrounding Eq'n
            // (23) of LAWN 89 [CITATION], but keep in mind that we use the
            // definitions (a,b,c) corresponding to the standard quadratic 
            // equation a x^2 + b x + c = 0 rather than the notation of LAWN 89.
            const Real bNeg =
              (kGap+km1Gap)*state.secular -
              kGap*km1Gap*(state.psiMinusDeriv+state.psiOriginDeriv);
            const Real c = kGap*km1Gap*state.secular;
            eta = SolveQuadraticPlus( a, bNeg, c, ctrl.negativeFix );
        }
    }
    else
    {
        const Real bNeg =
          (kGap+km1Gap)*state.secular -
          kGap*km1Gap*(state.psiMinusDeriv+state.psiOriginDeriv);
        const Real c = kGap*km1Gap*state.secular;
        eta = SolveQuadraticPlus( a, bNeg, c, ctrl.negativeFix );
    }

    if( state.secular*eta >= zero )
    {
        // The current update does not move in the right direction, so fall back
        // to a small Newton step (as the derivative is likely large).
        if( ctrl.progress )
            Output("Falling back to Newton step");
        eta = -state.secular / (state.psiMinusDeriv+state.psiOriginDeriv);
    }

    const Real rootRelEstProp = state.rootRelEst + eta;
    if( rootRelEstProp > state.rootRelUpperBound ||
        rootRelEstProp < state.rootRelLowerBound )
    {
        if( ctrl.progress )
            Output("Stepped out of bounds");
        // Move halfway towards the bound instead of exceeding it. Note that 
        // LAPACK's {s,d}laed4 [CITATION] follows this strategy, but LAPACK's
        // {s,d}lasd4 uses trivial upper and lower bounds rather than
        // continually updating them.
        if( state.secular < zero )
            eta = (state.rootRelUpperBound - state.rootRelEst) / 2;
        else 
            eta = (state.rootRelLowerBound - state.rootRelEst) / 2;
    }

    state.rootEst += eta;
    state.rootRelEst += eta;
    state.secularOld = state.secular;
    for( Int j=0; j<n; ++j )
    {
        state.dMinusShift(j) -= eta;
    }
    EvaluateSecularLast( rho, z, state, ctrl.penalizeDerivative );
}
Exemplo n.º 5
0
static void usage( void )
{
    ShowProductInfo();

    Output( "Usage: dmpobj [options] objfile[" OBJSUFFIX "]..." CRLF );
    Output( "Options:" CRLF );
    Output( "-l\t\tProduce listing file" CRLF );
    Output( "-d\t\tPrint descriptive titles for some output" CRLF );
    Output( "-t\t\tPrint names for some index values and list at end" CRLF );
    Output( "-c\t\tDump COMENT records without interpretation" CRLF );
    Output( "-i\t\tOriginal Intel OMF-86 format" CRLF );
    Output( "-q\t\tQuiet, don't show product info" CRLF );
    Output( "-r\t\tProvide raw dump of records as well" CRLF );
    Output( "-rec=xxx\tProvide dump of selected record type" CRLF );
    Output( "\t\t  (by number or by symbolic name)" CRLF );
    leave( 1 );
}
Exemplo n.º 6
0
static void RelocateStarportIfUnderwaterOrBuried(SystemBody *sbody, Frame *frame, Planet *planet, vector3d &pos, matrix3x3d &rot)
{
	const double radius = planet->GetSystemBody()->GetRadius();

	// suggested position
	rot = sbody->GetOrbit().GetPlane();
	pos = rot * vector3d(0,1,0);

	// Check if height varies too much around the starport center
	// by sampling 6 points around it. try upto 100 new positions randomly until a match is found
	// this is not guaranteed to find a match but greatly increases the chancessteroids which are not too steep.

	bool variationWithinLimits = true;
	double bestVariation = 1e10; // any high value
	matrix3x3d rotNotUnderwaterWithLeastVariation = rot;
	vector3d posNotUnderwaterWithLeastVariation = pos;
	const double heightVariationCheckThreshold = 0.008; // max variation to radius radius ratio to check for local slope, ganymede is around 0.01
	const double terrainHeightVariation = planet->GetMaxFeatureRadius(); //in radii

	//Output("%s: terrain height variation %f\n", sbody->name.c_str(), terrainHeightVariation);

	// 6 points are sampled around the starport center by adding/subtracting delta to to coords
	// points must stay within max height variation to be accepted
	//    1. delta should be chosen such that it a distance from the starport center that encloses landing pads for the largest starport
	//    2. maxSlope should be set so maxHeightVariation is less than the height of the landing pads
	const double delta = 20.0/radius; // in radii
	const double maxSlope = 0.2; // 0.0 to 1.0
	const double maxHeightVariation = maxSlope*delta*radius; // in m

	matrix3x3d rot_ = rot;
	vector3d pos_ = pos;

	bool manualRelocationIsEasy = !(planet->GetSystemBody()->GetType() == SystemBody::TYPE_PLANET_ASTEROID || terrainHeightVariation > heightVariationCheckThreshold);

	// warn and leave it up to the user to relocate custom starports when it's easy to relocate manually, i.e. not on asteroids and other planets which are likely to have high variation in a lot of places
	const bool isRelocatableIfBuried = !(sbody->IsCustomBody() && manualRelocationIsEasy);

	bool isInitiallyUnderwater = false;
	bool initialVariationTooHigh = false;

	Random r(sbody->GetSeed());

	for (int tries = 0; tries < 200; tries++) {
		variationWithinLimits = true;

		const double height = planet->GetTerrainHeight(pos_) - radius; // in m

		// check height at 6 points around the starport center stays within variation tolerances
		// GetHeight gives a varying height field in 3 dimensions.
		// Given it's smoothly varying it's fine to sample it in arbitary directions to get an idea of how sharply it varies
		double v[6];
		v[0] = fabs(planet->GetTerrainHeight(vector3d(pos_.x+delta, pos_.y, pos_.z))-radius-height);
		v[1] = fabs(planet->GetTerrainHeight(vector3d(pos_.x-delta, pos_.y, pos_.z))-radius-height);
		v[2] = fabs(planet->GetTerrainHeight(vector3d(pos_.x, pos_.y, pos_.z+delta))-radius-height);
		v[3] = fabs(planet->GetTerrainHeight(vector3d(pos_.x, pos_.y, pos_.z-delta))-radius-height);
		v[4] = fabs(planet->GetTerrainHeight(vector3d(pos_.x, pos_.y+delta, pos_.z))-radius-height);
		v[5] = fabs(planet->GetTerrainHeight(vector3d(pos_.x, pos_.y-delta, pos_.z))-radius-height);

		// break if variation for all points is within limits
		double variationMax = 0.0;
		for (int i = 0; i < 6; i++) {
			variationWithinLimits = variationWithinLimits && (v[i] < maxHeightVariation);
			variationMax = (v[i] > variationMax)? v[i]:variationMax;
		}

		// check if underwater
		const bool starportUnderwater = (height <= 0.0);

		//Output("%s: try no: %i, Match found: %i, best variation in previous results %f, variationMax this try: %f, maxHeightVariation: %f, Starport is underwater: %i\n",
		//	sbody->name.c_str(), tries, (variationWithinLimits && !starportUnderwater), bestVariation, variationMax, maxHeightVariation, starportUnderwater);

		if  (tries == 0) {
			isInitiallyUnderwater = starportUnderwater;
			initialVariationTooHigh = !variationWithinLimits;
		}

		if (!starportUnderwater && variationMax < bestVariation) {
			bestVariation = variationMax;
			posNotUnderwaterWithLeastVariation = pos_;
			rotNotUnderwaterWithLeastVariation = rot_;
		}

		if (variationWithinLimits && !starportUnderwater) break;

		// try new random position
		const double r2 = r.Double(); 	// function parameter evaluation order is implementation-dependent
		const double r1 = r.Double();	// can't put two rands in the same expression
		rot_ = matrix3x3d::RotateZ(2*M_PI*r1)
			* matrix3x3d::RotateY(2*M_PI*r2);
		pos_ = rot_ * vector3d(0,1,0);
	}

	if (isInitiallyUnderwater || (isRelocatableIfBuried && initialVariationTooHigh)) {
		pos = posNotUnderwaterWithLeastVariation;
		rot = rotNotUnderwaterWithLeastVariation;
	}

	if (sbody->IsCustomBody()) {
		const SystemPath &p = sbody->GetPath();
		if (initialVariationTooHigh) {
			if (isRelocatableIfBuried) {
				Output("Warning: Lua custom Systems definition: Surface starport has been automatically relocated. This is in order to place it on flatter ground to reduce the chance of landing pads being buried. This is not an error as such and you may attempt to move the starport to another location by changing latitude and longitude fields.\n      Surface starport name: %s, Body name: %s, In sector: x = %i, y = %i, z = %i.\n",
					sbody->GetName().c_str(), sbody->GetParent()->GetName().c_str(), p.sectorX, p.sectorY, p.sectorZ);
			} else {
				Output("Warning: Lua custom Systems definition: Surface starport may have landing pads buried. The surface starport has not been automatically relocated as the planet appears smooth enough to manually relocate easily. This is not an error as such and you may attempt to move the starport to another location by changing latitude and longitude fields.\n      Surface starport name: %s, Body name: %s, In sector: x = %i, y = %i, z = %i.\n",
					sbody->GetName().c_str(), sbody->GetParent()->GetName().c_str(), p.sectorX, p.sectorY, p.sectorZ);
			}
		}
		if (isInitiallyUnderwater) {
			Output("Error: Lua custom Systems definition: Surface starport is underwater (height not greater than 0.0) and has been automatically relocated. Please move the starport to another location by changing latitude and longitude fields.\n      Surface starport name: %s, Body name: %s, In sector: x = %i, y = %i, z = %i.\n",
				sbody->GetName().c_str(), sbody->GetParent()->GetName().c_str(), p.sectorX, p.sectorY, p.sectorZ);
		}
	}
}
Exemplo n.º 7
0
void SecularInitialGuessLast
( const Matrix<Real>& d,
  const Real& rho,
  const Matrix<Real>& z,
        LastState<Real>& state,
  const SecularEVDCtrl<Real>& ctrl )
{
    DEBUG_CSE
    const Int n = d.Height();
    const Real zero(0), one(1);
    const Real rhoInv = one / rho;

    const Int origin = n-1;

    // Since the largest eigenvalue must live within
    //
    //   d(n-1) + (0, rho ||z||_2^2) = d(n-1) + (0, rho),
    //
    // we use the center as our initial guess. Therefore, put
    // 
    //   rootRelEst = (rho ||z||_2^2) / 2 = rho / 2 = rootEst - d(n-1).
    //
    const Real shiftedCenter = rho / 2;
    state.rootRelEst = shiftedCenter;
    state.rootEst = state.rootRelEst + d(origin);
    for( Int j=0; j<n; ++j ) 
    {
        state.dMinusShift(j) = (d(j) - d(origin)) - state.rootRelEst;
    }

    // Form psi_{origin-2}
    Real psiDoubleMinus = zero;
    psiDoubleMinus = zero;
    for( Int j=0; j<origin-1; ++j )
        psiDoubleMinus += z(j)*z(j) / state.dMinusShift(j);

    state.psiMinus = psiDoubleMinus +
      z(origin-1)*z(origin-1) / state.dMinusShift(origin-1);

    state.psiOrigin = z(origin)*z(origin) / state.dMinusShift(origin);

    const Real a = rhoInv + psiDoubleMinus;
    state.secularMinus = rhoInv + state.psiMinus;
    state.secular = state.secularMinus + state.psiOrigin;

    if( state.secular <= zero )
    {
        // Evaluate the negative of the two terms of the secular equation
        // near the origin at d(origin) + rho to see if they would overpower
        // the remaining terms. If so, we accept d(origin) + rho as the initial
        // guess, otherwise we solve the implied quadratic equation.
        //
        // This strategy originated in LAPACK's {s,d}laed4 [CITATION].
        //
        const Real temp =
          z(origin-1)*z(origin-1) / (d(origin) - d(origin-1) + rho) +
          z(origin)*z(origin) / rho;

        if( a <= temp )
        {
            state.rootRelEst = rho;
        }
        else
        {
            const Real bNeg = -a*state.diagDiff + z(origin-1)*z(origin-1) +
              z(origin)*z(origin);
            const Real c = -z(origin)*z(origin)*state.diagDiff;
            state.rootRelEst =
              SolveQuadraticPlus( a, bNeg, c, ctrl.negativeFix );
        }
        state.rootRelLowerBound = shiftedCenter;
        state.rootRelUpperBound = rho;
    }
    else
    {
        // We will approximate the secular equation with
        //
        //  f_{n-1,n-2}(y) + z(n-2)^2 / (d(n-2) - x) +
        //                   z(n-1)^2 / (d(n-1) - x),
        //
        // where f_{n-1,n-2}(y) is the secular equation, with the (n-1)'th and 
        // (n-2)'th terms removed, evaluated at the current estimate. We solve
        // for a root of this equation in terms of tau = x - d(n-1).
        // In particular, we pick the '-' branch of the quadratic equation.

        const Real bNeg = -a*state.diagDiff + z(origin-1)*z(origin-1) +
          z(origin)*z(origin);
        const Real c = -z(origin)*z(origin)*state.diagDiff;
        state.rootRelEst = SolveQuadraticPlus( a, bNeg, c, ctrl.negativeFix );
        state.rootRelLowerBound = zero;
        state.rootRelUpperBound = shiftedCenter;
    }
    if( ctrl.progress )
        Output
        ("Initial relative interval is [",state.rootRelLowerBound,",",
         state.rootRelUpperBound,"]");

    state.rootEst = state.rootRelEst + d(origin);
    for( Int j=0; j<n; ++j ) 
    {
        state.dMinusShift(j) = (d(j) - d(origin)) - state.rootRelEst;
    }
    EvaluateSecularLast( rho, z, state, ctrl.penalizeDerivative );
}
Exemplo n.º 8
0
void readcsPing(const int client, const int server)
{
	(void)client;
	(void)server;
	Output("\n> 0x%02x ; PONG",OPC_PING);
}
Exemplo n.º 9
0
void readcsUpdate(const int client, const int server)
{
	(void)client;
	(void)server;
	Output("\n> 0x%02x ; update request",OPC_UPDATE);
}
Exemplo n.º 10
0
void CLogOutput::Print(int priority, const std::string& text)
{
	Output(priority, text.c_str());
}
Exemplo n.º 11
0
string SDLInit(const char *title, const int2 &desired_screensize, bool isfullscreen, int vsync)
{
    //SDL_SetMainReady();
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER /* | SDL_INIT_AUDIO*/) < 0)
    {
        return SDLError("Unable to initialize SDL");
    }

    SDL_SetEventFilter(SDLHandleAppEvents, nullptr);

    Output(OUTPUT_INFO, "SDL initialized...");

    SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN);

    // on demand now
    //extern bool sfxr_init();
    //if (!sfxr_init())
    //   return SDLError("Unable to initialize audio");

    #ifdef PLATFORM_ES2
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    #else
        //certain older Intel HD GPUs and also Nvidia Quadro 1000M don't support 3.1 ? the 1000M is supposed to support 4.2
        //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
        //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
        #ifdef __APPLE__
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
            SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
        #elif defined(_WIN32)
            //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
            //SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
            //SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
        #endif
        #if defined(__APPLE__) || defined(_WIN32)
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
            SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
        #endif
    #endif

    //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);      // set this if we're in 2D mode for speed on mobile?
    SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 1);    // because we redraw the screen each frame

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    Output(OUTPUT_INFO, "SDL about to figure out display mode...");

    #ifdef PLATFORM_ES2
        landscape = desired_screensize.x() >= desired_screensize.y();
        int modes = SDL_GetNumDisplayModes(0);
        screensize = int2(1280, 720);
        for (int i = 0; i < modes; i++)
        {
            SDL_DisplayMode mode;
            SDL_GetDisplayMode(0, i, &mode);
            Output(OUTPUT_INFO, "mode: %d %d", mode.w, mode.h);
            if (landscape ? mode.w > screensize.x() : mode.h > screensize.y())
            {
                screensize = int2(mode.w, mode.h);
            }
        }

        Output(OUTPUT_INFO, "chosen resolution: %d %d", screensize.x(), screensize.y());
        Output(OUTPUT_INFO, "SDL about to create window...");

        _sdl_window = SDL_CreateWindow(title,
                                        0, 0,
                                        screensize.x(), screensize.y(),
                                        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS);

        Output(OUTPUT_INFO, _sdl_window ? "SDL window passed..." : "SDL window FAILED...");

        if (landscape) SDL_SetHint("SDL_HINT_ORIENTATIONS", "LandscapeLeft LandscapeRight");

        int ax = 0, ay = 0;
        SDL_GetWindowSize(_sdl_window, &ax, &ay);
        int2 actualscreensize(ax, ay);
        //screenscalefactor = screensize.x / actualscreensize.x;  // should be 2 on retina
        #ifdef __IOS__
            assert(actualscreensize == screensize);
            screensize = actualscreensize;
        #else
            screensize = actualscreensize;  // __ANDROID__
            Output(OUTPUT_INFO, "obtained resolution: %d %d", screensize.x(), screensize.y());
        #endif
    #else
        screensize = desired_screensize;
        _sdl_window = SDL_CreateWindow(title,
                                        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                        screensize.x(), screensize.y(),
                                        SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE |
                                            (isfullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0));
    #endif

    if (!_sdl_window)
        return SDLError("Unable to create window");

    Output(OUTPUT_INFO, "SDL window opened...");


    _sdl_context = SDL_GL_CreateContext(_sdl_window);
    Output(OUTPUT_INFO, _sdl_context ? "SDL context passed..." : "SDL context FAILED...");
    if (!_sdl_context) return SDLError("Unable to create OpenGL context");

    Output(OUTPUT_INFO, "SDL OpenGL context created...");

    /*
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
    SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
    */

    #ifndef __IOS__
        SDL_GL_SetSwapInterval(vsync);
    #endif

    SDL_JoystickEventState(SDL_ENABLE);
    SDL_JoystickUpdate();
    for(int i = 0; i < SDL_NumJoysticks(); i++)
    {
        SDL_Joystick *joy = SDL_JoystickOpen(i);
        if (joy)
        {
            Output(OUTPUT_INFO, "Detected joystick: %s (%d axes, %d buttons, %d balls, %d hats)",
                                SDL_JoystickName(joy), SDL_JoystickNumAxes(joy), SDL_JoystickNumButtons(joy),
                                SDL_JoystickNumBalls(joy), SDL_JoystickNumHats(joy));
        };
    };

    timestart = SDL_GetPerformanceCounter();
    timefreq = SDL_GetPerformanceFrequency();

    lasttime = -0.02f;    // ensure first frame doesn't get a crazy delta

    return "";
}
Exemplo n.º 12
0
void CLogOutput::Print(const std::string& text)
{
	Output(0, text.c_str());
}
Exemplo n.º 13
0
static ASM(void) errfunc(REG(d0, UBYTE c), REG(a3, xadUINT32 pd))
{
  UBYTE d = c;
  if(c)
    Write(Output(), &d, 1);
}
Exemplo n.º 14
0
void    OutRecordsDsbl(void)
{
  InitPushCRC();
  Push(&mpfRecordDsbl, sizeof(mpfRecordDsbl));
  Output(sizeof(mpfRecordDsbl));
}
Exemplo n.º 15
0
Controler::Controler(){
    in = Input();
    com = Computer();
    out = Output();
    eh = ExceptionHandler();
}
Exemplo n.º 16
0
void readscPing(const int server, const int client)
{
	(void)client;
	(void)server;
	Output("\n< 0x%02x ; PING",OPC_PING);
}
Exemplo n.º 17
0
void DumpVisitor::PutIndent() const
{
	for (unsigned int i = 0; i < m_level; i++)
		Output("  ");
}
Exemplo n.º 18
0
bool wxCrashReportImpl::Generate(int flags, EXCEPTION_POINTERS *ep)
{
    if ( m_hFile == INVALID_HANDLE_VALUE )
        return false;

#if wxUSE_DBGHELP
    if ( !ep )
        ep = wxGlobalSEInformation;

    if ( !ep )
    {
        Output(wxT("Context for crash report generation not available."));
        return false;
    }

    // show to the user that we're doing something...
    BusyCursor busyCursor;

    // user-specified crash report flags override those specified by the
    // programmer
    TCHAR envFlags[64];
    DWORD dwLen = ::GetEnvironmentVariable
                    (
                        wxT("WX_CRASH_FLAGS"),
                        envFlags,
                        WXSIZEOF(envFlags)
                    );

    int flagsEnv;
    if ( dwLen && dwLen < WXSIZEOF(envFlags) &&
            wxSscanf(envFlags, wxT("%d"), &flagsEnv) == 1 )
    {
        flags = flagsEnv;
    }

    if ( wxDbgHelpDLL::Init() )
    {
        MINIDUMP_EXCEPTION_INFORMATION minidumpExcInfo;

        minidumpExcInfo.ThreadId = ::GetCurrentThreadId();
        minidumpExcInfo.ExceptionPointers = ep;
        minidumpExcInfo.ClientPointers = FALSE; // in our own address space

        // do generate the dump
        MINIDUMP_TYPE dumpFlags;
        if ( flags & wxCRASH_REPORT_LOCALS )
        {
            // the only way to get local variables is to dump the entire
            // process memory space -- but this makes for huge (dozens or
            // even hundreds of Mb) files
            dumpFlags = MiniDumpWithFullMemory;
        }
        else if ( flags & wxCRASH_REPORT_GLOBALS )
        {
            // MiniDumpWriteDump() has the option for dumping just the data
            // segment which contains all globals -- exactly what we need
            dumpFlags = MiniDumpWithDataSegs;
        }
        else // minimal dump
        {
            // the file size is not much bigger than when using MiniDumpNormal
            // if we use the flags below, but the minidump is much more useful
            // as it contains the values of many (but not all) local variables
            dumpFlags = (MINIDUMP_TYPE)(MiniDumpScanMemory
#if _MSC_VER > 1300
                                        |MiniDumpWithIndirectlyReferencedMemory
#endif
                                        );
        }

        if ( !wxDbgHelpDLL::MiniDumpWriteDump
              (
                ::GetCurrentProcess(),
                ::GetCurrentProcessId(),
                m_hFile,                    // file to write to
                dumpFlags,                  // kind of dump to craete
                &minidumpExcInfo,
                NULL,                       // no extra user-defined data
                NULL                        // no callbacks
              ) )
        {
            Output(wxT("MiniDumpWriteDump() failed."));

            return false;
        }

        return true;
    }
    else // dbghelp.dll couldn't be loaded
    {
        Output(wxT("%s"), wxDbgHelpDLL::GetErrorMessage().c_str());
    }
#else // !wxUSE_DBGHELP
    wxUnusedVar(flags);
    wxUnusedVar(ep);

    Output(wxT("Support for crash report generation was not included ")
           wxT("in this wxWidgets version."));
#endif // wxUSE_DBGHELP/!wxUSE_DBGHELP

    return false;
}
Exemplo n.º 19
0
void SecularInitialGuess
( const Int whichValue,
  const Matrix<Real>& d,
  const Real& rho,
  const Matrix<Real>& z,
        State<Real>& state,
  const SecularEVDCtrl<Real>& ctrl )
{
    DEBUG_CSE
    const Real zero(0), one(1);
    const Int k = whichValue;
    const Int n = d.Height();
    if( k >= n-1 )
        LogicError("Assumption of inner eigenvalue broken");

    // We can test whether the k'th eigenvalue is in the first or second
    // half of (d(k) d(k+1)) by testing the sign of the secular
    // equation evaluated at the center point,
    //
    //   center = (d(k) + d(k+1))/2.
    //
    const Real center = (d(k) + d(k+1)) / 2; 

    // Follow LAPACK's {s,d}laed4's [CITATION] lead in carefully computing
    //
    //   shiftedCenter = center - d(k).
    //
    const Real shiftedCenter = state.diagDiff / 2;

    // Again use LAPACK's {s,d}laed4's [CITATION] suggestion that the
    // diagonal entries minus the center roots be computed in a safe
    // (but somewhat obscured) manner.
    for( Int j=0; j<n; ++j ) 
    {
        state.dMinusShift(j) = (d(j) - d(k)) - shiftedCenter;
    }

    // Given the partition of the secular equation as
    //
    //   f(x) = (1/rho) + sum_{j=0}^{n-1} z(j)^2 / (d(j) - x)
    //        = (1/rho) + psi_k(x) + phi_k(x),
    //
    // where
    //
    //   psi_k(x) = sum_{j=0}^k       z(j)^2 / (d(j) - x),
    //   phi_k(x) = sum_{j=k+1}^{n-1} z(j)^2 / (d(j) - x),
    //
    // we follow the suggestion surrounding Eq's (40) and (41) of
    //
    //   Ren-Cang Li, "Solving Secular Equations Stably and Efficiently",
    //   LAPACK Working Note 89, 1993 [CITATION]
    //
    // and split off the last term of psi_k(x) and first term of phi_k(x)
    // so that the initial condition can be subsequently quickly computed.
    // We denote psi_k and phi_k evaluated at the center point with said 
    // terms removed as 'psiMinus' and 'phiMinus', respectively.
    state.psiMinus = zero;
    for( Int j=0; j<k; ++j )
        state.psiMinus += z(j)*z(j) / state.dMinusShift(j);
    Real phiMinus = zero; 
    for( Int j=k+2; j<n; ++j )
        phiMinus += z(j)*z(j) / state.dMinusShift(j);

    // The secular equation can now be expressed as
    //
    //   f(center) = (1/rho) + psiMinus + phiMinus +
    //       z(k)^2 / (d(k) - center) + z(k+1)^2 / (d(k+1) - center),
    //
    // where the top row will turn out to be the 'a' coefficient of a 
    // quadratic equation a x^2 + b x + c = 0 that we will solve to compute
    // the initial guess for the sought-after eigenvalue. But recall that
    // we should carefully compute (d(j) - center).
    const Real a = one/rho + state.psiMinus + phiMinus;
    const Real secularCenter = a +
      z(k)*z(k) / state.dMinusShift(k) + z(k+1)*z(k+1) / state.dMinusShift(k+1);

    if( secularCenter >= zero )
    {
        // The eigenvalue lives in (d(k), center), so we solve the 
        // quadratic equation
        //
        //   a + z(k)^2 / (d(k) - x) + z(k+1)^2 / (d(k+1) - x) = 0,
        //
        // directly for rootRelEst = x - d(k), which yields the quadratic
        // equation a rootRelEst^2 + b rootRelEst + c = 0, with
        //
        //   b = -a gap - (z(k)^2 + z(k+1)^2),
        //   c = z(k)^2 gap,
        //
        // with gap = d(k+1) - d(k).
        state.originOnLeft = true;
        state.origin = k;
        state.rootRelLowerBound = zero; 
        state.rootRelUpperBound = shiftedCenter;
        const Real bNeg = a*state.diagDiff + z(k)*z(k) + z(k+1)*z(k+1);
        const Real c = z(k)*z(k)*state.diagDiff;
        state.rootRelEst = SolveQuadraticMinus( a, bNeg, c, ctrl.negativeFix ); 
    }
    else
    {
        // The eigenvalue lives in [center, d(k+1)), so we solve the
        // quadratic equation
        //
        //   a + z(k)^2 / (d(k) - x) + z(k+1)^2 / (d(k+1) - x) = 0,
        //
        // directly for rootRelEst = x - d(k+1), which yields the quadratic
        // equation a rootRelEst^2 + b rootRelEst + c = 0, with
        //
        //   b = a gap - (z(k)^2 + z(k+1)^2),
        //   c = -z(k)^2 gap,
        //
        // with gap = d(k+1) - d(k).
        state.originOnLeft = false;
        state.origin = k+1;
        state.rootRelLowerBound = -shiftedCenter;
        state.rootRelUpperBound = 0; 
        const Real bNeg = -a*state.diagDiff + z(k)*z(k) + z(k+1)*z(k+1);
        const Real c = -z(k+1)*z(k+1)*state.diagDiff;
        state.rootRelEst = SolveQuadraticMinus( a, bNeg, c, ctrl.negativeFix );
    }
    if( ctrl.progress )
        Output
        ("Initial relative interval is [",state.rootRelLowerBound,",",
         state.rootRelUpperBound,"]");

    state.rootEst = state.rootRelEst + d(state.origin);
    for( Int j=0; j<n; ++j ) 
    {
        state.dMinusShift(j) = (d(j) - d(state.origin)) - state.rootRelEst;
    }

    EvaluateSecular( rho, z, state, ctrl.penalizeDerivative );
}
Exemplo n.º 20
0
 // output end of line
 void OutputEndl() { Output(wxT("\r\n")); }
Exemplo n.º 21
0
void SecularUpdate
( bool  initialize,
  Int   whichValue,
  const Matrix<Real>& d,
  const Real& rho,
  const Matrix<Real>& z,
        State<Real>& state,
        SecularEVDInfo& info,
  const SecularEVDCtrl<Real>& ctrl )
{
    DEBUG_CSE
    const Real zero(0);
    const Int n = d.Height();
    const Int k = whichValue;
    const Int origin = state.origin;
    Real eta;

    if( state.secular <= zero )
        state.rootRelLowerBound =
          Max( state.rootRelLowerBound, state.rootRelEst );
    else
        state.rootRelUpperBound =
          Min( state.rootRelUpperBound, state.rootRelEst );
    if( ctrl.progress )
        Output
        ("Relative interval is [",state.rootRelLowerBound,",",
         state.rootRelUpperBound,"]");

    if( state.useThreePoles )
    {
        // Use the "Hybrid Scheme" described in subsection 3.4 of LAWN 89
        // [CITATION] and implemented within {s,d}laed4 [CITATION].
 
        // Carefully compute
        //
        //   leftGap = d(origin-1) - rootEst, and
        //   rightGap = d(origin+1) - rootEst.
        //
        const Real leftGap = state.dMinusShift(origin-1);
        const Real rightGap = state.dMinusShift(origin+1);

        Real a;
        Matrix<Real> zCubic(3,1);
        if( state.alternateStrategy )
        {
            a = state.secularMinus - leftGap*state.psiMinusDeriv -
              rightGap*state.phiDeriv;
            zCubic(0) = leftGap*leftGap*state.psiMinusDeriv;
            zCubic(1) = z(origin)*z(origin);
            zCubic(2) = rightGap*rightGap*state.phiDeriv;
        }
        else
        {
            const Real doubleGap = d(origin+1) - d(origin-1);

            if( state.originOnLeft )
            {
                // Since the shift origin, m, is k, We will interpolate the
                // secular equation as
                //
                //  Q(x; a, s, S) = a + z(m-1)^2 / (d(m-1) - x) + 
                //                      z(m  )^2 / (d(m  ) - x) + 
                //                      S        / (d(m+1) - x),
                //
                // which can be effected by applying the Middle Way, the Fixed
                // Weight Method, or Borges/Gragg/Thornton/Warner's cubic scheme
                //  to
                //
                //   f_m(y) = f(y) - z(m)^2 / (d(m) - x).
                //
                // We balance between the Fixed Weight Method and the Middle
                // Way; their formulae for computing a are identical. In both
                // cases,
                // 
                //  a = f_m - rightGap*f'_m +
                //      (z(m-1)/leftGap)^2*(d(m+1)-d(m-1)).
                //
                // The computation of S primarily follows the Fixed Weight
                // Method but enforces the non-negativity of psi_{k-2}' when
                // computing
                //
                //   f'_{m-1,m}(y) = psi'_{m-2}(y) + phi'_m(y).
                //
                // The two subscripts on f denote the m-1 and m terms of the
                // secular equation being left out.
                //
                const Real leftRatio = z(origin-1) / leftGap;
                const Real leftDerivTerm = leftRatio*leftRatio;
                a =
                  (state.secularMinus-rightGap*state.secularMinusDeriv) +
                  leftDerivTerm*doubleGap;

                // We could either flip or clip here, but LAPACK tends to flip
                // and clips here, so we will follow suit so that requesting
                // flips leads to mirroring LAPACK.
                const Real psiDoubleMinusDeriv =
                  Max( state.psiMinusDeriv-leftDerivTerm, zero );
    
                zCubic(0) = z(origin-1)*z(origin-1);
                zCubic(1) = z(origin)*z(origin);
                zCubic(2) =
                  rightGap*rightGap*(psiDoubleMinusDeriv+state.phiDeriv);
            }
            else
            {
                // Since the shift origin, m, is k+1, we will interpolate the
                // secular equation as
                //
                //  Q(x; a, s, S) = a + s        / (d(m-1) - x) +
                //                      z(m)^2   / (d(m  ) - x) +
                //                      z(m+1)^2 / (d(m+1) - x),
                //
                // which can be effected by applying the Middle Way, the Fixed
                // Weight Method, or Borges/Gragg/Thornton/Warner's cubic scheme
                //  to
                //
                //   f_m(y) = f(y) - z(m)^2 / (d(m) - x).
                //
                // We balance between the Fixed Weight Method and the Middle
                // Way; their formulae for computing a are identical. In both
                // cases,
                // 
                //  a = f_m - leftGap*f'_m -
                //      (z(m+1)/rightGap)^2*(d(m+1)-d(m-1)),
                //
                // The computation of s primarily follows the Fixed Weight
                // Method but enforces the non-negativity of phi_{m+1}' when
                // computing
                //
                //   f'_{m,m+1}(y) = psi'_{m-1}(y) + phi'_{m+1}(y).
                //
                // The two subscripts on f denote the m and m+1 terms of the
                // secular equation being left out.
                //
                const Real rightRatio = z(origin+1) / rightGap;
                const Real mPlusDerivTerm = rightRatio*rightRatio;
                a =
                  (state.secularMinus-leftGap*state.secularMinusDeriv) -
                  mPlusDerivTerm*doubleGap;

                // We could either flip or clip here, but LAPACK tends to flip
                // and clips here, so we will follow suit so that requesting
                // flips leads to mirroring LAPACK.
                const Real phiMinusDeriv =
                  Max( state.phiDeriv-mPlusDerivTerm, zero );
            
                zCubic(0) = leftGap*leftGap*(state.psiMinusDeriv+phiMinusDeriv);
                zCubic(1) = z(origin)*z(origin);
                zCubic(2) = z(origin+1)*z(origin+1);
            }
        }
        Matrix<Real> dCubic(3,1);
        dCubic(0) = leftGap;
        dCubic(1) = state.dMinusShift(origin);
        dCubic(2) = rightGap;

        auto cubicInfo =
          CubicSecular
          ( initialize, state.originOnLeft, a, zCubic, dCubic, state.secular,
            eta, ctrl.cubicCtrl );
        info.numCubicIterations += cubicInfo.numIterations;
        if( cubicInfo.converged )
        {
            if( ctrl.progress )
                Output
                ("Cubic converged in ",cubicInfo.numIterations,
                 " iter's with eta=",eta);
        }
        else
        {
            // For some reason, LAPACK's {s,d}laed4 [CITATION] choose to fail
            // if the cubic iteration did not succeed, but {s,d}lasd4 [CITATION]
            // uses a recovery process analogous to what follows. We will part 
            // ways with LAPACK here and run the recovery process rather than
            // simply failing.
            if( ctrl.progress )
                Output("Cubic did *not* converge");
            ++info.numCubicFailures;
            state.useThreePoles = false;
            const Real kGap = state.dMinusShift(k);
            const Real kp1Gap = state.dMinusShift(k+1);
            Real a;
            if( state.originOnLeft )
            {
                const Real temp = z(k) / kGap;
                a = state.secular - kp1Gap*state.secularDeriv +
                  state.diagDiff*(temp*temp);
            }
            else
            {
                const Real temp = z(k+1) / kp1Gap;
                a = state.secular - kGap*state.secularDeriv +
                  state.diagDiff*(temp*temp);
            }
            Real bNeg = (kGap+kp1Gap)*state.secular -
              kGap*kp1Gap*state.secularDeriv;
            const Real c = kGap*kp1Gap*state.secular;
            if( a == zero && bNeg == zero )
            {
                // a x^2 + b x + c = 0 has collapsed to c = 0, which is
                // nonsense. Follow LAPACK's {s,d}laed4 [CITATION] in handling
                // this breakdown.
                if( state.originOnLeft )
                {
                    bNeg = z(k)*z(k) + kp1Gap*kp1Gap*state.secularMinusDeriv;
                }
                else
                {
                    bNeg = z(k+1)*z(k+1) + kGap*kGap*state.secularMinusDeriv; 
                }
            }
            eta = SolveQuadraticMinus( a, bNeg, c, ctrl.negativeFix );
        }
    }
    else
    {
        // Use one step of the Fixed Weight Method, as described in subsection
        // 3.2 of LAPACK Working Note 89 [CITATION]. We solve the quadratic
        // equation implied by the osculatory interpolation of the secular
        // equation as
        //
        //   Q(x; a, s, S) = a + s / (d(k) - x) + S / (d(k+1) - x).
        //
        // As noted after Proposition 3 of LAWN 89, the iteration formula does
        // not depend upon either s or S!

        // Safely compute the distance from our current eigenvalue estimate to
        // the surrounding grid points, d(k)^2 and d(k+1)^2.
        const Real kGap = state.dMinusShift(k);
        const Real kp1Gap = state.dMinusShift(k+1);

        Real a;
        if( state.alternateStrategy )
        {
            // TODO(poulson): Document this strategy
            if( state.originOnLeft )
            {
                const Real temp = z(k) / kGap;
                a = state.secular - kGap*(state.psiMinusDeriv+temp*temp) -
                  kp1Gap*state.phiDeriv;
            }
            else
            {
                const Real temp = z(k+1) / kp1Gap;
                a = state.secular - kGap*state.psiMinusDeriv -
                  kp1Gap*(state.phiDeriv+temp*temp);
            }
        }
        else
        {
            if( state.originOnLeft )
            {
                // Apply Eq'ns (32) through (34) from LAWN 89 [CITATION] to set
                //
                //  a = f - kp1Gap f' + (z(k)^2/kGap^2) (d(k+1) - d(k)),
                //
                // and implicitly set
                //
                //  s = z(k)^2,
                //  S = kp1Gap^2 (f' - z(k)^2/kGap^2),
                //
                // where y is the current estimate of the k'th eigenvalue and 
                // f and f' are the secular equation and its derivative
                // evaluated at y.
                const Real temp = z(k) / kGap;
                a = state.secular - kp1Gap*state.secularDeriv +
                  (temp*temp)*state.diagDiff;
            }
            else
            {
                // Apply Eq'ns (35) through (37) from LAWN 89 [CITATION] to set
                //
                //  a = f - kGap f' - (z(k+1)^2/kp1Gap^2) (d(k+1)^2 - d(k)^2),
                //
                // and implicitly set
                //
                //  s = kGap^2 (f' - z(k+1)^2/kp1Gap^2),
                //  S = z(k+1)^2.
                //
                const Real temp = z(k+1) / kp1Gap;
                a = state.secular - kGap*state.secularDeriv -
                  (temp*temp)*state.diagDiff;
            }
        }

        // See Proposition 3 from LAWN 89 [CITATION] for these formulae for the
        // coefficients of the quadratic equation a x^2 - bNeg x + c = 0.
        Real bNeg = (kGap+kp1Gap)*state.secular -
          kGap*kp1Gap*state.secularDeriv;
        Real c = kGap*kp1Gap*state.secular;

        if( a == zero && bNeg == zero )
        {
            // a eta^2 + b eta + c = 0 has collapsed to c = 0, which is
            // nonsensical to solve for eta. We therefore follow the lead of
            // LAPACK's {s,d}laed4 [CITATION] and use a mysterious patch-up.
            //
            // TODO(poulson): Provide motivation for these formulae.
            if( state.alternateStrategy )
            {
                if( state.originOnLeft )
                {
                    bNeg = z(k)*z(k) + kGap*kGap*state.psiMinusDeriv +
                           kp1Gap*kp1Gap*state.phiDeriv;
                }
                else
                {
                    bNeg = z(k+1)*z(k+1) + kGap*kGap*state.psiMinusDeriv +
                           kp1Gap*kp1Gap*state.phiDeriv;
                }
            }
            else
            {
                if( state.originOnLeft )
                    bNeg = z(k)*z(k) + kp1Gap*kp1Gap*state.secularMinusDeriv;
                else
                    bNeg = z(k+1)*z(k+1) + kGap*kGap*state.secularMinusDeriv;
            }
        }
        eta = SolveQuadraticMinus( a, bNeg, c, ctrl.negativeFix );
    }

    if( state.secular*eta >= zero )
    {
        if( ctrl.progress )
            Output("Falling back to Newton step");
        // The current update does not move in the right direction, so fall
        // back to a small Newton step (as the derivative is likely large).
        eta = -state.secular / state.secularDeriv;
    }

    // Since rootRelEst = rootEst - d(origin), the following sets
    // rootRelEstProp = rootEstProp - d(origin).
    const Real rootRelEstProp = state.rootRelEst + eta;
    if( rootRelEstProp > state.rootRelUpperBound ||
        rootRelEstProp < state.rootRelLowerBound )
    {
        if( ctrl.progress )
            Output("Stepped out of bounds");
        // We again follow LAPACK's {s,d}laed4 for how to handle this breakdown

        if( state.secular < zero )
        {
            // Since the secular equation implies that the root is to the right
            // of the un-updated estimate, but our update pushed us out of
            // bounds, we default to the update pushing us to the center of the
            // feasible domain, [rootRelEst, rootRelUpperBound).
            eta = (state.rootRelUpperBound - state.rootRelEst) / 2;
        }
        else
        {
            // Since the secular equation implies that the root is to the left
            // of the un-updated estimate, but our update pushed us out of
            // bounds, we default to the update being in the center of the
            // feasible domain, (rootRelLowerBound,rootRelEst].
            eta = (state.rootRelLowerBound - state.rootRelEst) / 2;
        }
    }

    state.rootEst += eta;
    state.rootRelEst += eta;
    state.secularOld = state.secular;
    for( Int j=0; j<n; ++j )
    {
        state.dMinusShift(j) -= eta;
    }
    EvaluateSecular( rho, z, state, ctrl.penalizeDerivative );
}
Exemplo n.º 22
0
finalout()
{

INT c ;
INT bbtop, bbbottom, bbleft, bbright ;

/* dump the results of the placement to graphics file */
G( graphics_dump() ) ;
G( TWsetMode(1) ) ;
G( draw_the_data() ) ;
G( TWsetMode(0) ) ;


/* we known wire area at this point don't need to estimate */
turn_wireest_on(FALSE) ;

/* let the user know which pins we couldn't place */
set_pin_verbosity( TRUE ) ;

/* before channel graph generation and global routing let use tweak */
/* placement if desired */
if( doGraphicsG && wait_for_userG ){
    G( TWmessage( "TimberWolfMC waiting for your response" ) ) ;
    G( process_graphics() ) ;
} 

savewolf( TRUE ) ;  /* for debug purposes force save to occur */
if( scale_dataG > 1 ){
    /* end of the line for scaled case - 
	will return to parent to continue using saved placement. */
    closegraphics() ;
    YexitPgm( PGMOK ) ;
}
grid_cells() ;      /* force cells to grid locations */
compact(VIOLATIONSONLY); /* remove cell overlap */

/* if this is a partitioning run determine row placement */
if( doPartitionG && !(quickrouteG) ){
    set_determine_side( FALSE ) ;  /* allow SC to pick side */
    G( set_graphic_context( PARTITION_PLACEMENT ) ) ;
    config_rows() ;
    print_paths() ; /* print path information */
    Output( 0 ) ;
    return ;
}
/* do final placement of pads using virtual core to insure pads */
/* are outside of core */
setVirtualCore( TRUE ) ;
placepads() ;

/* before channel graph generation and global routing let use tweak */
/* placement if desired */
check_graphics() ;

if( !scale_dataG ){ 
    /* reload bins to get new overlap penalty */
    loadbins(FALSE) ; /* wireArea not known */
}
prnt_cost( "\nFINAL PLACEMENT RESULTS AFTER VIOLATION REMOVAL ARE:\n" ) ;

print_paths() ; /* print path information */
Output( 0 ) ;

if( doCompactionG > 0 || quickrouteG ) {
    gmain( CHANNELGRAPH ) ;
    rmain( NOCONSTRAINTS ) ;
    gmain( UPDATE_ROUTING ) ;
    adapt_wire_estimator() ;
    check_graphics() ;

    if( quickrouteG ){
	return ;
    }

    for( c = 1 ; c <= doCompactionG ; c++ ) {

	funccostG = findcost() ;
	sprintf(YmsgG,"\n\nCompactor Pass Number: %d begins with:\n", c ) ;
	prnt_cost( YmsgG ) ;

	wirecosts() ;


	grid_cells() ;      /* force cells to grid locations */
	compact(COMPACT);   /* remove white space */
	reorigin() ;
	check_graphics() ;

	sprintf(YmsgG,"\n\nCompactor Pass Number: %d after cost:\n", c ) ;
	prnt_cost( YmsgG ) ;

	Output( c ) ;

	gmain( CHANNELGRAPH ) ;

	if( c == doCompactionG ){
	    rmain( CONSTRAINTS ) ;
	} else {
	    rmain( NOCONSTRAINTS ) ;
	    gmain( UPDATE_ROUTING ) ;
	    adapt_wire_estimator() ;
	    check_graphics() ;
	}

    } /* end compaction - global route loop */

} else {
    if( doChannelGraphG ) {
	gmain( CHANNELGRAPH ) ;
    }
    if( doGlobalRouteG ) {
	rmain( CONSTRAINTS ) ;
    }
}


prnt_cost("\nTIMBERWOLFMC FINAL RESULTS ARE:\n" ) ;

return ;
} /* end finalout */
// Blocks until decoded sample is produced by the deoder.
nsresult
GonkVideoDecoderManager::Output(int64_t aStreamOffset,
                                RefPtr<MediaData>& aOutData)
{
  aOutData = nullptr;
  status_t err;
  if (mDecoder == nullptr) {
    GVDM_LOG("Decoder is not inited");
    return NS_ERROR_UNEXPECTED;
  }
  err = mDecoder->Output(&mVideoBuffer, READ_OUTPUT_BUFFER_TIMEOUT_US);

  switch (err) {
    case OK:
    {
      RefPtr<VideoData> data;
      nsresult rv = CreateVideoData(aStreamOffset, getter_AddRefs(data));
      if (rv == NS_ERROR_NOT_AVAILABLE) {
        // Decoder outputs a empty video buffer, try again
        return NS_ERROR_NOT_AVAILABLE;
      } else if (rv != NS_OK || data == nullptr) {
        GVDM_LOG("Failed to create VideoData");
        return NS_ERROR_UNEXPECTED;
      }
      aOutData = data;
      return NS_OK;
    }
    case android::INFO_FORMAT_CHANGED:
    {
      // If the format changed, update our cached info.
      GVDM_LOG("Decoder format changed");
      if (!SetVideoFormat()) {
        return NS_ERROR_UNEXPECTED;
      }
      return Output(aStreamOffset, aOutData);
    }
    case android::INFO_OUTPUT_BUFFERS_CHANGED:
    {
      if (mDecoder->UpdateOutputBuffers()) {
        return Output(aStreamOffset, aOutData);
      }
      GVDM_LOG("Fails to update output buffers!");
      return NS_ERROR_FAILURE;
    }
    case -EAGAIN:
    {
//      GVDM_LOG("Need to try again!");
      return NS_ERROR_NOT_AVAILABLE;
    }
    case android::ERROR_END_OF_STREAM:
    {
      GVDM_LOG("Got the EOS frame!");
      RefPtr<VideoData> data;
      nsresult rv = CreateVideoData(aStreamOffset, getter_AddRefs(data));
      if (rv == NS_ERROR_NOT_AVAILABLE) {
        // For EOS, no need to do any thing.
        return NS_ERROR_ABORT;
      }
      if (rv != NS_OK || data == nullptr) {
        GVDM_LOG("Failed to create video data");
        return NS_ERROR_UNEXPECTED;
      }
      aOutData = data;
      return NS_ERROR_ABORT;
    }
    case -ETIMEDOUT:
    {
      GVDM_LOG("Timeout. can try again next time");
      return NS_ERROR_UNEXPECTED;
    }
    default:
    {
      GVDM_LOG("Decoder failed, err=%d", err);
      return NS_ERROR_UNEXPECTED;
    }
  }

  return NS_OK;
}
Exemplo n.º 24
0
void    Result(uchar  bT) {
  InitPushCRC();
  PushChar(bT);

  Output(1);
}
Exemplo n.º 25
0
int main( int argc, char **argv )
/*******************************/
{
    FILE        *fp;
    char        drive[ _MAX_DRIVE ];
    char        dir[ _MAX_DIR ];
    char        fname[ _MAX_FNAME ];
    char        ext[ _MAX_EXT ];
    char        file[ _MAX_PATH ];
    char        *fn;
    int         i;
    bool        list_file;
    FILE        *fh;
    bool        is_intel;

    OutputInit();
    OutputSetFH( stdout );

    Descriptions = FALSE;
    InterpretComent = TRUE;
    TranslateIndex = FALSE;
    list_file = FALSE;
    is_intel = FALSE;
    quiet = FALSE;
    for( i = 1; i < argc; ++i ) {
        if( argv[i][0] == '-' ) {
            switch( tolower( argv[i][1] ) ) {
            case 'l':
                list_file = TRUE;
                break;
            case 'd':
                Descriptions = TRUE;
                break;
            case 'c':
                InterpretComent = FALSE;
                break;
            case 'r':
                if( strnicmp( argv[i] + 1, "rec=", 4 ) == 0 ) {
                    if( rec_count < 10 ) {
                        if( isdigit( argv[i][5] ) ) {
                            rec_type[ rec_count++ ] = atoi( argv[i] + 5 );
                        } else {
                            rec_type[ rec_count++ ] = RecNameToNumber( argv[i] + 5 );
                        }
                    } else {
                        Output( "Maximum 10 record type allowed." CRLF );
                        OutputFini();
                    }
                } else {
                    DumpRaw = TRUE;
                }
                break;
            case 'i':
                is_intel = FALSE;
                break;
            case 'q':
                quiet = TRUE;
                break;
            case 't':
                TranslateIndex = TRUE;
                break;
            default:
                usage();
            }
        } else {
            break;
        }
    }
    if( i == argc ) {
        usage();
    }

    ShowProductInfo();
    for( ; i < argc; ++i ) {
        _splitpath( argv[i], drive, dir, fname, ext );
        if( ext[0] == 0 ) {
            _makepath( file, drive, dir, fname, OBJSUFFIX );
            fn = file;
        } else {
            fn = argv[i];
        }
        fp = fopen( fn, "rb" );
        if( fp == NULL ) {
            Output( "Cannot open '%s' for reading" CRLF, fn );
            leave( 20 );
        }
        if( list_file ) {
            _makepath( file, drive, dir, fname, LSTSUFFIX );
            fh = fopen( file, "w" );
            if( fh == NULL ) {
                Output( "Cannot open '%s' for writing" CRLF, file );
                leave( 20 );
            }
            OutputSetFH( fh );
        }
        ProcFile( fp, is_intel );
        fclose( fp );
        OutputSetFH( stdout );  /* does fclose() if necessary */
    }
    leave( 0 );
    return( 0 );  // for the less intelligent compilers
}
Exemplo n.º 26
0
void AOCS(double AOCS_Xupdata[19],double AOCS_Xinitial[14],int N,double AOCS_Y0[100],unsigned char AOCS_Flag0[6],double AOCS_Y[],unsigned char AOCS_Flag[9])
{
	int i;
	double Worbity_CHK,nine_CHK[9];
	all2Xupdate(AOCS_Xupdata,&Time,Wwheel,ThTime); //输出飞轮转速[4]和推力器开启时间[14]
	all2Xinitial(AOCS_Xinitial,Y,Wib,Quatib,&Msat); // 输出卫星位置速度[6],本体相对惯性系在本体系下的姿态角速度[3],本体系相对惯性系的四元数[4],卫星质量[1]

	/*质量更新模型*/
	MsatUPDATE(&Msat,ACS_DMsat,ThTime); //返回质量

	/*环境力矩*/
	//输入为卫星时间,太阳黄经,黄赤交角; 输出为格林尼治视恒星时角,太阳矢量[3],测量系相对惯性系的姿态四元数[4]
	SunVectori(Time,&Yousun,&Aisun,&Jingdu_GreenWitch_inertia, SunInertia, Quatis);/*太阳矢量*/
	//输入为太阳矢量,本体系相对惯性系的四元数[3],太阳帆板安装矩阵[3][3],太阳帆板表面反射系数=0.5,太阳光照射面积=5,
	//太阳光压=9e-6,太阳光压压心到卫星质心的矢径[3],输出本体系下太阳光压力[3]和光压力矩[3]
	SunTorque(SunInertia,Quatib,ACS_Psunb,ACS_niu,ACS_Ssun,ACS_Psun,ACS_Cps,F_Sun,Td_Sun);   /*太阳光压力矩模型*/

	/*执行机构*/
	//输入为推力器开启时间[14],推力器推力系数[14],推力器组喷嘴中心的方向余弦角[14][3],推力器组偏心矢量[14][3]
	//输出本体系下推力器推力[3]和力矩[3]
	Fthrust(ThTime,ACS_KFthurst,ACS_cosattis,ACS_Cattis, F_Th, T_Th);
	//输入为飞轮转速[4],飞轮转动惯量[4]为什么是一维矩阵? 飞轮安装矩阵[4][3], 输出本体系下飞轮组产生的力矩[3]
	Wheel(Wwheel,ACS_Jwheel,ACS_Pwheelb, Twheelb);
	Magnetic(Bci,Quatib,Mags,ACS_PMagb, Tmag);

	/*轨道递推*/
	for(i=0;i<3;i++)
        Fb[i]=F_Th[i]+F_aero[i]+F_Sun[i];/*计算本体系下卫星合外力*/
	orbJ2_rk4(Y,H,Fb,Quatib,Msat); /*轨道动力学模型,利用龙格库塔法递推,得到下一时刻的位置和速度,需要给出初始位置和速度*/
	PV2Six(Y,nine,&Worbity);  /*位置速度转换六根数模型,由位置和速度计算轨道六要素*/
	PV2Six_OLD(Y,nine_CHK,&Worbity_CHK); /*nine[9]:0A,1E,2SI,3DW,4SW,5DM,6SU,7theta,8n*/
	Iner2orbitquat(nine[3],nine[2],nine[6],Quatio);

	/*姿态递推*/
	QuatTatti_rk4(H,Wib,Quatib);/*姿态运动学,递推下一时刻的姿态四元素Qib  */
	for(i=0;i<3;i++)
		Tb[i]=Twheelb[i]+T_Th[i]+Td_geomagnetic[i]+Td_gravity[i]+Td_aero[i]+Td_Sun[i]+Tmag[i];   /*计算卫星合力矩*/
	//输入飞轮转动惯量[4],飞轮转速[4]; 输出飞轮角动量[4]
	WheelMomentum(ACS_Jwheel,Wwheel,MomentumWheel);    /*飞轮角动量计算*/
	//输入飞轮角动量NMS[4](不知道是啥?),飞轮安装矩阵[4][3]; 输出飞轮系统角动量[4]
	WheelSysToThree(MomentumWheel,ACS_Pwheelb,Hwheel);  /*飞轮系统角动量计算 	*/
	//输入飞轮系统角动量,本体相对惯性系的角速度[3],卫星转动惯量[3][3]; 输出卫星角动量[3]
	formHB(Hwheel,Wib,ACS_IBf,Hbody);                /*卫星角动量计算*/
	//输入积分步长[1],卫星角动量[3],卫星合力矩[3],卫星转动惯量[3][3]; 输出本体系相对惯性系的角速度[3]
	BiasattiDynamic_rk4(H,Hbody,Tb,ACS_IBf,Wib);   /*姿态动力学,带轮控系统的刚体动力学,递推下一时刻的角速度Wib*/

	/*天体矢量*/
	//输入为卫星时间+积分步长,太阳黄经,黄赤交角, 输出惯性系下的太阳矢量[3],太阳系相对惯性系的四元数[4],格林尼治视恒星时角[1]*/
	SunVectori(Time+H,&Yousun,&Aisun,&Jingdu_GreenWitch_inertia,SunInertia,Quatis);  /*太阳矢量模型*/
	//输入卫星时间+积分步长, 卫星位置速度[6]; 输出惯性系下月球矢量[3]
	MoonVectori(Time+H,Y,Mooni); /*月球矢量模型*/
	//输入卫星位置速度[6]; 输出惯性系下地球矢量[3]
	EarthVectori(Y,Earthi); /*地心矢量模型*/
    //输入卫星位置速度[6],惯性系下太阳矢量[3], 输出地影标志位:EshadowFlag=1时进入地影;
	EarthShadow(Y,SunInertia,&EshadowFlag);/*地影计算*/

	/*敏感器*/
    //输入太阳矢量[3],本体系相对惯性系的四元数[4],数字太敏1的安装矩阵[3][3],数字太敏1的视场测量极值[1],数字太敏1的噪声系数[1],地影标志位,数字太敏1测量有效标志位
	//输出理论值和带噪声值:太阳矢量在测量系yz和xz平面上的投影分别与z轴的夹角
	Fsun(SunInertia,Quatib,ACS_PFsunb1,ACS_Fsun1Limit,ACS_Fsun1R,EshadowFlag,&Fsun1Flag,&Fsun1out0,&Fsun1out);  /*数字太阳敏感器1测量模型*/
	Fsun(SunInertia,Quatib,ACS_PFsunb2,ACS_Fsun2Limit,ACS_Fsun2R,EshadowFlag,&Fsun2Flag,&Fsun2out0,&Fsun2out);  /*数字太阳敏感器2测量模型*/
	//输入太阳矢量,地球矢量,月球矢量,星敏A光轴指向分别与太阳、地球、月球矢量夹角的临界值[3](单位是度°),星敏A到星体的旋转四元数[4]
	//本体系相对惯性系的四元数[4],星敏A噪声系数[3],星敏A测量有效标志位[1]; 输出星敏A/B安装
	quatstar(SunInertia,Earthi,Mooni,ACS_StarALimit,ACS_StarsbA,Quatib,ACS_quatstarRA,&StarAFlag,QuatsiA0,QuatsiA);    /*星敏感器A测量模型,输出测量四元素*/
	quatstar(SunInertia,Earthi,Mooni,ACS_StarBLimit,ACS_StarsbB,Quatib,ACS_quatstarRB,&StarBFlag,QuatsiB0,QuatsiB);    /*星敏感器B测量模型,输出测量四元素*/
	Gyro(Wib,ACS_Pgyrob1,ACS_NoGyro1,ACS_GyroR1,ACS_GyroRC1,Wgyro10,Wgyro1);        /*平台陀螺测量模型,输出测量角速度*/
	Gyro(Wib,ACS_Pgyrob2,ACS_NoGyro2,ACS_GyroR2,ACS_GyroRC2,Wgyro20,Wgyro2);        /*光纤陀螺测量模型,输出测量角速度*/
	Acceler(F_Th,F_aero,F_Sun,Msat,ACS_Psb,ACS_AccelerR,ACS_AccelerRC,as0,as);   /*加速度计测量模型,输出测量角加速度*/
	Magnet(Bci,Quatib,ACS_PbBB,ACS_MagoutR,Magout0,Magout);  /*磁强计模型,输出测量磁场强度*/

    Distance_in_Radar(r1,r2, &Distance);
    Angel_in_Camera(r1,r2,ACS_StarsbA,Quatib, &Theta_yz, &Theta_yx);

	/*系统输出*/
	Output(AOCS_Y0,AOCS_Flag0,AOCS_Y,AOCS_Flag);

}
Exemplo n.º 27
0
//Paragraph Segment and POS Tagging
bool CResult::ParagraphProcessing(char *sParagraph,char *sResult)
{
	char *sSentence,sChar[3];
	char *sSentenceResult;
	unsigned int nLen=strlen(sParagraph)+13;
	sSentence=new char[nLen];//malloc buffer
	sSentenceResult=new char[nLen*3];//malloc buffer
	sSentence[0]=0;
	unsigned int nPosIndex=0,nParagraphLen=strlen(sParagraph),nSentenceIndex=0;
	sChar[2]=0;
	sResult[0]=0;//Init the result
	bool bFirstIgnore=true;
	strcpy(sSentence,SENTENCE_BEGIN);//Add a sentence begin flag
	while(nPosIndex<nParagraphLen)
	{//Find a whole sentence which separated by ! . \n \r
		sChar[0]=sParagraph[nPosIndex];//Get a char
		sChar[1]=0;
		if(sParagraph[nPosIndex]<0)
		{//double byte char
			nPosIndex+=1;
			sChar[1]=sParagraph[nPosIndex];
		}
		nPosIndex+=1;
/*
#define  SEPERATOR_C_SENTENCE "。!?:;…"
#define  SEPERATOR_C_SUB_SENTENCE "、,()“”‘’"
#define  SEPERATOR_E_SENTENCE "!?:;"
#define  SEPERATOR_E_SUB_SENTENCE ",()\042'"
#define  SEPERATOR_LINK "\n\r  "
*/
		if(CC_Find(SEPERATOR_C_SENTENCE,sChar)||CC_Find(SEPERATOR_C_SUB_SENTENCE,sChar)||strstr(SEPERATOR_E_SENTENCE,sChar)||strstr(SEPERATOR_E_SUB_SENTENCE,sChar)||strstr(SEPERATOR_LINK,sChar))
		{//Reach end of a sentence.Get a whole sentence
			if(!strstr(SEPERATOR_LINK,sChar))//Not link seperator
			{
				strcat(sSentence,sChar);
			}
			if(sSentence[0]!=0&&strcmp(sSentence,SENTENCE_BEGIN)!=0)
			{
				if(!strstr(SEPERATOR_C_SUB_SENTENCE,sChar)&&!strstr(SEPERATOR_E_SUB_SENTENCE,sChar))
					strcat(sSentence,SENTENCE_END);//Add sentence ending flag

				Processing(sSentence,1);//Processing and output the result of current sentence.
				Output(m_pResult[0],sSentenceResult,bFirstIgnore);//Output to the imediate result
				//bFirstIgnore=true;
				strcat(sResult,sSentenceResult);//Store in the result buffer
			}
			if(strstr(SEPERATOR_LINK,sChar))//Link the result with the SEPERATOR_LINK
			{
				strcat(sResult,sChar);
				strcpy(sSentence,SENTENCE_BEGIN);//Add a sentence begin flag

				//sSentence[0]=0;//New sentence, and begin new segmentation
				//bFirstIgnore=false;
			}
			else if(strstr(SEPERATOR_C_SENTENCE,sChar)||strstr(SEPERATOR_E_SENTENCE,sChar))
			{
				strcpy(sSentence,SENTENCE_BEGIN);//Add a sentence begin flag
				//sSentence[0]=0;//New sentence, and begin new segmentation
				//bFirstIgnore=false;
			}
			else
			{
				strcpy(sSentence,sChar);//reset current sentence, and add the previous end at begin position
			}
		}
		else //Other chars and store in the sentence buffer
			strcat(sSentence,sChar);
	}
	if(sSentence[0]!=0&&strcmp(sSentence,SENTENCE_BEGIN)!=0)
	{
		strcat(sSentence,SENTENCE_END);//Add sentence ending flag
		Processing(sSentence,1);//Processing and output the result of current sentence.
		Output(m_pResult[0],sSentenceResult,bFirstIgnore);//Output to the imediate result
		strcat(sResult,sSentenceResult);//Store in the result buffer
	}
	delete []  sSentence;//FREE sentence buffer 	
	delete []  sSentenceResult;//free buffer
	return true;
}
Exemplo n.º 28
0
int main(int argc, char* argv[])
{
  char exePath[MAXPATHLEN];

  nsresult rv = mozilla::BinaryPath::Get(argv[0], exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't calculate the application directory.\n");
    return 255;
  }

  char *lastSlash = strrchr(exePath, XPCOM_FILE_PATH_SEPARATOR[0]);
  if (!lastSlash || (lastSlash - exePath > MAXPATHLEN - sizeof(XPCOM_DLL) - 1))
    return 255;

  strcpy(++lastSlash, XPCOM_DLL);

  int gotCounters;
#if defined(XP_UNIX)
  struct rusage initialRUsage;
  gotCounters = !getrusage(RUSAGE_SELF, &initialRUsage);
#elif defined(XP_WIN)
  // GetProcessIoCounters().ReadOperationCount seems to have little to
  // do with actual read operations. It reports 0 or 1 at this stage
  // in the program. Luckily 1 coincides with when prefetch is
  // enabled. If Windows prefetch didn't happen we can do our own
  // faster dll preloading.
  IO_COUNTERS ioCounters;
  gotCounters = GetProcessIoCounters(GetCurrentProcess(), &ioCounters);
  if (gotCounters && !ioCounters.ReadOperationCount)
#endif
  {
      XPCOMGlueEnablePreload();
  }


  rv = XPCOMGlueStartup(exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XPCOM.\n");
    return 255;
  }
  // Reset exePath so that it is the directory name and not the xpcom dll name
  *lastSlash = 0;

  rv = XPCOMGlueLoadXULFunctions(kXULFuncs);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XRE functions.\n");
    return 255;
  }

#ifdef XRE_HAS_DLL_BLOCKLIST
  XRE_SetupDllBlocklist();
#endif

  if (gotCounters) {
#if defined(XP_WIN)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_OPS,
                            int(ioCounters.ReadOperationCount));
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_TRANSFER,
                            int(ioCounters.ReadTransferCount / 1024));
    IO_COUNTERS newIoCounters;
    if (GetProcessIoCounters(GetCurrentProcess(), &newIoCounters)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_OPS,
                              int(newIoCounters.ReadOperationCount - ioCounters.ReadOperationCount));
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_TRANSFER,
                              int((newIoCounters.ReadTransferCount - ioCounters.ReadTransferCount) / 1024));
    }
#elif defined(XP_UNIX)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_HARD_FAULTS,
                            int(initialRUsage.ru_majflt));
    struct rusage newRUsage;
    if (!getrusage(RUSAGE_SELF, &newRUsage)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_HARD_FAULTS,
                              int(newRUsage.ru_majflt - initialRUsage.ru_majflt));
    }
#endif
  }

  int result;
  {
    ScopedLogging log;
    result = do_main(argc, argv);
  }

  XPCOMGlueShutdown();
  return result;
}
Exemplo n.º 29
0
/*
 * StartProg - start sampling a program
 */
void StartProg( char *cmd, char *prog, char *full_args, char *dos_args )
{
    DWORD       code;
    DWORD       tid;
    CONTEXT     con;
    BOOL        waiting_for_first_bp;
    SIZE_T      len;
    DWORD       continue_how;
    BOOL        rc;
    seg_offset  where;
    DWORD       ttid;
    HANDLE      tth;

    cmd = cmd;

    strcpy( utilBuff, prog );
    strcat( utilBuff, " " );
    strcat( utilBuff, full_args );

    loadProg( prog, utilBuff );
    tid = debugEvent.dwThreadId;

    tth = CreateThread( NULL, 1024, TimerThread, NULL, 0, &ttid );
    if( !tth ) {
        internalError( MsgArray[MSG_SAMPLE_3 - ERR_FIRST_MESSAGE] );
    }
    /* attempt to ensure that we can get all of our samples in one shot */
    SetThreadPriority( tth, THREAD_PRIORITY_TIME_CRITICAL );

    Output( MsgArray[MSG_SAMPLE_1 - ERR_FIRST_MESSAGE] );
    Output( prog );
    Output( "\r\n" );

    waiting_for_first_bp = TRUE;
    continue_how = DBG_CONTINUE;

    for( ;; ) {
        ContinueDebugEvent( taskPid, tid, continue_how );
        rc = WaitForDebugEvent( &debugEvent, INFINITE );
        continue_how = DBG_CONTINUE;
        tid = debugEvent.dwThreadId;
        switch( debugEvent.dwDebugEventCode ) {
        case EXCEPTION_DEBUG_EVENT:
            code = debugEvent.u.Exception.ExceptionRecord.ExceptionCode;
            switch( code ) {
            case STATUS_SINGLE_STEP:
                if( timeOut ) {
                    myGetThreadContext( tid, &con );
                    RecordSample( con.Eip, con.SegCs, tid );
                    timeOut = FALSE;
                }
                break;
            case STATUS_BREAKPOINT:
                if( !waiting_for_first_bp ) {
                    myGetThreadContext( tid, &con );
                    con.Eip--;
                    if( (con.Edx & 0xffff) != 0 ) {    /* this is a mark */
                        ReadProcessMemory( processHandle, (LPVOID)con.Eax, utilBuff, BUFF_SIZE - 1, len );
                        utilBuff[len] = '\0';
                        where.segment = con.SegCs;
                        where.offset = con.Eip;
                        WriteMark( utilBuff, where );
                    } else {            /* this passes CommonAddr */
                        commonAddr.segment = con.Ecx & 0xffff;
                        commonAddr.offset = con.Ebx;
                    }
                } else {
                    waiting_for_first_bp = FALSE;
                }
                break;
            case STATUS_DATATYPE_MISALIGNMENT:
            case STATUS_ACCESS_VIOLATION:
            case STATUS_IN_PAGE_ERROR:
            case STATUS_NO_MEMORY:
            case STATUS_ILLEGAL_INSTRUCTION:
            case STATUS_NONCONTINUABLE_EXCEPTION:
            case STATUS_INVALID_DISPOSITION:
            case STATUS_ARRAY_BOUNDS_EXCEEDED:
            case STATUS_FLOAT_DENORMAL_OPERAND:
            case STATUS_FLOAT_DIVIDE_BY_ZERO:
            case STATUS_FLOAT_INVALID_OPERATION:
            case STATUS_FLOAT_OVERFLOW:
            case STATUS_FLOAT_STACK_CHECK:
            case STATUS_FLOAT_UNDERFLOW:
            case STATUS_INTEGER_DIVIDE_BY_ZERO:
            case STATUS_INTEGER_OVERFLOW:
            case STATUS_PRIVILEGED_INSTRUCTION:
            case STATUS_STACK_OVERFLOW:
            case STATUS_CONTROL_C_EXIT:
                if( debugEvent.u.Exception.dwFirstChance ) {
                    continue_how = DBG_EXCEPTION_NOT_HANDLED;
                } else {
                    Output( MsgArray[MSG_SAMPLE_4 - ERR_FIRST_MESSAGE] );
                    Output( "\r\n" );
                    doneSample = TRUE;
                    TerminateProcess( processHandle, 0 );
                    report();
                    return;
                }
                break;
            default:
                continue_how = DBG_EXCEPTION_NOT_HANDLED;
                break;
            }
            break;
        case LOAD_DLL_DEBUG_EVENT:
            if( GetDllName( &debugEvent.u.LoadDll, utilBuff, sizeof( utilBuff ) ) ) {
                codeLoad( debugEvent.u.LoadDll.hFile,
                            (DWORD) debugEvent.u.LoadDll.lpBaseOfDll,
                            utilBuff,
                            SAMP_CODE_LOAD );
            }
            break;
        case CREATE_THREAD_DEBUG_EVENT:
            newThread( debugEvent.dwThreadId, debugEvent.u.CreateThread.hThread );
            break;
        case EXIT_THREAD_DEBUG_EVENT:
            deadThread( debugEvent.dwThreadId );
            break;
        case EXIT_PROCESS_DEBUG_EVENT:
            doneSample = TRUE;
//          TerminateProcess( processHandle, 0 ); - already gone!!
            report();
            return;
        }
    }

} /* StartProg */
Exemplo n.º 30
0
int main(void)
{
    struct TrackedResources *crs = NULL;
    struct TrackedResources *start_rs = NULL;
    BOOL quitme = FALSE;
    int numlines = 30;
    struct Task *this;
    ULONG  portsig;
    struct MsgPort *port;

    this = FindTask(NULL);

    port = CreateMsgPort();
    if (!port)
	return 2;
    port->mp_Node.ln_Name = "LeakWatch";
    port->mp_Node.ln_Pri  = 0;
    AddPort(port);

    portsig = 1L << port->mp_SigBit;

    open_libs();

    FPuts(Output(), "LeakWatch running, CTRL-C to exit, CTRL-E to watch for leaks since beginning, CTRL-F to watch for leaks since last CTRL-F, CTRL-D for an usage snapshot\n");

    crs = NewResourcesState();
    if (NULL == crs)
	quitme = TRUE;
    else
	start_rs = CopyResourcesState(crs);

    while(!quitme)
    {
	ULONG signals;

	signals = Wait(portsig | SIGBREAKF_CTRL_F | SIGBREAKF_CTRL_E | SIGBREAKF_CTRL_D | SIGBREAKF_CTRL_C);

	if (signals & SIGBREAKF_CTRL_D)
	{
	    struct TrackedResources *tr;

	    tr = NewResourcesState();
	    if (NULL == tr)
	    {
		quitme = TRUE;
		break;
	    }
	    DisplayResourcesState(tr, numlines);
	    DeleteResourcesState(tr);
	}
	if (signals & SIGBREAKF_CTRL_E)
	{
	    struct ResourceDiff *rd = NULL;

	    DeleteResourcesState(crs);
	    crs = NewResourcesState();
	    if (NULL == crs)
	    {
		quitme = TRUE;
		break;
	    }
	    /*  DisplayResourcesState(crs); */ /* only for debug */
	    rd = NewStateDiff(start_rs, crs);
	    DisplayStateDiff(rd, numlines);
	    DeleteStateDiff(rd);
	}
	if (signals & SIGBREAKF_CTRL_F)
	{
	    struct TrackedResources *ors = crs;
	    struct ResourceDiff *rd = NULL;

	    crs = NewResourcesState();
	    if (NULL == crs)
	    {
		quitme = TRUE;
		break;
	    }
	    rd = NewStateDiff(ors, crs);
	    DisplayStateDiff(rd, numlines);
	    DeleteStateDiff(rd);
	    DeleteResourcesState(ors);
	}
	if (signals & SIGBREAKF_CTRL_C)
	{
	    quitme = TRUE;
	}
	if (signals & portsig)
	{
	    struct Message *msg;

	    while((msg = (struct Message *)GetMsg(port)))
	    {
		D(bug("Received watch message.\n"));

		ReplyMsg(msg);
	    }

	}
    } /* while(!quitme) */

    DeleteResourcesState(crs);
    DeleteResourcesState(start_rs);

    close_libs();

    if (port)
    {
	RemPort(port);
    	DeleteMsgPort(port);
    }
    return 0;
}