//
// Purpose: 
//   Entry point function. Executes specified command from user.
//
// Parameters:
//   Command-line syntax is: svcconfig [command] [service_path]
// 
// Return value:
//   None
//
void __cdecl _tmain(int argc, TCHAR *argv[])
{
    printf("\n");
    if( argc != 3 )
    {
        printf("ERROR:\tIncorrect number of arguments\n\n");
        DisplayUsage();
        return;
    }

    StringCchCopy(szCommand, 10, argv[1]);
    StringCchCopy(szSvcName, 80, argv[2]);

    if (lstrcmpi( szCommand, TEXT("query")) == 0 )
        DoQuerySvc();
    else if (lstrcmpi( szCommand, TEXT("describe")) == 0 )
        DoUpdateSvcDesc();
    else if (lstrcmpi( szCommand, TEXT("disable")) == 0 )
        DoDisableSvc();
    else if (lstrcmpi( szCommand, TEXT("enable")) == 0 )
        DoEnableSvc();
    else if (lstrcmpi( szCommand, TEXT("delete")) == 0 )
        DoDeleteSvc();
    else 
    {
        _tprintf(TEXT("Unknown command (%s)\n\n"), szCommand);
        DisplayUsage();
    }
}
Esempio n. 2
0
int main( int argc, char **argv ) {

	//Initialize easylogging
	InitializeLogger();

	//TODO - Use boost cmdline args

	if( argc < 3 )
	{
		DisplayUsage();

		return EXIT_FAILURE;
	}
	else
	{
		std::unique_ptr<CMultiTrackerApp> trackerApp( new CMultiTrackerApp( argv ) );

		if( !trackerApp->Initialize() )
		{
			LOG( INFO ) << ">>>> Application Failed To Initialize <<<<";
			return false;
		}

		trackerApp->Run();

		LOG( INFO ) << ">>>> Application Closing <<<<";

		return EXIT_SUCCESS;
	}
}
Esempio n. 3
0
int
main(
    int argc,
    char *argv[]
    )
{
    HANDLE handle;
    int i;

    printf("\nStart %s...\n", argv[0]);

    for (i = 1; i < argc; i++) {

        switch ( *argv[i] ) {

        case 'h':
        case '?':
            DisplayUsage( argv[0] );
            break;

        case 'o':
            if ( !OpenMailslot( argv[i] + 1, &handle ) ) {
                return 3;
            }
            break;

        case 'n':
            if ( !NotifyChangeDirectoryTest() ) {
                return 3;
            }
            break;

        case 'c':
            printf( "Closing file\n" );
            NtClose( handle );
            break;

        case 'w':
            if (!WriteTest(handle)) {
                return 3;
            }
            break;

        case 'v':
            if (!QueryVolumeTest()) {
                return 3;
            }
            break;

        default:
            printf( "Unknown test ""%s"" skipped.\n", argv[i] );

        }
    }

    printf( "%s exiting\n", argv[0]);
    return 0;
}
int main(int argc, char **argv) {

  int c; 
  int index;
  
  // Presence of option character will set correspond flag
  char aflag = 0;
  char tflag = 0;
  char *tvalue = NULL;

  opterr = 0; // prevents the default error messages of getopt() 
  
  while ((c = getopt (argc, argv, "abt:")) != -1) { // Set option flags 
    switch (c) {

    case 'a':
      aflag = 1;
      break;

    case 't':
      tflag = 1;
      tvalue = optarg;
      break;

    case '?': // getopt detected invalid option character or missing target
      if (optopt == 't')
        fprintf (stderr, "Option -%c requires an argument.\n", optopt);
      else if (isprint (optopt))
        fprintf (stderr, "Unknown option `-%c'.\n", optopt);
      else
        fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);

      return 1; // Error!

    default:
      abort (); // Critical Error!
    }
  }

  if (argc == 1)
    DisplayUsage(argv[0]);

  /********Shift Execution based on option flags********/

  else {
    printf ("aflag = %d, tflag = %d, tvalue = %s\n",
             aflag, tflag, tvalue);  
  }

  /********* Process non-option argv arguments *********/

  for (index = optind; index < argc; index++) { // Process non-option arguments
    printf ("Non-option argument \"%s\" @ argv[%d]\n", argv[index], index);
  }

  return 0;
}
Esempio n. 5
0
/** Display all help. */
void DisplayHelp() {
   DisplayUsage();
   printf("  -display X  Set the X display to use\n");
   printf("  -exit       Exit JWM (send _JWM_EXIT to the root)\n");
   printf("  -h          Display this help message\n");
   printf("  -p          Parse the configuration file and exit\n");
   printf("  -restart    Restart JWM (send _JWM_RESTART to the root)\n");
   printf("  -v          Display version information\n");
}
Esempio n. 6
0
int main(int argc, char* argv[])
{
  int speed;
  if (argc == 3) {
    if (sscanf(argv[1],"-s%d",&speed) != 1) {
      DisplayUsage();
      return 0;
    }
    NextImage(argv[2], speed);
  }
  else if(argc == 2) {
    speed = 1000;
    NextImage(argv[1], speed);
  }
  else
    DisplayUsage();

  return 0;
}
Esempio n. 7
0
int main(int argc, char * argv[])
{
   int result = 0;
   SLPToolCommandLine cmdline;

   /* zero out the cmdline */
   memset(&cmdline, 0, sizeof(cmdline));

   /* Parse the command line */
   if (ParseCommandLine(argc, argv, &cmdline) == 0)
      switch (cmdline.cmd)
      {
         case FINDSRVS:
            FindSrvs(&cmdline);
            break;

         case FINDATTRS:
            FindAttrs(&cmdline);
            break;

         case FINDSRVTYPES:
            FindSrvTypes(&cmdline);
            break;

         case FINDSCOPES:
            FindScopes(&cmdline);
            break;

         case GETPROPERTY:
            GetProperty(&cmdline);
            break;

         case REGISTER:
            Register(&cmdline);
            break;

         case DEREGISTER:
            Deregister(&cmdline);
            break;

         case PRINT_VERSION:
            PrintVersion(&cmdline);
	    break;

	 case DUMMY:
	    break;
      }
   else
   {
      DisplayUsage();
      result = 1;
   }

   return result;
}
Esempio n. 8
0
void Options::DisplayError (const Exceptions& aErr)
	{
	const char* msg;
	switch (aErr)
		{
		case EUnknownOption:
			msg = "Unknown option specified";
			DisplayUsage ();
			break;
		case EMissingRegistryEntry:
			msg = "One of the registry entry (PkgUID ,PkgName and VendorName ) not specified";
			DisplayUsage ();
			break;
		case EMissingPkgUID:
			msg = "Package UID not specified ";
			DisplayUsage ();
			break;
		case EInvalidOption:
			msg = "Invalid option specified ";
			DisplayUsage ();
			break;
		case EInvalidPackageUID:
			msg = "Invalid Package UID";
			break;
		case ESetEnvironmentVariable:
			msg = "Set the environment variable or \nspecify registry file path";
			break;
		case EInvalidFile:
			msg = "Registry format not supported .";
			break;
		default:
			msg = "Unknown error";
			break;
		}

	cerr << CommandName () << ": Error : " << msg << endl;
	}
Esempio n. 9
0
void CCommandParser::DisplayError( int aError )
    {
	const wchar_t* msg;
    //
	switch( aError )
	{
	case ECmdLineUnknownOption:
		msg = L"Unknown option specified";
		break;
	case ECmdLineMissingParamFile:
		msg = L"Can't open the parameter file specified";
		break;
	case ECmdLineNoDirArgument:
		msg = L"No directory(s) specified";
		break;
	case ECmdLineNoSisArgument:
		msg = L"No SIS file(s) specified";
		break;
	case ECmdLineNoRomRofsLogsArgument:
		msg = L"No ROM/ROFS[BUILD] log file(s) specified";
		break;
	case ECmdLineNoConfigFileArgument:
		msg = L"No configuration file specified";
		break;
	case ECmdLineNoSisStubPathArgument:
		msg = L"No SIS stub directory specified";
		break;
	case ECmdLineMissingParams:
		msg = L"Missing parameters";
		break;
    case ECmdLineInvalidLanguage:
		msg = L"Invalid language code";
        break;
	case ECmdLineMissingPackageUID:
		msg = L"Package UID not found";
        break;
	default:
		msg = L"Unknown error";
		break;
	}
    //
	LERROR(msg << std::endl);
	DisplayUsage();
    }
Esempio n. 10
0
void Options::DisplayError (CmdLineException err)
	{
	const char* msg;
	switch (err)
		{
		case ECmdLineUnknownOption:
			msg = "unknown option specified";
			break;
		case ECmdLineMissingSIS:
			msg = "no SIS file specified";
			break;
		case ECmdLineMultipleSIS:
			msg = "too many SIS files specified";
			break;
		case ECmdLineNoDirArgument:
			msg = "No argument supplied with the -d flag";
			break;
		case ECmdLineDirIsFile:
			msg = "Directory specified with the -d flag is a file";
			break;
		case ECmdLineNoPermission:
			msg = "Permission was denied when using directory specified with -d";
			break;
		case ECmdLineOtherDirFailure:
			msg = "Operation failed when accessing directory specified with -d";
			break;
		case ECmdLineInvalidDir:
			msg = "Directory name specified with -d could not be created, invalid name";
			break;
		default:
			msg = "unknown error";
			break;
		}
	std::cerr << CommandName () << ": Error in command: " << msg << std::endl;
	DisplayUsage ();
	}
int parseCommandLine() {

    int iRet    =   0;
    int iNumArgs, iNumToBeProcessed;

    LPTSTR lpstrCommandArgs=GetCommandLine();
    
    LPTSTR *rgCmdArgs=CommandLineToArgvW(lpstrCommandArgs,&iNumArgs);

    // To take care of no command line arguments
    if (iNumArgs <= 1 ) {
        iRet = -1;
        goto Cleanup;
    }

    // Check if one argument only and that is the /? argument
    if (0==_tcsncicmp(rgCmdArgs[1],CAzGlobalOptions::HELPTAG , CAzGlobalOptions::HELPTAG_LEN)) {
          DisplayUsage();
          iRet = 1;
          goto Cleanup;
    }

    // if more than one argument but not the required 2 arguments
    if (iNumArgs < 3 ) {
        iRet = -1;
        goto Cleanup;
    }

    CAzGlobalOptions::m_bstrDestStoreName.Attach(CComBSTR(rgCmdArgs[1]).Copy());

    CAzGlobalOptions::m_bstrSourceStoreName.Attach(CComBSTR(rgCmdArgs[2]).Copy());

    CAzGlobalOptions::setDefaults();

    iNumToBeProcessed = iNumArgs-3;

    for (int i = 3 ; i < iNumArgs ; i++) {
        
        // Checking for /logfile
        if (0==_tcsncicmp(rgCmdArgs[i],CAzGlobalOptions::LOGFILETAG,CAzGlobalOptions::LOGFILETAG_LEN)) {

            _TCHAR *strRightPart=_tcschr(rgCmdArgs[i],_TCHAR('='));

            if (NULL==strRightPart) {
                iRet = -1;
                goto Cleanup;
            }

            CAzLogging::Initialize(CAzLogging::LOG_LOGFILE,&strRightPart[1]);

            iNumToBeProcessed--;

        } else if (0==_tcsncicmp(rgCmdArgs[i],CAzGlobalOptions::APPNAMETAG,CAzGlobalOptions::APPNAMETAG_LEN)) {

            //Checking for /application flag

            LPTSTR strTmp;

            _TCHAR *strRightPart=_tcschr(rgCmdArgs[i],_TCHAR('='));

            if (NULL==strRightPart) {
                iRet = -1;
                goto Cleanup;
            }
            CAzGlobalOptions::m_bSpecificApp=true;

            _TCHAR *strAppNames =_tcstok_s(&strRightPart[1],_TEXT(","),&strTmp);

            while (strAppNames!=NULL) {

                CAzGlobalOptions::m_bstrAppNames.push_back(CComBSTR(strAppNames).Copy());

                /* While there are tokens in "string" */
                /* Get next token: */

                strAppNames =_tcstok_s(NULL,_TEXT(","),&strTmp);

                }

            iNumToBeProcessed--;

        } else if (0==_tcsncicmp(rgCmdArgs[i] , CAzGlobalOptions::OVERWRITETAG , CAzGlobalOptions::OVERWRITETAG_LEN)) {

            //Checking for /overwrite flag

            CAzGlobalOptions::m_bOverWrite=true;

            iNumToBeProcessed--;

        } else if (0==_tcsncicmp(rgCmdArgs[i] , CAzGlobalOptions::IGNOREMEMBERSTAG,CAzGlobalOptions::IGNOREMEMBERSTAG_LEN)) {

            //Checking for /IGNOREMEMBERS flag

            CAzGlobalOptions::m_bIgnoreMembers=true;

            iNumToBeProcessed--;

        } else if (0==_tcsncicmp(rgCmdArgs[i] , CAzGlobalOptions::IGNOREPOLICYADMINSTAG , CAzGlobalOptions::IGNOREPOLICYADMINSTAG_LEN)) {

            //Checking for /IGNOREPOLICYADMIN flag

            CAzGlobalOptions::m_bIgnorePolicyAdmins=true;

            iNumToBeProcessed--;

        } else if (0==_tcsncicmp(rgCmdArgs[i] , CAzGlobalOptions::VERBOSETAG , CAzGlobalOptions::VERBOSETAG_LEN)) {

            CAzGlobalOptions::m_bVerbose=true;

            CAzLogging::Initialize(CAzLogging::LOG_TRACE);

            iNumToBeProcessed--;

        } else if (0==_tcsncicmp(rgCmdArgs[i] , CAzGlobalOptions::HELPTAG , CAzGlobalOptions::HELPTAG_LEN)) {

            DisplayUsage();

            iNumToBeProcessed--;
            iRet = 1;
            goto Cleanup;
        }
    }
    // Some additional parameters exist which donot match
    // hence these are invalid flags.
    if (0 != iNumToBeProcessed)
    {
        iRet = -1;
        goto Cleanup;
    }

    iRet = 0;

Cleanup:
    
    if (rgCmdArgs)
    {
        LocalFree(rgCmdArgs);
    }

    return iRet;
}
Esempio n. 12
0
main (int argc, char *argv[])
{
  char *mppfile;
  char *option;
  bool verbose;
  char readln[FILENAME_MAX];

  double x;
  double y;
  double lat;
  double lon;
  int status;

  mapx_class *the_map;

/*
 *	set defaults
 */
  verbose = FALSE;

/* 
 *	get command line options
 */
  while (--argc > 0 && (*++argv)[0] == '-') {
    for (option = argv[0]+1; *option != '\0'; option++) {
      switch (*option) {
      case 'v':
	verbose = TRUE;
	break;
      default:
	fprintf(stderr,"invalid option %c\n", *option);
	DisplayUsage();
      }
    }
  }

/*
 *	get command line arguments
 */
  if (argc != 1)
    DisplayUsage();

  mppfile = *argv++;

  if (verbose) {
    fprintf(stderr, "  mppfile       = %s\n", mppfile);
    fprintf(stderr, "  ll2xy_c_rcsid = %s\n", ll2xy_c_rcsid);
  }
  
  /*
   *  initialize the map
   */

  the_map = init_mapx(mppfile);
  if (NULL == the_map)
    exit(ABORT);

  /*
   * keep reading lines until eof
   */
  for (;;) {
    gets(readln);
    if (!feof(stdin)) {
      
      /*
       * get x-y pair
       */
      sscanf(readln, "%lf %lf", &lat, &lon);
      
      /*
       *  convert x-y pair to latitude-longitude pair
       */
      status = forward_xy_mapx(the_map, lat, lon, &x, &y);
      
      /*
       *  print lat, lon, x, y, and status
       */
      printf("%11.7lf %12.7lf %17.7lf %17.7lf %2d\n", lat, lon, x, y, status);
    } else {
      
      /*
       *  close the map
       */
      close_mapx(the_map);
      break;
    }
  }
    
  exit(EXIT_SUCCESS);
}
Esempio n. 13
0
//*****************************************************************************
//
//! Main function handling the I2C example
//!
//! \param  None
//!
//! \return None
//! 
//*****************************************************************************
void main()
{
    int iRetVal;
    char acCmdStore[512];
    
    //
    // Initialize board configurations
    //
    BoardInit();
    
    //
    // Configure the pinmux settings for the peripherals exercised
    //
    PinMuxConfig();
    
    //
    // Configuring UART
    //
    InitTerm();
    
    //
    // I2C Init
    //
    I2C_IF_Open(I2C_MASTER_MODE_FST);
    
    //
    // Display the banner followed by the usage description
    //
    DisplayBanner(APP_NAME);
    DisplayUsage();

    while(FOREVER)
    {
      //
      // Provide a prompt for the user to enter a command
      //
      DisplayPrompt();
      
      //
      // Get the user command line
      //
      iRetVal = GetCmd(acCmdStore, sizeof(acCmdStore));

      if(iRetVal < 0)
      {
          //
          // Error in parsing the command as length is exceeded.
          //
          UART_PRINT("Command length exceeded 512 bytes \n\r");
          DisplayUsage();
      }
      else if(iRetVal == 0)
      {
          //
          // No input. Just an enter pressed probably. Display a prompt.
          //
      }
      else
      {
          //
          // Parse the user command and try to process it.
          //
          iRetVal = ParseNProcessCmd(acCmdStore);
          if(iRetVal < 0)
          {
              UART_PRINT("Error in processing command\n\r");
              DisplayUsage();
          }
      }
    }
}
Esempio n. 14
0
int
main (
    int                     argc,
    char                    *argv[])
{
    char                    *Filename;
    int                     Status;
    int                     j;


    printf (ACPI_COMMON_SIGNON ("ACPI Binary Table Extraction Utility"));

    if (argc < 2)
    {
        DisplayUsage ();
        return (0);
    }

    /* Command line options */

    while ((j = AcpiGetopt (argc, argv, "ahls:")) != EOF) switch (j)
    {
    case 'a':
        AxAction = AX_EXTRACT_ALL;          /* Extract all tables found */
        break;

    case 'l':
        AxAction = AX_LIST_ALL;             /* List tables only, do not extract */
        break;

    case 's':
        AxAction = AX_EXTRACT_SIGNATURE;    /* Extract only tables with this sig */
        break;

    case 'h':
    default:
        DisplayUsage ();
        return (0);
    }

    /* Input filename is always required */

    Filename = argv[AcpiGbl_Optind];
    if (!Filename)
    {
        printf ("Missing required input filename\n");
        return (-1);
    }

    /* Perform requested action */

    switch (AxAction)
    {
    case AX_EXTRACT_ALL:
        Status = AxExtractTables (Filename, NULL, AX_OPTIONAL_TABLES);
        break;

    case AX_LIST_ALL:
        Status = AxListTables (Filename);
        break;

    case AX_EXTRACT_SIGNATURE:
        Status = AxExtractTables (Filename, AcpiGbl_Optarg, AX_REQUIRED_TABLE);
        break;

    default:
        /*
         * Default output is the DSDT and all SSDTs. One DSDT is required,
         * any SSDTs are optional.
         */
        Status = AxExtractTables (Filename, "DSDT", AX_REQUIRED_TABLE);
        if (Status)
        {
            return (Status);
        }

        Status = AxExtractTables (Filename, "SSDT", AX_OPTIONAL_TABLES);
        break;
    }

    return (Status);
}
Esempio n. 15
0
static int ReadData(int socket_fd, uint8_t *buffer, uint32_t length, unsigned long timeout_ms)
{
    ssize_t numread;
    unsigned total = 0;
    fd_set socket_fd_set;

    do
    {
        struct timeval tv = {.tv_sec = timeout_ms / 1000, .tv_usec = (timeout_ms % 1000)*1000};
        FD_ZERO(&socket_fd_set);
        FD_SET(socket_fd,&socket_fd_set);

        const int select_result = select(socket_fd+1,&socket_fd_set,NULL,NULL,&tv);
        if(select_result <= 0)
            return -1;
        else if(select_result == 0)
            return 0;

        numread = read(socket_fd, buffer + total, length - total);
        if (!numread)
            return 0;
        else if (numread > 0)
            total += numread;
        else if (errno != EINTR && errno != EAGAIN)
            return -1;
    } while (total < length);
    if (total < length)
        return 0;
    return 1;
}

static int ReadResponse(int socket_fd, CSMessageHeader *hdr, int timeout_ms)
{
    const int rc = ReadData(socket_fd,(uint8_t *)hdr,sizeof(*hdr),timeout_ms);
    if(rc > 0){
        hdr->length = ntohl(hdr->length);
        hdr->version = ntohs(hdr->version);
        hdr->type = ntohs(hdr->type);
    }

    return rc;
}

static void ConnectToUnixSocket(const char * const name, int * const psock)
{
    struct sockaddr_un sunaddr;
    int sock = -1;
    int rval;

    memset(&sunaddr, 0, sizeof(sunaddr));
    rval = snprintf(sunaddr.sun_path, sizeof(sunaddr.sun_path), "%s", name);
    if (rval < 0 || (size_t)rval >= sizeof(sunaddr.sun_path))
    {
        fprintf(stderr, "Socket name '%s' is too long\n", name);
        exit(-1);
    }

    sunaddr.sun_family = AF_UNIX;

    /* open the socket */
    if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
    {
        fprintf(stderr, "Error opening socket: %s\n", strerror(errno));
        exit(-1);
    }

    if (connect(sock, (struct sockaddr *) &sunaddr, sizeof(sunaddr)) == -1)
    {
        fprintf(stderr, "Unable to connect to UNIX socket at %s: %s\n", name, strerror(errno));
        close(sock);
        exit(-1);
    }

    *psock = sock;
}

int main(int argc, char *argv[])
{
    int rval;
    char socket_fn[PATH_MAX];
    int socket_fd;
    CSMessage *message;
    const unsigned long type = 1361;
    const char *sep;
    ssize_t len;
    PrintMode mode = PRINT_MODE_FAST;
    unsigned int timeout_ms = 0;

    if (argc != 4 || !*argv[1] || !*argv[2] || !*argv[3])
    {
        DisplayUsage(argv[0]);
        exit(-1);
    }
    else if (argc > 2)
    {
        int idx = 2;

        if((strlen(TIMEOUT_KEYWORD) == strlen(argv[idx])) &&
           (strcmp(TIMEOUT_KEYWORD,argv[idx]) == 0))
        {
            mode = PRINT_MODE_FAST;
            idx ++;
        }

        if (argc > idx)
        {
             timeout_ms = atoi(argv[idx]);
        }
    }

    len = strlen(argv[1]);
    if (len && argv[1][len - 1] == '/')
        sep = "";
    else
        sep = "/";

    snprintf(socket_fn, sizeof(socket_fn), "%s%s%s", argv[1], sep, CONTROL_FILE);
    ConnectToUnixSocket(socket_fn, &socket_fd);

    message = malloc(sizeof *message);
    if (message == NULL)
    {
        fprintf(stderr, "%s: could not allocate message.\n",argv[0]);
        exit(-1);
    }

    message->hdr.version = htons(CS_HEADER_VERSION);
    message->hdr.type = htons((uint16_t)type);
    message->hdr.length = 0;

    if ((rval = SendMessage(socket_fd, message)) < 0)
    {
        fprintf(stderr, "Failed to send the message: %s\n", strerror(errno));
        close(socket_fd);
        exit(-1);
    }
    else if (!rval)
    {
        fprintf(stderr, "Server closed the socket\n");
        close(socket_fd);
        exit(-1);
    }

    if ((rval = ReadResponse(socket_fd, &message->hdr,timeout_ms)) < 0)
    {
        fprintf(stderr, "Failed to read the response: %s\n", strerror(errno));
        close(socket_fd);
        exit(-1);
    }
    else if (!rval)
    {
        fprintf(stderr, "Server closed the socket before sending a response\n");
        close(socket_fd);
        exit(-1);
    }

    if (message->hdr.version != CS_HEADER_VERSION)
    {
        printf("%s: bad response version\n",argv[0]);
        close(socket_fd);
        exit(-1);
    }

    if (message->hdr.type != 9)
    {
        printf("%s: bad response type:%d, expected %d",argv[0],message->hdr.type,9);
        close(socket_fd);
        exit(-1);
    }

    if (message->hdr.length)
    {

        if (message->hdr.length < sizeof(message->msg_hdr))
        {
            printf("%s: response message is too small\n",argv[0]);
            close(socket_fd);
            exit(-1);
        }

        if (message->hdr.length > sizeof(message->msg))
        {
            printf("%s: response message is too large\n",argv[0]);
            close(socket_fd);
            exit(-1);
        }

        if ((rval = ReadData(socket_fd, (uint8_t *)message+sizeof(message->hdr), message->hdr.length, timeout_ms)) < 0)
        {
            fprintf(stderr, "Failed to read the response data: %s\n", strerror(errno));
            close(socket_fd);
            exit(-1);
        }
        else if (!rval)
        {
            fprintf(stderr, "Server closed the socket before sending the response data\n");
            close(socket_fd);
            exit(-1);
        }

        message->msg_hdr.code = ntohl(message->msg_hdr.code);
        message->msg_hdr.length = ntohs(message->msg_hdr.length);

        if (mode == PRINT_MODE_DETAIL)
        {
            fprintf(stdout, "Response %04X with code %d and length %u\n",
                message->hdr.type, message->msg_hdr.code, message->msg_hdr.length);
            DumpHex(stdout, message->msg, message->msg_hdr.length);
        }
        else if (mode == PRINT_MODE_FAST)
        {
            if (message->msg_hdr.length == message->hdr.length - sizeof(message->msg_hdr))
            {
                message->msg[message->msg_hdr.length-1] = 0;
                fprintf(stdout, "Response %04X with code %d (%s)\n",
                    message->hdr.type, message->msg_hdr.code, message->msg);
            }
            else
                fprintf(stdout, "Response %04X with code %d\n", message->hdr.type, message->msg_hdr.code);
        }
    }
    else
    {
        if (mode == PRINT_MODE_DETAIL)
            printf("Response %04X without data\n", message->hdr.type);
        else
            printf("Response %04X\n", message->hdr.type);
    }

    return 0;
}
Esempio n. 16
0
bool BMDConfig::ParseArguments(int argc,  char** argv)
{
	int		ch;
	bool	displayHelp = false;

	while ((ch = getopt(argc, argv, "d:?h3c:s:v:a:m:n:q:p:t:l:")) != -1)
	{
		switch (ch)
		{
			case 'd':
				m_deckLinkIndex = atoi(optarg);
				break;

			case 'm':
				m_displayModeIndex = atoi(optarg);
				break;

			case 'c':
				m_audioChannels = atoi(optarg);
				if (m_audioChannels != 2 &&
					m_audioChannels != 8 &&
					m_audioChannels != 16)
				{
					fprintf(stderr, "Invalid argument: Audio Channels must be either 2, 8 or 16\n");
					return false;
				}
				break;

			case 's':
				m_audioSampleDepth = atoi(optarg);
				if (m_audioSampleDepth != 16 && m_audioSampleDepth != 32)
				{
					fprintf(stderr, "Invalid argument: Audio Sample Depth must be either 16 bits or 32 bits\n");
					return false;
				}
				break;

			case 'v':
				m_videoOutputFile = optarg;
				break;

			case 'l':
				m_lcmChannelName = optarg;
				break;

			case 'a':
				m_audioOutputFile = optarg;
				break;

			case 'n':
				m_maxFrames = atoi(optarg);
				break;

			case 'q':
				m_compressionQuality = atoi(optarg);
				break;

			case '3':
				m_inputFlags |= bmdVideoInputDualStream3D;
				break;

			case 'p':
				switch(atoi(optarg))
				{
					case 0: m_pixelFormat = bmdFormat8BitYUV; break;
					case 1: m_pixelFormat = bmdFormat10BitYUV; break;
					case 2: m_pixelFormat = bmdFormat10BitRGB; break;
					default:
						fprintf(stderr, "Invalid argument: Pixel format %d is not valid", atoi(optarg));
						return false;
				}
				break;

			case 't':
				if (!strcmp(optarg, "rp188"))
					m_timecodeFormat = bmdTimecodeRP188Any;
				else if (!strcmp(optarg, "vitc"))
					m_timecodeFormat = bmdTimecodeVITC;
				else if (!strcmp(optarg, "serial"))
					m_timecodeFormat = bmdTimecodeSerial;
				else
				{
					fprintf(stderr, "Invalid argument: Timecode format \"%s\" is invalid\n", optarg);
					return false;
				}
				break;

			case '?':
			case 'h':
				displayHelp = true;
		}
	}
        

	if (m_deckLinkIndex < 0)
	{
		fprintf(stderr, "You must select a device\n");
		DisplayUsage(1);
	}

	if (m_displayModeIndex < -1)
	{
		fprintf(stderr, "You must select a display mode\n");
		DisplayUsage(1);
	}

	if (displayHelp)
		DisplayUsage(0);

	// Get device and display mode names
	IDeckLink* deckLink = GetDeckLink(m_deckLinkIndex);

	if (deckLink != NULL)
	{
		if (m_displayModeIndex != -1)
		{
			IDeckLinkDisplayMode* displayMode = GetDeckLinkDisplayMode(deckLink, m_displayModeIndex);
			if (displayMode != NULL)
			{
				displayMode->GetName((const char**)&m_displayModeName);
				displayMode->Release();
			}
			else
			{
				m_displayModeName = strdup("Invalid");
			}
		}
		else
		{
			m_displayModeName = strdup("Format Detection");
		}

		deckLink->GetModelName((const char**)&m_deckLinkName);
		deckLink->Release();
	}
	else
	{
		m_deckLinkName = strdup("Invalid");
	}

	return true;
}
Esempio n. 17
0
File: asmq1.c Progetto: joewing/q1
int main(int argc, char *argv[]) {

   const char *input_name;
   const char *output_name;
   FILE *input_fd;
   FILE *output_fd;
   int x;

   /* Parse arguments. */
   input_name = NULL;
   output_name = NULL;
   for(x = 1; x < argc; x++) {
      if(!strcmp(argv[x], "-o")) {
         if(output_name != NULL) {
            DisplayUsage(argv[0]);
            return -1;
         } else {
            output_name = argv[x + 1];
            ++x;
         }
      } else if(!strcmp(argv[x], "-raw")) {
         output_format = OUT_RAW;
      } else if(!strcmp(argv[x], "-list")) {
         output_format = OUT_LISTING;
      } else if(!strcmp(argv[x], "-hex")) {
         output_format = OUT_HEX;
      } else if(!strcmp(argv[x], "-h")) {
         DisplayUsage(argv[0]);
         return 0;
      } else {
         if(input_name != NULL) {
            DisplayUsage(argv[0]);
            return -1;
         } else {
            input_name = argv[x];
         }
      }
   }
   if(input_name == NULL) {
      DisplayUsage(argv[0]);
      return -1;
   }
   if(output_name == NULL) {
      switch(output_format) {
      case OUT_RAW:
         output_name = "out.raw";
         break;
      case OUT_HEX:
         output_name = "out.hex";
         break;
      default:
         output_name = "out.lst";
         break;
      }
   }

   byte_count = 0;
   error_count = 0;
   symbols = NULL;
   macros = NULL;
   input_fd = DoPreprocess(input_name);
   if(input_fd != NULL) {
      DoFirstPass(input_fd);
   }
   if(error_count == 0) {
      output_fd = fopen(output_name, output_format == OUT_RAW ? "wb" : "w");
      if(output_fd == NULL) {
         fclose(input_fd);
         fprintf(stderr, "ERROR: could not open %s for writing\n", output_name);
         return -1;
      }
      rewind(input_fd);
      DoSecondPass(input_fd, output_fd);
      fclose(output_fd);
   }
   if(input_fd) {
      fclose(input_fd);
   }

   printf("Errors:     %u\n", error_count);
   printf("Byte count: %u\n", byte_count);

   return error_count;

}
Esempio n. 18
0
//--------------------------------------------------------------------------------------
// Parses the command line for parameters.  See DXUTInit() for list 
//--------------------------------------------------------------------------------------
bool ParseCommandLine( SETTINGS* pSettings )
{
    bool bDisplayError = false;
    bool bDisplayHelp = false;
    WCHAR* strCmdLine;
    WCHAR* strArg;

    int nNumArgs;
    WCHAR** pstrArgList = CommandLineToArgvW( GetCommandLine(), &nNumArgs );
    for( int iArg=1; iArg<nNumArgs; iArg++ )
    {
        strCmdLine = pstrArgList[iArg];

        // Handle flag args
        if( *strCmdLine == L'/' || *strCmdLine == L'-' )
        {
            strCmdLine++;

            if( IsNextArg( strCmdLine, L"y" ) )
            {
                pSettings->bOverwrite = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"t" ) )
            {
                pSettings->bGenTangents = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"tb" ) )
            {
                pSettings->bGenTangents = true;
                pSettings->bGenBinormals = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"a" ) )
            {
                pSettings->bRetainAnimation = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"v" ) )
            {
                pSettings->bVerbose = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"xt" ) )
            {
                pSettings->outputType = MESH_TYPE_X_TEXT;
                continue;
            }

            if( IsNextArg( strCmdLine, L"x" ) )
            {
                pSettings->outputType = MESH_TYPE_X_BINARY;
                continue;
            }

            if( IsNextArg( strCmdLine, L"sdkmesh" ) )
            {
                pSettings->outputType = MESH_TYPE_SDKMESH;
                continue;
            }

            if( IsNextArg( strCmdLine, L"o" ) )
            {
                if( iArg+1 < nNumArgs )
                {
                    strArg = pstrArgList[++iArg];
                    pSettings->bOutputFileProvided = true;
                    StringCchCopy( pSettings->strOutputFile, 256, strArg );
                    continue;
                }

                wprintf( L"Incorrect flag usage: /o\n" );
                bDisplayError = true;
                continue;
            }

            if( IsNextArg( strCmdLine, L"?" ) )
            {
                DisplayUsage();
                return false;
            }

            // Unrecognized flag
            wprintf( L"Unrecognized or incorrect flag usage: %s\n", strCmdLine );
            bDisplayError = true;
        }
        else
        {
            // Handle non-flag args as seperate input file
            if( pSettings->bInputFileProvided )
            {
                wprintf( L"Too many input files provided: %s\n", strCmdLine );
                bDisplayError = true;
            }
            else
            {
                pSettings->bInputFileProvided = true;
                StringCchCopy( pSettings->strInputFile, 256, strCmdLine );
                continue;
            }
        }
    }

    if( !pSettings->bInputFileProvided )
        bDisplayHelp = true;

    if( pSettings->bInputFileProvided && !pSettings->bOutputFileProvided )
    {
        StringCchCopy( pSettings->strOutputFile, MAX_PATH, pSettings->strInputFile );

    }

    if( bDisplayHelp )
    {
        DisplayUsage();
        return false;
    }

    if( bDisplayError )
    {
        wprintf( L"Type \"MeshConvert.exe /?\" for a complete list of options\n" );
        return false;
    }

    return true;
}
Esempio n. 19
0
main (int argc, char *argv[])
{
  char *gpdfile;
  char *option;
  bool verbose;

  grid_class *grid_def;

/*
 *	set defaults
 */
  verbose = FALSE;

/* 
 *	get command line options
 */
  while (--argc > 0 && (*++argv)[0] == '-') {
    for (option = argv[0]+1; *option != '\0'; option++) {
      switch (*option) {
      case 'v':
	verbose = TRUE;
	break;
      default:
	fprintf(stderr,"invalid option %c\n", *option);
	DisplayUsage();
      }
    }
  }

/*
 *	get command line arguments
 */
  if (argc != 1)
    DisplayUsage();

  gpdfile = *argv++;

  if (verbose) {
    fprintf(stderr, "gridsize:\n");
    fprintf(stderr, "  gpdfile       = %s\n", gpdfile);
    fprintf(stderr, "  gridsize_c_rcsid = %s\n", gridsize_c_rcsid);
  }
  
  /*
   *  initialize grid
   */
  grid_def = init_grid(gpdfile);

  if (NULL == grid_def) {

    /*
     *  if grid has error, then print zeroes and exit with failure
     */
    printf("cols: 0\n");
    printf("rows: 0\n");
    exit(ABORT);
  } else {

    /*
     *  if grid is ok, then print number of columns and rows
     */
    printf("cols: %d\n", grid_def->cols);
    printf("rows: %d\n", grid_def->rows);

    /*
     *  close grid
     */
    close_grid(grid_def);
  }
  exit(EXIT_SUCCESS);
}
Esempio n. 20
0
main (int argc, char *argv[])
{
  bool verbose;
  bool very_verbose;
  bool exponential;
  bool ignore;
  bool temp_mode;
  char *option;
  char *gpdfile;
  int col_start;
  int row_start;
  int cols;
  int rows;
  char *corfile;
  bool do_correction;
  char line[MAX_STRING];
  int count_input;
  int count_output;
  double col;
  double row;
  double elev;
  double temperature;
  float lat;
  float lon;
  grid_class *grid_def;
  int status;
  int bytes_per_cell;
  int bytes_per_row;
  float **correction;
  int jcol;
  int irow;
  FILE *fp_cor;
  bool in_region;

/*
 *	set defaults
 */
  verbose = FALSE;
  very_verbose = FALSE;
  exponential = FALSE;
  ignore = FALSE;
  gpdfile = "Sa0.gpd";
  do_correction = FALSE;
  temp_mode = 0;

/* 
 *	get command line options
 */
  while (--argc > 0 && (*++argv)[0] == '-') {
    for (option = argv[0]+1; *option != '\0'; option++) {
      switch (*option) {
      case 'v':
	if (verbose)
	  very_verbose = TRUE;
	verbose = TRUE;
	break;
      case 'e':
	exponential = TRUE;
	break;
      case 'i':
        ignore = TRUE;
	break;
      case 'g':
	++argv; --argc;
 	if (argc <= 0)
	  DisplayInvalidParameter("gpdfile");
	gpdfile = *argv;
	break;
      case 'c':
	do_correction = TRUE;
	++argv; --argc;
	if (argc <= 0)
	  DisplayInvalidParameter("col_start");
	if (sscanf(*argv, "%d", &col_start) != 1)
	  DisplayInvalidParameter("col_start");
 	++argv; --argc;
	if (argc <= 0)
	  DisplayInvalidParameter("row_start");
	if (sscanf(*argv, "%d", &row_start) != 1)
	  DisplayInvalidParameter("row_start");
	++argv; --argc;
	if (argc <= 0)
	  DisplayInvalidParameter("cols");
	if (sscanf(*argv, "%d", &cols) != 1)
	  DisplayInvalidParameter("cols");
	++argv; --argc;
	if (argc <= 0)
	  DisplayInvalidParameter("rows");
	if (sscanf(*argv, "%d", &rows) != 1)
	  DisplayInvalidParameter("rows");
	++argv; --argc;
 	if (argc <= 0)
	  DisplayInvalidParameter("corfile");
	corfile = *argv;
	break;
      case 't':
	temp_mode = TRUE;
	break;
    default:
	fprintf(stderr,"invalid option %c\n", *option);
	DisplayUsage();
      }
    }
  }

/*
 *	get command line arguments
 */
  if (argc != 0)
    DisplayUsage();

  if (verbose) {
    fprintf(stderr, "lle2cre: %s\n", lle2cre_c_rcsid);
    fprintf(stderr, "  very_verbose = %d\n", very_verbose);
    fprintf(stderr, "  exponential  = %d\n", exponential);
    fprintf(stderr, "  ignore       = %d\n", ignore);
    fprintf(stderr, "  gpdfile      = %s\n", gpdfile);
    if (do_correction) {
      fprintf(stderr, "  col_start    = %d\n", col_start);
      fprintf(stderr, "  row_start    = %d\n", row_start);
      fprintf(stderr, "  cols         = %d\n", cols);
      fprintf(stderr, "  rows         = %d\n", rows);
      fprintf(stderr, "  corfile      = %s\n", corfile);
    }
    fprintf(stderr, "  temp_mode    = %d\n", temp_mode);
  }

  /*
   *  initialize grid
   */

  grid_def = init_grid(gpdfile);
  if (NULL == grid_def)
    exit(ABORT);

  if (do_correction) {
    /*
     *  allocate memory for correction
     */
    
    bytes_per_cell = sizeof(float);
    if ((correction =
	 (float **)matrix(rows, cols, bytes_per_cell, 1)) == NULL) {
      fprintf(stderr, "cr2cre: error allocating memory for correction");
      perror("lle2cre");
      error_exit("lle2cre");
    }
    
    /*
     *  read in entire correction
     */
    
    if ((fp_cor = fopen(corfile, "r")) == NULL) {
      fprintf(stderr, "lle2cre: error opening %s\n", corfile);
      perror("lle2cre");
      error_exit("lle2cre");
    }
    bytes_per_row = bytes_per_cell * cols;
    if (fread(&correction[0][0], bytes_per_row, rows, fp_cor) != rows) {
      fprintf(stderr, "lle2cre: error reading %s\n", corfile);
      perror("lle2cre");
      error_exit("lle2cre");
    }
    fclose(fp_cor);
  }

  count_input = 0;
  count_output = 0;
  while (fgets(line, sizeof(line), stdin)) {

    /*
     *  read and parse input line
     */

    count_input++;
    if (sscanf(line, "%f%f%lf", &lat, &lon, &elev) != 3) {
      fprintf(stderr, "error parsing input line %d:\n%s\n", count_input, line);
    } else {

      if (temp_mode) {
	temperature = elev;
	elev = 0.0;
      }

      /*
       *  convert lat-lon pair to col-row pair
       */
      
      in_region = TRUE;
      status = forward_grid(grid_def, lat, lon, &col, &row);
      if (status == 0) {
	if (very_verbose || !ignore) {
	  fprintf(stderr, "Error mapping lat-lon to col-row on line %d:\n",
		  count_input);
	  fprintf(stderr, "  %s\n", line);
	}
	if (ignore)
	  in_region = FALSE;
      }
      
      /*
       *  perform correction as needed
       */
      
      if (do_correction) {
	irow = (int)(row - row_start + 0.5);
	jcol = (int)(col - col_start + 0.5);
	if (irow >= 0 && irow < rows &&
	    jcol >= 0 && jcol < cols) {
	  elev += correction[irow][jcol];
	} else {
	  in_region = FALSE;
	}
      }
      
      /*
       *  write output line
       */
      
      if (in_region) {
	if (temp_mode)
	  if (exponential)
	    printf("%15.8le %15.8le %15.8le %15.8le\n",
		   col, row, elev, temperature);
	  else
	    printf("%11.5lf %11.5lf %11.6lf %11.5lf\n",
		   col, row, elev, temperature);
	else
	  if (exponential)
	    printf("%15.8le %15.8le %15.8le\n", col, row, elev);
	  else
	    printf("%11.5lf %11.5lf %11.6lf\n", col, row, elev);
	count_output++;
      }
    }
  }

  /*
   *  close grid
   */

  close_grid(grid_def);

  /*
   *  deallocate memory for correction
   */

  if (do_correction)
    free(correction);

  /*
   *  print number of lines processed
   */

  if (verbose) {
    fprintf(stderr, "  %d lines input\n", count_input);
    fprintf(stderr, "  %d lines output\n", count_output);
  }
  exit(EXIT_SUCCESS);
}
Esempio n. 21
0
static void DisplayInvalidParameter(char *param)
{
  fprintf(stderr, "lle2cre: Parameter %s is invalid.\n", param);
  DisplayUsage();
}
Esempio n. 22
0
File: acc.c Progetto: Edward850/acc
static void ProcessArgs(void)
{
	int i = 1;
	int count = 0;
	char *text;
	char option;
	
	while(i < ArgCount)
	{
		text = ArgVector[i];
		
		if(*text == '-')
		{
			// Option
			text++;
			if(*text == 0)
			{
				DisplayUsage();
			}
			option = toupper(*text++);
			switch(option)
			{
				case 'I':
					if((i + 1) < ArgCount)
					{
						TK_AddIncludePath(ArgVector[++i]);
					}
					break;
					
				case 'D':
					acs_DebugMode = YES;
					acs_VerboseMode = YES;
					if(*text != 0)
					{
						OpenDebugFile(text);
					}
					break;
					
				case 'H':
					pc_NoShrink = TRUE;
					pc_HexenCase = TRUE;
					pc_EnforceHexen = toupper(*text) != 'H';
					pc_WarnNotHexen = toupper(*text) == 'H';
					break;
					
				default:
					DisplayUsage();
					break;
			}
		}
		else
		{
			// Input/output file
			count++;
			switch(count)
			{
				case 1:
					strcpy(acs_SourceFileName, text);
					MS_SuggestFileExt(acs_SourceFileName, ".acs");
					break;
					
				case 2:
					strcpy(ObjectFileName, text);
					MS_SuggestFileExt(ObjectFileName, ".o");
					break;
					
				default:
					DisplayUsage();
					break;
			}
		}
		
		// Next arg
		i++;
	}
	
	if(count == 0)
	{
		DisplayUsage();
	}

	TK_AddIncludePath(".");
#ifdef unix
	TK_AddIncludePath("/usr/local/share/acc/");
#endif
	TK_AddProgramIncludePath(ArgVector[0]);
	
	if(count == 1)
	{
		strcpy(ObjectFileName, acs_SourceFileName);
		MS_StripFileExt(ObjectFileName);
		MS_SuggestFileExt(ObjectFileName, ".o");
	}
}
extern "C" int __stdcall WinMain(HINSTANCE hInst, HINSTANCE hPrevInst , __in LPSTR lpszCmdLine, int nCmdShow)
{

//-----------------------------------------------------------------------------------------------------------------
//  VARIABLES
//
//-----------------------------------------------------------------------------------------------------------------
    UINT    uiRet = ERROR_SUCCESS;
    HRESULT hr    = S_OK;

    char *szMsiFile          = 0;
    char *szBaseURL          = 0;
    char *szInstallPath      = 0;
    char *szMsiCacheFile     = 0;
    char *szOperation        = 0;
    char *szProductName      = 0;
    char *szMinimumMsi       = 0;
    char *szProperties       = 0;
    char *szInstProperties   = 0;
    char *szTempPath         = 0;
    char *szFilePart         = 0;
    char *szBase             = 0;
    char *szUpdate           = 0;

    char *szRegisteredMsiFolder = 0;
    char *szMsiDllLocation      = 0;

    char szAppTitle[MAX_STR_CAPTION]    = {0};
    char szError[MAX_STR_LENGTH]        = {0};
    char szText[MAX_STR_CAPTION]        = {0};
    char szBanner[MAX_STR_LENGTH]       = {0};
    char szAction[MAX_STR_LENGTH]       = {0};
    char szUserPrompt[MAX_STR_LENGTH]   = {0};
    char szProductCode[MAX_LENGTH_GUID] = {0};

    char szModuleFile[MAX_PATH]         = {0};
    DWORD dwModuleFileSize       = MAX_PATH;
    
    DWORD dwMsiFileSize          = 0;
    DWORD dwBaseURLSize          = 0;
    DWORD cchInstallPath         = 0;
    DWORD dwMsiCacheFileSize     = 0;
    DWORD dwOperationSize        = 0;
    DWORD dwProductNameSize      = 0;
    DWORD dwMinimumMsiSize       = 0;
    DWORD dwPropertiesSize       = 0;
    DWORD cchInstProperties      = 0;
    DWORD cchTempPath            = 0;
    DWORD dwLastError            = 0;
    DWORD cchReturn              = 0;
    DWORD dwBaseUpdateSize      = 0;
    DWORD dwUpdateSize          = 0;
    DWORD dwResult               = 0;
    DWORD dwType                 = 0;
    DWORD dwProductCodeSize      = MAX_LENGTH_GUID;

    DWORD dwRegisteredMsiFolderSize  = 0;
    DWORD dwMsiDllLocationSize       = 0;

    ULONG ulMsiMinVer        = 0;
    char *szStopScan         = NULL;

    bool        fDelayRebootReq    = false;
    bool        fPatch             = false;
    bool        fQFE               = false;
    bool        fOSSupported       = false;
    emEnum      emExecMode         = emPreset;

    HKEY hInstallerKey = 0;

    HMODULE hMsi = 0;
    PFnMsiSetInternalUI pfnMsiSetInternalUI = 0;
    PFnMsiInstallProduct pfnMsiInstallProduct = 0;
    PFnMsiApplyPatch pfnMsiApplyPatch = 0;
    PFnMsiReinstallProduct pfnMsiReinstallProduct = 0;
    PFnMsiQueryProductState pfnMsiQueryProductState = 0;
    PFnMsiOpenDatabase pfnMsiOpenDatabase = 0;
    PFnMsiDatabaseOpenView pfnMsiDatabaseOpenView = 0;
    PFnMsiViewExecute pfnMsiViewExecute = 0;
    PFnMsiViewFetch pfnMsiViewFetch = 0;
    PFnMsiRecordGetString pfnMsiRecordGetString = 0;
    PFnMsiCloseHandle pfnMsiCloseHandle = 0;

    MSIHANDLE hDatabase = 0;
    MSIHANDLE hView = 0;
    MSIHANDLE hRec = 0;

    INSTALLSTATE isProduct = INSTALLSTATE_UNKNOWN;
    
    const char * szAdminImagePath = 0;



//-----------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------
    // create our UI object
    CDownloadUI DownloadUI;

    // Load our AppTitle (caption)
    WIN::LoadString(hInst, IDS_APP_TITLE, szAppTitle, sizeof(szAppTitle)/sizeof(char));

    // Obtain path we are running from
    if (0 == WIN::GetModuleFileName(hInst, szModuleFile, dwModuleFileSize))
    {
        // No UI displayed. Silent failure.
        uiRet = GetLastError();
        goto CleanUp;
    }
    DebugMsg("[Info] we are running from --> %s\n", szModuleFile);

    // Figure out what we want to do
    emExecMode = GetExecutionMode (lpszCmdLine);
    
    if (emVerify == emExecMode)
    {
        //
        // We don't want any UI to be displayed in this case. The return value
        // from the exe is the result of the verification. Therefore, this
        // should be done before initializing the UI.
        //
        uiRet = VerifyFileSignature (szModuleFile, lpszCmdLine);
        if (ERROR_BAD_ARGUMENTS != uiRet)
            goto CleanUp;
    }
    
    if (ERROR_BAD_ARGUMENTS == uiRet || emHelp == emExecMode)
    {
        DisplayUsage(hInst, NULL, szAppTitle);
        goto CleanUp;
    }
    
    //
    // NOTE:
    // Delay handling admin. installs until we have determined if we are
    // patching an existing install or if we are doing a default install.
    //
 
    // initialize our UI object with desktop as parent
    DownloadUI.Initialize(hInst, /* hwndParent = */ 0, szAppTitle);

    // Check if we are installing on an OS that supports Windows Installer 3.0
    fOSSupported = IsOSSupported();
    if(!fOSSupported)
    {
        PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_OS_NOT_SUPPORTED);
        uiRet = ERROR_INSTALL_FAILURE;
        goto CleanUp;
    }
    HANDLE hMutex = 0;

    // only run one instance at a time
    if (AlreadyInProgress(hMutex))
    {
        // silently return - correct return code ?
		uiRet = ERROR_INSTALL_ALREADY_RUNNING;
		goto CleanUp;
    }
    
    // determine operation, default (if not present) is INSTALL
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_OPERATION, &szOperation, dwOperationSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    if (ERROR_SUCCESS != uiRet)
    {
        // set operation to default which is install
        if (szOperation)
            delete [] szOperation;
        szOperation = new char[lstrlen(szDefaultOperation) + 1];
        if (!szOperation)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        if (FAILED(StringCchCopy(szOperation, lstrlen(szDefaultOperation) + 1, szDefaultOperation)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }
    }

    // obtain name of product
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PRODUCTNAME, &szProductName, dwProductNameSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    if (ERROR_SUCCESS != uiRet)
    {
        // use default
        if (szProductName)
            delete [] szProductName;
        szProductName = new char[MAX_STR_CAPTION];
        if (!szProductName)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        WIN::LoadString(hInst, IDS_DEFAULT_PRODUCT, szProductName, MAX_STR_CAPTION);
    }

    // set banner text
    WIN::LoadString(hInst, IDS_BANNER_TEXT, szText, MAX_STR_CAPTION);
    StringCchPrintf(szBanner, sizeof(szBanner), szText, szProductName);
    if (irmCancel == DownloadUI.SetBannerText(szBanner))
    {
        ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        uiRet = ERROR_INSTALL_USEREXIT;
        goto CleanUp;
    }

    // Determine if this is a patch or a normal install.
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_DATABASE, &szMsiFile, dwMsiFileSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    else if (ERROR_SUCCESS != uiRet)
    {
        // look for patch
        if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PATCH, &szMsiFile, dwMsiFileSize)))
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        else if (ERROR_SUCCESS != uiRet)
        {
            PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_DATABASE);
            goto CleanUp;
        }

        fPatch = true;
    }
    
    //
    // If we are here, this is either an admin. install or a default install.
    // File signature verification, help and other invalid parameters have
    // already been taken care of above.
    //
    if (emAdminInstall == emExecMode)
    {
        uiRet = GetAdminInstallInfo (fPatch, lpszCmdLine, &szAdminImagePath);
        if (ERROR_BAD_ARGUMENTS == uiRet)
        {
            DisplayUsage(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
    }
    
    //
    // At this point, the validation of the commandline arguments is complete
    // and we have all the information we need.
    //

    // obtain minimum required MSI version
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_MINIMUM_MSI, &szMinimumMsi, dwMinimumMsiSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    else if (ERROR_SUCCESS != uiRet)
    {
        PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_MINIMUM_MSI);
        goto CleanUp;
    }

    // make sure required Msi version is a valid value -- must be >= 150
    ulMsiMinVer = strtoul(szMinimumMsi, &szStopScan, 10);
    if (!szStopScan || (szStopScan == szMinimumMsi) || (*szStopScan != 0) || ulMsiMinVer < MINIMUM_SUPPORTED_MSI_VERSION)
    {
        // invalid minimum version string
        PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_VER_STR, szMinimumMsi, MINIMUM_SUPPORTED_MSI_VERSION);
        uiRet = ERROR_INVALID_PARAMETER;
        goto CleanUp;
    }

    DebugMsg("[Resource] Minimum Msi Value = %d\n", ulMsiMinVer);

    // compare minimum required MSI version to that which is on the machine
    if (IsMsiUpgradeNecessary(ulMsiMinVer))
    {
        DebugMsg("[Info] Upgrade of Windows Installer is requested\n");

        // make sure this is admin -- must have admin priviledges to upgrade Windows Installer
        if (!IsAdmin())
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_REQUIRES_ADMIN_PRIV);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }

        // Ask the user if they want to upgrade the installer
        WIN::LoadString(hInst, IDS_ALLOW_MSI_UPDATE, szUserPrompt, MAX_STR_LENGTH);
        if (IDYES != WIN::MessageBox(DownloadUI.GetCurrentWindow(), szUserPrompt, szAppTitle, MB_YESNO|MB_ICONQUESTION))
        {
            // user decided to cancel
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }

        if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_UPDATE, &szUpdate, dwUpdateSize)))
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        else if (ERROR_SUCCESS != uiRet)
        {
            PostResourceNotFoundError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, ISETUPPROPNAME_UPDATE);
            goto CleanUp;
        }            
        
        // determine if we need to download the Windows Installer update package from the web -- based on presence of UPDATELOCATION property
        if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_UPDATELOCATION, &szBase, dwBaseUpdateSize)))
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            goto CleanUp;
        }
        else if (ERROR_SUCCESS == uiRet)
        {
            // presence of UPDATELOCATION property indicates assumption of URL source
            if (ERROR_SUCCESS != (uiRet = DownloadAndUpgradeMsi(hInst, &DownloadUI, szAppTitle, szBase, szUpdate, szModuleFile, ulMsiMinVer)))
            {
                if (ERROR_SUCCESS_REBOOT_REQUIRED == uiRet)
                {
                    // successful, but must reboot at end
                    fDelayRebootReq = true;
                }
                else
                    goto CleanUp;
            }
        }
        else
        {
            // lack of UPDATELOCATION property indicates assumption of Media source
            if (ERROR_SUCCESS != (uiRet = UpgradeMsi(hInst, &DownloadUI, szAppTitle, szModuleFile, szUpdate, ulMsiMinVer)))
            {
                if (ERROR_SUCCESS_REBOOT_REQUIRED == uiRet)
                {
                    // successful, but must reboot at end
                    fDelayRebootReq = true;
                }
                else
                    goto CleanUp;
            }
        }
    }

    DebugMsg("[Info] Windows Installer has been upgraded, or was already correct version\n");

    // perform some extra authoring validation
    if (fPatch
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMinPatchOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMajPatchOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1))
    {
        // wrong operation
        DebugMsg("[Error] Operation %s is not valid for a patch\n", szOperation);
        PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_OPERATION, szOperation);
        uiRet = ERROR_INVALID_PARAMETER;
        goto CleanUp;
    }
    else if (!fPatch
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallUpdOperation, -1)
        && CSTR_EQUAL != CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1))
    {
        // wrong operation
        DebugMsg("[Error] Operation %s is not valid for a package\n", szOperation);
        PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_OPERATION, szOperation);
        uiRet = ERROR_INVALID_PARAMETER;
        goto CleanUp;
    }

    // by now we either have a MSI or a MSP
    if (CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szMinPatchOperation, -1)
        || CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szInstallUpdOperation, -1)
        || (fPatch && CSTR_EQUAL == CompareString(lcidLOCALE_INVARIANT, NORM_IGNORECASE, szOperation, -1, szDefaultOperation, -1)))
        fQFE = true;

    // obtain base URL
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_BASEURL, &szBaseURL, dwBaseURLSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        goto CleanUp;
    }
    else if (ERROR_SUCCESS == uiRet)
    {
        // presence of BASEURL property indicates assumption of URL source . . .

        // generate the path to the installation package == baseURL + msiFile
        //   note: msiFile is a relative path
        cchTempPath = lstrlen(szBaseURL) + lstrlen(szMsiFile) + 2; // 1 for slash, 1 for null
        szTempPath = new char[cchTempPath ];
        if (!szTempPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }
        if (FAILED(StringCchCopy(szTempPath, cchTempPath, szBaseURL)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }
        // check for trailing slash on szBaseURL
        char *pch = szBaseURL + lstrlen(szBaseURL) + 1; // put at null terminator
        pch = CharPrev(szBaseURL, pch);
        if (*pch != '/')
        {
            if (FAILED(StringCchCat(szTempPath, cchTempPath, szUrlPathSep)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }
        if (FAILED(StringCchCat(szTempPath, cchTempPath, szMsiFile)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }        

        // canocialize the URL path
        cchInstallPath = cchTempPath*2;
        szInstallPath = new char[cchInstallPath];
        if (!szInstallPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        dwLastError = 0; // success
        if (!InternetCanonicalizeUrl(szTempPath, szInstallPath, &cchInstallPath, 0))
        {
            dwLastError = GetLastError();
            if (ERROR_INSUFFICIENT_BUFFER == dwLastError)
            {
                // try again
                delete [] szInstallPath;
                szInstallPath = new char[cchInstallPath];
                if (!szInstallPath)
                {
                    ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
                    uiRet = ERROR_OUTOFMEMORY;
                    goto CleanUp;
                }
                dwLastError = 0; // reset to success for 2nd attempt
                if (!InternetCanonicalizeUrl(szTempPath, szInstallPath, &cchInstallPath, 0))
                    dwLastError = GetLastError();
            }
        }
        if (0 != dwLastError)
        {
            // error -- invalid path/Url
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath);
            uiRet = dwLastError;
            goto CleanUp;
        }

        // set action text for download
        WIN::LoadString(hInst, IDS_DOWNLOADING_PACKAGE, szText, MAX_STR_CAPTION);
        StringCchPrintf(szAction, sizeof(szAction), szText, szMsiFile);
        if (irmCancel == DownloadUI.SetActionText(szAction))
        {
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }

        // download the msi file so we can attempt a trust check -- must be local for WinVerifyTrust
        DebugMsg("[Info] Downloading msi file %s for WinVerifyTrust check\n", szInstallPath);

        szMsiCacheFile = new char[MAX_PATH];
        dwMsiCacheFileSize = MAX_PATH;
        if (!szMsiCacheFile)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        hr = WIN::URLDownloadToCacheFile(NULL, szInstallPath, szMsiCacheFile, dwMsiCacheFileSize, 0, /* IBindStatusCallback = */ &CDownloadBindStatusCallback(&DownloadUI));
        if (DownloadUI.HasUserCanceled())
        {
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }
        if (FAILED(hr))
        {
            // error during download -- probably because file not found (or lost connection)
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NOMSI, szInstallPath);
            uiRet = ERROR_FILE_NOT_FOUND;
            goto CleanUp;
        }

        DebugMsg("[Info] Msi file was cached to %s\n", szMsiCacheFile);

        // set action text for trust verification
        WIN::LoadString(hInst, IDS_VALIDATING_SIGNATURE, szText, MAX_STR_CAPTION);
        StringCchPrintf(szAction, sizeof(szAction), szText, szMsiFile);
        if (irmCancel == DownloadUI.SetActionText(szAction))
        {
            ReportUserCancelled(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_INSTALL_USEREXIT;
            goto CleanUp;
        }

        // perform trust check 
        itvEnum itv = IsPackageTrusted(szModuleFile, szMsiCacheFile, DownloadUI.GetCurrentWindow());
        if (itvWintrustNotOnMachine == itv)
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NO_WINTRUST);
            uiRet = ERROR_CALL_NOT_IMPLEMENTED;
            goto CleanUp;
        }
        else if (itvUnTrusted == itv)
        {
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_UNTRUSTED, szInstallPath);
            uiRet = HRESULT_CODE(TRUST_E_SUBJECT_NOT_TRUSTED);
            goto CleanUp;
        }
    }
    else
    {
        // lack of BASEURL property indicates assumption of Media source

        // generate the path to the Msi file =  szModuleFile + msiFile
        //   note: msiFile is a relative path
        cchTempPath = lstrlen(szModuleFile) + lstrlen(szMsiFile) + 2; // 1 for null terminator, 1 for back slash
        szTempPath = new char[cchTempPath];
        if (!szTempPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        // find 'setup.exe' in the path so we can remove it
        if (0 == GetFullPathName(szModuleFile, cchTempPath, szTempPath, &szFilePart))
        {
            uiRet = GetLastError();
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath);
            goto CleanUp;
        }
        if (szFilePart)
            *szFilePart = '\0';

        if (FAILED(StringCchCat(szTempPath, cchTempPath, szMsiFile)))
        {
            PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
            uiRet = ERROR_INSTALL_FAILURE;
            goto CleanUp;
        }
        
        cchInstallPath = 2*cchTempPath;
        szInstallPath = new char[cchInstallPath];
        if (!szInstallPath)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }

        // normalize the path
        cchReturn = GetFullPathName(szTempPath, cchInstallPath, szInstallPath, &szFilePart);
        if (cchReturn > cchInstallPath)
        {
            // try again, with larger buffer
            delete [] szInstallPath;
            cchInstallPath = cchReturn;
            szInstallPath = new char[cchInstallPath];
            if (!szInstallPath)
            {
                ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
                uiRet = ERROR_OUTOFMEMORY;
                goto CleanUp;
            }
            cchReturn = GetFullPathName(szTempPath, cchInstallPath, szInstallPath, &szFilePart);
        }
        if (0 == cchReturn)
        {
            // error -- invalid path
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INVALID_PATH, szTempPath);
            uiRet = dwLastError;
            goto CleanUp;
        }

        // no download is necessary -- but we can check for the file's existence
        DWORD dwFileAttrib = GetFileAttributes(szInstallPath);
        if (0xFFFFFFFF == dwFileAttrib)
        {
            // package is missing
            PostFormattedError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_NOMSI, szInstallPath);
            uiRet = ERROR_FILE_NOT_FOUND;
            goto CleanUp;
        }
    }

    //
    // good to go -- terminate our UI and let the Windows Installer take over
    //

    // retrieve the optional command line PROPERTY = VALUE strings if available
    if (ERROR_OUTOFMEMORY == (uiRet = SetupLoadResourceString(hInst, ISETUPPROPNAME_PROPERTIES, &szProperties, dwPropertiesSize)))
    {
        ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
        uiRet = ERROR_OUTOFMEMORY;
        goto CleanUp;
    }
    else if (ERROR_SUCCESS != uiRet)
    {
        // PROPERTY=VALUE pairs not specified
        if (szProperties)
            delete [] szProperties;
        szProperties = NULL;
    }

    DownloadUI.Terminate();

    //
    // perform install 
    //

    hMsi = LoadLibrary(MSI_DLL);
    
    if (hMsi)
    {
        pfnMsiSetInternalUI = (PFnMsiSetInternalUI)GetProcAddress(hMsi, MSIAPI_MsiSetInternalUI);
        pfnMsiInstallProduct = (PFnMsiInstallProduct)GetProcAddress(hMsi, MSIAPI_MsiInstallProduct);
        pfnMsiApplyPatch = (PFnMsiApplyPatch)GetProcAddress(hMsi, MSIAPI_MsiApplyPatch);
        pfnMsiReinstallProduct = (PFnMsiReinstallProduct)GetProcAddress(hMsi, MSIAPI_MsiReinstallProduct);
        pfnMsiQueryProductState = (PFnMsiQueryProductState)GetProcAddress(hMsi, MSIAPI_MsiQueryProductState);
        pfnMsiOpenDatabase = (PFnMsiOpenDatabase)GetProcAddress(hMsi, MSIAPI_MsiOpenDatabase);
        pfnMsiDatabaseOpenView = (PFnMsiDatabaseOpenView)GetProcAddress(hMsi, MSIAPI_MsiDatabaseOpenView);
        pfnMsiViewExecute = (PFnMsiViewExecute)GetProcAddress(hMsi, MSIAPI_MsiViewExecute);
        pfnMsiViewFetch = (PFnMsiViewFetch)GetProcAddress(hMsi, MSIAPI_MsiViewFetch);
        pfnMsiRecordGetString = (PFnMsiRecordGetString)GetProcAddress(hMsi, MSIAPI_MsiRecordGetString);
        pfnMsiCloseHandle = (PFnMsiCloseHandle)GetProcAddress(hMsi, MSIAPI_MsiCloseHandle);
    }
    if (!hMsi || !pfnMsiSetInternalUI || !pfnMsiInstallProduct || !pfnMsiApplyPatch || !pfnMsiReinstallProduct || !pfnMsiQueryProductState
        || !pfnMsiDatabaseOpenView || !pfnMsiViewExecute || !pfnMsiViewFetch || !pfnMsiRecordGetString || !pfnMsiCloseHandle)
    {
        PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_FAILED_TO_UPGRADE_MSI);
        uiRet = ERROR_INSTALL_FAILURE;
        goto CleanUp;
    }

    DebugMsg("[Info] Setting Internal UI level to FULL...\n");
    pfnMsiSetInternalUI(INSTALLUILEVEL_FULL, 0);

    if (!fPatch)
    {
        // performing install or reinstall/recache
        DebugMsg("[Info] Calling MsiInstallProduct with szInstallPath = %s", szInstallPath); 
        DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}");

        // default operation for a package is INSTALL

        if (fQFE)
        {
            // check to see if this product is already installed
            if (ERROR_SUCCESS == pfnMsiOpenDatabase(szMsiCacheFile ? szMsiCacheFile : szInstallPath, MSIDBOPEN_READONLY, &hDatabase)
                && ERROR_SUCCESS == pfnMsiDatabaseOpenView(hDatabase, sqlProductCode, &hView)
                && ERROR_SUCCESS == pfnMsiViewExecute(hView, 0)
                && ERROR_SUCCESS == pfnMsiViewFetch(hView, &hRec)
                && ERROR_SUCCESS == pfnMsiRecordGetString(hRec, 1, szProductCode, &dwProductCodeSize))
            {
                isProduct = pfnMsiQueryProductState(szProductCode);
                DebugMsg("[Info] MsiQueryProductState returned %d\n", isProduct);
                if (INSTALLSTATE_ADVERTISED != isProduct && INSTALLSTATE_DEFAULT != isProduct)
                {
                    // product is unknown, so this will be a first time install
                    DebugMsg("[Info] The product code '%s' is unknown. Will use first time install logic...\n", szProductCode);
                    fQFE = false;
                }
                else
                {
                    // product is known, use QFE syntax
                    DebugMsg("[Info] The product code '%s' is known. Will use QFE recache and reinstall upgrade logic...\n", szProductCode);
                }
            }
            else
            {
                // some failure occurred when processing the product code, so treat as non-QFE
                DebugMsg("[Info] Unable to process product code. Will treat as first time install...\n");
                fQFE = false;
            }
            if (hDatabase)
                pfnMsiCloseHandle(hDatabase);
            if (hView)
                pfnMsiCloseHandle(hView);
            if (hRec)
                pfnMsiCloseHandle(hRec);
        }
        
        //
        // Set up the properties to be passed into MSIInstallProduct
        //
        if (fQFE && !szProperties)
            cchInstProperties = lstrlen (szDefaultInstallUpdCommandLine);
        else if (szProperties)
            cchInstProperties = lstrlen (szProperties);
        if (emAdminInstall == emExecMode)
            cchInstProperties += lstrlen (szAdminInstallProperty);
        
        szInstProperties = new char[cchInstProperties + 1];
        if (! szInstProperties)
        {
            ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
            uiRet = ERROR_OUTOFMEMORY;
            goto CleanUp;
        }
        
        if (fQFE && !szProperties)
        {
            if (FAILED(StringCchCopy(szInstProperties, cchInstProperties + 1, szDefaultInstallUpdCommandLine)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }
        else if (szProperties)
        {
            if (FAILED(StringCchCopy(szInstProperties, cchInstProperties + 1, szProperties)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }
        else
            szInstProperties[0] = '\0';
        if (emAdminInstall == emExecMode)
        {
            if (FAILED(StringCchCat(szInstProperties, cchInstProperties + 1, szAdminInstallProperty)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }

        uiRet = pfnMsiInstallProduct(szInstallPath, szInstProperties);
        if (ERROR_SUCCESS != uiRet)
        {
            // attempt to display an error message stored in msi.dll
            PostMsiError(hInst, hMsi, DownloadUI.GetCurrentWindow(), szAppTitle, uiRet);
        }

        DebugMsg("[Info] MsiInstallProduct returned %d\n", uiRet);
    }
    else
    {
        // default Operation for a patch is MINPATCH

        // if szProperties is NULL, use our default value for QFE patches
        if (!szProperties && fQFE)
        {
            DebugMsg("[Info] Patch is a MINPATCH (small or minor update patch) so using default command line '%s'\n", szDefaultMinPatchCommandLine);

            szProperties = new char[lstrlen(szDefaultMinPatchCommandLine) + 1];
            if (!szProperties)
            {
                ReportErrorOutOfMemory(hInst, DownloadUI.GetCurrentWindow(), szAppTitle);
                uiRet = ERROR_OUTOFMEMORY;
                goto CleanUp;
            }
            if (FAILED(StringCchCopy(szProperties, lstrlen(szDefaultMinPatchCommandLine) + 1, szDefaultMinPatchCommandLine)))
            {
                PostError(hInst, DownloadUI.GetCurrentWindow(), szAppTitle, IDS_INTERNAL_ERROR);
                uiRet = ERROR_INSTALL_FAILURE;
                goto CleanUp;
            }
        }

        if (emAdminInstall == emExecMode)
        {
            // performing a patch
            DebugMsg("[Info] Calling MsiApplyPatch with szPatchPackage = %s", szMsiCacheFile);
            DebugMsg(" and szInstallPackage = %s and eInstallType = INSTALLTYPE_NETWORK_IMAGE", szAdminImagePath);
            DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}");

            uiRet = pfnMsiApplyPatch(szMsiCacheFile, szAdminImagePath, INSTALLTYPE_NETWORK_IMAGE, szProperties);
        }
        else
        {
            // performing a patch
            DebugMsg("[Info] Calling MsiApplyPatch with szPatchPackage = %s", szInstallPath);
            DebugMsg(" and szInstallPackage = {null} and eInstallType = INSTALLTYPE_DEFAULT");
            DebugMsg(" and szCommandLine = %s\n", szProperties ? szProperties : "{null}");

            uiRet = pfnMsiApplyPatch(szInstallPath, NULL, INSTALLTYPE_DEFAULT, szProperties);
        }
        if (ERROR_SUCCESS != uiRet)
        {
            // attempt to display an error message stored in msi.dll
            PostMsiError(hInst, hMsi, DownloadUI.GetCurrentWindow(), szAppTitle, uiRet);
        }

        DebugMsg("[Info] MsiApplyPatch returned %d\n", uiRet);
    }

    
CleanUp:

    if (szMsiFile)
        delete [] szMsiFile;
    if (szBaseURL)
        delete [] szBaseURL;
    if (szInstallPath)
        delete [] szInstallPath;
    if (szMsiCacheFile)
    {
        WIN::DeleteUrlCacheEntry(szMsiCacheFile);
        delete [] szMsiCacheFile;
    }
    if (szProductName)
        delete [] szProductName;
    if (szMinimumMsi)
        delete [] szMinimumMsi;
    if (szProperties)
        delete [] szProperties;
    if (szTempPath)
        delete [] szTempPath;
    if (szBase)
        delete [] szBase;
    if (szUpdate)
        delete [] szUpdate;
    if (szRegisteredMsiFolder)
        delete [] szRegisteredMsiFolder;
    if (szMsiDllLocation)
        delete [] szMsiDllLocation;
    if (szOperation)
        delete [] szOperation;

    if(hMutex)
        CloseHandle(hMutex);

    if (hMsi)
        FreeLibrary(hMsi);

    DebugMsg("[Info] Setup exit code is %d\n", uiRet);

    if (fDelayRebootReq)
    {
        // need to reboot machine for updating Windows Installer
        WIN::LoadString(hInst, IDS_REBOOT_REQUIRED, szAction, MAX_STR_LENGTH);
        if (IDYES == MessageBox(NULL, szAction, szAppTitle, MB_YESNO|MB_ICONQUESTION))
        {
            // must first aquire system shutdown privileges on NT/Win2K
            AcquireShutdownPrivilege();
            // initiate system shutdown for reboot
            WIN::ExitWindowsEx(EWX_REBOOT, PCLEANUI | SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_INSTALLATION);
        }
    }

    return uiRet;
}
Esempio n. 24
0
int
main (
    int                     argc,
    char                    *argv[])
{
    char                    *Filename;
    int                     AxAction;
    int                     Status;
    int                     j;


    Gbl_TableCount = 0;
    Gbl_TableListHead = NULL;
    AxAction = AX_EXTRACT_AML_TABLES; /* Default: DSDT & SSDTs */

    ACPI_DEBUG_INITIALIZE (); /* For debug version only */
    AcpiOsInitialize ();
    printf (ACPI_COMMON_SIGNON (AX_UTILITY_NAME));

    if (argc < 2)
    {
        DisplayUsage ();
        return (0);
    }

    /* Command line options */

    while ((j = AcpiGetopt (argc, argv, AX_SUPPORTED_OPTIONS)) != ACPI_OPT_END) switch (j)
    {
    case 'a':

        AxAction = AX_EXTRACT_ALL;          /* Extract all tables found */
        break;

    case 'l':

        AxAction = AX_LIST_ALL;             /* List tables only, do not extract */
        break;

    case 'm':

        AxAction = AX_EXTRACT_MULTI_TABLE;  /* Make single file for all DSDT/SSDTs */
        break;

    case 's':

        AxAction = AX_EXTRACT_SIGNATURE;    /* Extract only tables with this sig */
        break;

    case 'v': /* -v: (Version): signon already emitted, just exit */

        return (0);

    case 'h':
    default:

        DisplayUsage ();
        return (0);
    }

    /* Input filename is always required */

    Filename = argv[AcpiGbl_Optind];
    if (!Filename)
    {
        printf ("Missing required input filename\n");
        return (-1);
    }

    /* Perform requested action */

    switch (AxAction)
    {
    case AX_EXTRACT_ALL:

        Status = AxExtractTables (Filename, NULL, AX_OPTIONAL_TABLES);
        break;

    case AX_EXTRACT_MULTI_TABLE:

        Status = AxExtractToMultiAmlFile (Filename);
        break;

    case AX_LIST_ALL:

        Status = AxListTables (Filename);
        break;

    case AX_EXTRACT_SIGNATURE:

        Status = AxExtractTables (Filename, AcpiGbl_Optarg, AX_REQUIRED_TABLE);
        break;

    default:
        /*
         * Default output is the DSDT and all SSDTs. One DSDT is required,
         * any SSDTs are optional.
         */
        Status = AxExtractTables (Filename, "DSDT", AX_REQUIRED_TABLE);
        if (Status)
        {
            return (Status);
        }

        Status = AxExtractTables (Filename, "SSDT", AX_OPTIONAL_TABLES);
        break;
    }

    return (Status);
}
Esempio n. 25
0
int
main (
    int                     argc,
    char                    *argv[])
{
    int                     Status;


    if (argc < 2)
    {
        DisplayUsage ();
        return (0);
    }

    if (argv[1][0] == '-')
    {
        if (argc < 3)
        {
            DisplayUsage ();
            return (0);
        }

        switch (argv[1][1])
        {
        case 'a':

            /* Extract all tables found */

            return (ExtractTables (argv[2], NULL, 0));

        case 'l':

            /* List tables only, do not extract */

            return (ListTables (argv[2]));

        case 's':

            /* Extract only tables with this signature */

            return (ExtractTables (argv[2], &argv[1][2], 1));

        default:
            DisplayUsage ();
            return (0);
        }
    }

    /*
     * Default output is the DSDT and all SSDTs. One DSDT is required,
     * any SSDTs are optional.
     */
    Status = ExtractTables (argv[1], "DSDT", 1);
    if (Status)
    {
        return (Status);
    }

    Status = ExtractTables (argv[1], "SSDT", 0);
    return (Status);
}
Esempio n. 26
0
Options::Options (int argc, wchar_t** argv)
	: iVerboseFlag (false),
	iVersion (false),
	iHelpFlag (false),
	iExtractFilesFlag (false),
	iPauseOnExit (false),
	iList(false),
	iCreateECI(false)
	{
	while (--argc)
		{
		argv++;
		// WINDOWS ENVIRONMENT : If the underlying platform is WINDOWS then, 
		// cope up with multiple arguments following the '-' or '/'. 
		//
		// LINUX ENVIRONMENT : If the underlying platform is LINUX then, cope 
		// up with multiple arguments following only the '-'. This restriction 
		// of not dealing with arguments following '/' is due to the fact that, 
		// the absolute paths in case of LINUX start with a '/'. So, this could 
		// be mistaken as an option if we treat anything prefixed by a '/' as 
		// an option. Hence, this facility is being removed once for all and 
		// only '-' can(should) be used for specifying an option.
					if (	   (**argv == '-')   
#ifndef __TOOLS2_LINUX__
							|| (**argv == '/')
#endif
					   )
			{
			const wchar_t* optPtr = *argv;

			while (*++optPtr)
				{
				switch (*optPtr)
					{
					case 'd':
					case 'D':
						if (argc > 1)
							{
							argc--;
							iExtractDirectory = *(++argv);
							}
						else
							{
							
							throw ECmdLineNoDirArgument;

							}
						break;

					case 'h':
					case 'H':
					case '?':
						iHelpFlag = true;
						break;
					case 'v':
					case 'V':
						iVersion = true;
						break;

					case 'p':
					case 'P':
						iPauseOnExit = true;
						break;
					case 'i':
					case 'I':
						iVerboseFlag = true;
						break;
					case 'x':
					case 'X':
						iExtractFilesFlag = true;
						break;

					case 'l':
					case 'L':
						iList = true;
						break;
					case 'y':
					case 'Y':
						iCreateECI = true;
						break;

			
					default:
						throw ECmdLineUnknownOption;
					}
				}
			}
		else
			{
			if (iSISFileName != L"")
				{
				throw ECmdLineMultipleSIS;
				}
			else
				{
				iSISFileName = *argv;
				}
			}
		}
		
	if (iHelpFlag)
		{
		DisplayUsage ();
		if (iSISFileName == L"")	// If we were asked for help then we shouldn't
			{				// complain that there's no SIS file specified,
			exit (0);		// just exit quietly.
			}
		}

	if (iVersion)
		{
		DisplayVersion ();
		if (iSISFileName == L"")
			{
			exit (0);		
			}
		}

	if (iSISFileName == L"")
		{
		throw ECmdLineMissingSIS;	
		}
	
	// Sanity check the directory argument
	// If directory name is not provided then
	// generate a directory name.
	GetExtractDir();
	}
Esempio n. 27
0
bool CCommandParser::ParseParam(int argc, const char**argv, CParameterList* aParamList)
	{
	if (argc < 2)
	    {
		throw CCommandParser::ECmdLineUnknownOption;
	    }
	
	bool bContinue = true;
	
	while ((--argc > 0) && bContinue)
	    {
		++argv;
		if (**argv != '-')
			{
			continue;
            }

		bool err = false;
		const char* optPtr = *argv;

		switch (toupper(*++optPtr))
		    {
			#ifdef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK
			case 'A':
				{
				if (argc <= 1)
					throw CCommandParser::ECmdLineNoDirArgument;
				
				--argc;
				aParamList->SetResourceFilePath(*(++argv));
				break;	
				}
			#endif //SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK
			case 'C':
				{
				if (argc <= 1)
					throw CCommandParser::ECmdLineNoDirArgument;
				
				--argc;
				aParamList->SetSystemDrive(*(++argv));
				break;
				
				}
			case 'D':
				{	
				--argc;
				wchar_t buf[2048];
				ConvertMultiByteToWideChar(*++argv,-1, buf, 2048);
				aParamList->SetSystemDriveLetter(tolower(buf[0]));
				break;
				}					
			case 'E':
				{
				aParamList->SetFlag(CParameterList::EFlagsDisableZDriveChecksSet);
				break;
				}
			#ifdef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK
			case 'F':
				{				
				aParamList->SetOriginVerificationStatus(false);
				break;
				}
			#endif
			case 'H':
			case '?':
				{
				DisplayUsage();
				bContinue = false;
				break;
				}
			case 'I':
				{
				if (argc <= 1)
					throw CCommandParser::ECmdLineNoConfigFileArgument;
	
				--argc;
				aParamList->SetConfigFile(*(++argv));
				break;
				}
			case 'K':
				{
				// Last command
				if (argc == 1)
					{
					aParamList->SetSisRegistryVersion(SisRegistry::KRegistryV40string);
					}
				else
					{
					// Check that the next arg is valid
					std::string versionStr = *(++argv);

					if (**argv == '-')
						{
						aParamList->SetSisRegistryVersion(SisRegistry::KRegistryV40string);
						--argv;
						}
					else
						{
						--argc;
						aParamList->SetSisRegistryVersion(versionStr);
						}
					}
				break;
				}
			case 'L':
				{
				if (argc > 1)
					{
					--argc;
					wchar_t buf[2048];
					ConvertMultiByteToWideChar(*++argv,-1, buf, 2048);
					iLogFile = buf;
					}
				break;
				}
			case 'N':
				{
				if (argc <= 1)
					throw CCommandParser::ECmdLineInvalidLanguage;

				--argc;
				aParamList->SetLanguage(static_cast< CSISLanguage::TLanguage >( String2Language( *(++argv) ) ));
				break;
				}
			case 'O':
				{
				DisplayOpenSSLCopyright();
				bContinue = false;
				break;
				}
			case 'P':
				{
				if (!(err = argc <= 1))
					{
					--argc;
					std::string paramFile = *(++argv);
					ParseParam(argc, paramFile, aParamList);
					}
				break;
				}
			case 'R':
				{
				if (argc <= 1)
					throw CCommandParser::ECmdLineNoRomRofsLogsArgument;

				--argc;
				aParamList->EmptyRomLogFiles();
#ifdef _MSC_VER
				FilePtr funtionPtr = aParamList->AddRomLogFile;
#else
				FilePtr funtionPtr = &(aParamList->AddRomLogFile);
#endif // _MSC_VER	
				String2List(*aParamList, funtionPtr, *(++argv) );
				break;
				}
			case 'S':
				{
				if (argc <= 1)
					throw CCommandParser::ECmdLineNoSisArgument;

				--argc;

				String2SISFileList(*aParamList, argc, ++argv);
				break;
				}
			case 'T':
				{
				if (argc <= 1)
					throw CCommandParser::ECmdLineNoSisStubPathArgument;

				--argc;
				aParamList->SetStubDir(*(++argv));
				break;
				}
			case 'V':
				{
				DisplayVersion();
				bContinue = false;
				break;
				}
			case 'W':
				{
				--argc;
				iWarnLevel = String2Warn(*(++argv));
				break;
				}
			case 'X':
				{
				if (argc <= 1)
					throw CCommandParser::ECmdLineMissingPackageUID;

				--argc;
				aParamList->EmptyPkgUids();
#ifdef _MSC_VER
				FilePtr funtionPtr = (aParamList->AddPkgUid);
#else
				FilePtr funtionPtr = &(aParamList->AddPkgUid);
#endif // _MSC_VER	
				String2List(*aParamList, funtionPtr, *(++argv) );
				break;
				}
			case 'Z':
				{
				if (argc <= 1)
					throw CCommandParser::ECmdLineNoDirArgument;
			
				--argc;
				aParamList->SetZDrive(*(++argv));
				break;
				}
			default:
				{
				LERROR(string2wstring(std::string(optPtr)));
				throw CCommandParser::ECmdLineUnknownOption;
				}
			}

		if (err)
			{
			throw CCommandParser::ECmdLineUnknownOption;
			}
		} // Finished parsing all the command line options
	
	return !bContinue; 
    }
Esempio n. 28
0
/* 
 *  ======== main ========
 */ 
INT main(INT argc, CHAR * argv[]) 
{
	INT opt;
	bool fWaitForTerminate = false;
	UINT uProcId = 0;	/* default proc ID is 0. */
	bool fError = false;
	DSP_HPROCESSOR hProc;
	int status = 0;
	INT cArgc = 0;		/* local argc count. */
	bool fScriptable = false;
	extern char *optarg;
	struct DSP_PROCESSORINFO dspInfo;
	UINT numProcs;
	UINT index = 0;
	while ((opt = getopt(argc, argv, "+T+v+w+?p:")) != EOF) {
		switch (opt) {
		case 'v':
			/* verbose mode */ 
			fprintf(stdout, "Verbose mode: ON\n");
			g_fVerbose = true;
			cArgc++;
			break;
		case 'w':
			/* wait for user input to terminate */ 
			fprintf(stdout, "Not supported \n");
			fWaitForTerminate = true;
			cArgc++;
			break;
		case 'T':
			fScriptable = true;
			cArgc++;
			break;
		case 'p':
			/* user specified DSP processor ID (based on zero-index) */ 
			uProcId = atoi(optarg);
			cArgc++;
			break;
		case '?':
		default:
			fError = true;
			break;
		}
	}
	argv += cArgc + 1;
	argc -= cArgc + 1;
	if (fError) {
		DisplayUsage();
	} else {
		status = (DBAPI)DspManager_Open(ROOT_ACCESS, NULL);
		if (DSP_FAILED(status)) {
			PrintVerbose("DSPManager_Open failed \n");
			return -1;
		} 
		while (DSP_SUCCEEDED(DSPManager_EnumProcessorInfo(index,&dspInfo,
						(UINT)sizeof(struct DSP_PROCESSORINFO),&numProcs))) {
			if ((dspInfo.uProcessorType == DSPTYPE_55) || 
									(dspInfo.uProcessorType == DSPTYPE_64)) {
				printf("DSP device detected !! \n");
				uProcId = index;
				status = 0;
				break;
			}
			index++;
		}
		status = DSPProcessor_Attach(uProcId, NULL, &hProc);
		if (DSP_SUCCEEDED(status)) {
			PrintVerbose("DSPProcessor_Attach succeeded.\n");
			status = DSPProcessor_Stop(hProc);
			if (DSP_SUCCEEDED(status)) {
				PrintVerbose("DSPProcessor_Stop succeeded.\n");
				status = DSPProcessor_Load(hProc,argc,(CONST CHAR **)argv,NULL);
				if (DSP_SUCCEEDED(status)) {
					PrintVerbose("DSPProcessor_Load succeeded.\n");
					status = DSPProcessor_Start(hProc);
					if (DSP_SUCCEEDED(status)) {
						fprintf(stdout,"DSPProcessor_Start succeeded.\n");
#if 0                    
						/* It seems Linux bridge does n't yet support
						 * * DSPProcessor_GetTrace */ 
						if (fWaitForTerminate) { 
							/* wait for user */ 
							fprintf(stdout,"Hit \"return\" to stop DSP and"
													"dump trace buffer:\n");
							(void)getchar();
							status = DSPProcessor_GetTrace(hProc,
												(BYTE *)&traceBuf,MAXTRACESIZE);
							fprintf(stdout,"%s\n",traceBuf);
						} else {
							PrintVerbose("in run free mode...\n");
						}
#endif	/* 0 */
					} else {
						PrintVerbose("DSPProcessor_Start failed: 0x%x.\n",
																		status);
					}
				} else {
					PrintVerbose("DSPProcessor_Load failed: 0x%x.\n",status);
				}
				DSPProcessor_Detach(hProc);
			}
		} else {
			PrintVerbose("DSPProcessor_Attach failed: 0x%x.\n",status);
		}
	}
	if (!fScriptable) {
		/* Wait for user to hit any key before exiting. */ 
		fprintf(stdout, "Hit any key to terminate cexec.\n");
		(void)getchar();
	}
	status = DspManager_Close(0, NULL);
	if (DSP_FAILED(status)) {
		printf("\nERROR: DSPManager Close FAILED\n");
	}
	return (DSP_SUCCEEDED(status) ? 0 : -1);
}
Esempio n. 29
0
int main(int argc, char *argv[])
{
    int rval;
    char socket_fn[PATH_MAX];
    int socket_fd;
    char *p;
    CSMessage *message;
    unsigned long type;
    const char *sep;
    ssize_t len;
    PrintMode mode = PRINT_MODE_DETAIL;
    const char *extra;
    unsigned int extra_len = 0;

    if (argc < 3 || argc > 5 || !*argv[1] || !*argv[2])
    {
        DisplayUsage(argv[0]);
        exit(-1);
    }
    else if (argc > 3)
    {
        int idx = 3;

        if((strlen(PRINT_MODE_FAST_KEYWORD) == strlen(argv[idx])) &&
           (strcmp(PRINT_MODE_FAST_KEYWORD,argv[idx]) == 0))
        {
            mode = PRINT_MODE_FAST;
            idx ++;
        }

        if (argc > idx)
        {
             extra = argv[idx];
             extra_len = strlen(extra) + 1;
        }
    }

    type = strtoul(argv[2], &p, 0);
    if (*p || type > CS_TYPE_MAX)
    {
        DisplayUsage(argv[0]);
        exit(-1);
    }

    len = strlen(argv[1]);
    if (len && argv[1][len - 1] == '/')
        sep = "";
    else
        sep = "/";

    snprintf(socket_fn, sizeof(socket_fn), "%s%s%s", argv[1], sep, CONTROL_FILE);
    ConnectToUnixSocket(socket_fn, &socket_fd);

    if (extra_len > sizeof(message->msg))
    {
        fprintf(stderr, "snort_control: message is too long.\n");
        exit(-1);
    }

    message = malloc(sizeof *message);
    if (message == NULL)
    {
        fprintf(stderr, "snort_control: could not allocate message.\n");
        exit(-1);
    }

    message->hdr.version = htons(CS_HEADER_VERSION);
    message->hdr.type = htons((uint16_t)type);
    message->hdr.length = 0;

    if (extra_len)
    {
        message->hdr.length = htonl(extra_len + sizeof(message->msg_hdr));

        message->msg_hdr.code = 0;
        message->msg_hdr.length = htons(extra_len);
        memcpy(message->msg, extra, extra_len);
    }

    if ((rval = SendMessage(socket_fd, message, extra_len)) < 0)
    {
        fprintf(stderr, "Failed to send the message: %s\n", strerror(errno));
        close(socket_fd);
        exit(-1);
    }
    else if (!rval)
    {
        fprintf(stderr, "Server closed the socket\n");
        close(socket_fd);
        exit(-1);
    }

    do
    {
        /* Reusing the same CSMessage to capture the response */
        if ((rval = ReadResponse(socket_fd, &message->hdr)) < 0)
        {
            fprintf(stderr, "Failed to read the response: %s\n", strerror(errno));
            close(socket_fd);
            exit(-1);
        }
        else if (!rval)
        {
            fprintf(stderr, "Server closed the socket before sending a response\n");
            close(socket_fd);
            exit(-1);
        }

        if (message->hdr.version != CS_HEADER_VERSION)
        {
            printf("snort_control: bad response version\n");
            close(socket_fd);
            exit(-1);
        }

        if (message->hdr.length)
        {

            if (message->hdr.length < sizeof(message->msg_hdr))
            {
                printf("snort_control: response message is too small\n");
                close(socket_fd);
                exit(-1);
            }

            if (message->hdr.length > sizeof(message->msg))
            {
                printf("snort_control: response message is too large\n");
                close(socket_fd);
                exit(-1);
            }

            if ((rval = ReadData(socket_fd, (uint8_t *)message+sizeof(message->hdr), message->hdr.length)) < 0)
            {
                fprintf(stderr, "Failed to read the response data: %s\n", strerror(errno));
                close(socket_fd);
                exit(-1);
            }
            else if (!rval)
            {
                fprintf(stderr, "Server closed the socket before sending the response data\n");
                close(socket_fd);
                exit(-1);
            }

            message->msg_hdr.code = ntohl(message->msg_hdr.code);
            message->msg_hdr.length = ntohs(message->msg_hdr.length);

            if (mode == PRINT_MODE_DETAIL)
            {
                fprintf(stdout, "Response %04X with code %d and length %u\n",
                    message->hdr.type, message->msg_hdr.code, message->msg_hdr.length);
                DumpHex(stdout, message->msg, message->msg_hdr.length);
            }
            else if (mode == PRINT_MODE_FAST)
            {
                if (message->msg_hdr.length == message->hdr.length - sizeof(message->msg_hdr))
                {
                    message->msg[message->msg_hdr.length-1] = 0;
                    fprintf(stdout, "Response %04X with code %d (%s)\n",
                        message->hdr.type, message->msg_hdr.code, message->msg);
                }
                else
                    fprintf(stdout, "Response %04X with code %d\n", message->hdr.type, message->msg_hdr.code);
            }
        }
        else
        {
            if (mode == PRINT_MODE_DETAIL)
                printf("Response %04X without data\n", message->hdr.type);
            else
                printf("Response %04X\n", message->hdr.type);
        }
    } while (message->hdr.type == CS_HEADER_DATA);
    return 0;
}
Esempio n. 30
-1
//-----------------------------------------------------------------------------
// Name: main()
// Desc: Entry point for the application.  We use just the console window
//-----------------------------------------------------------------------------
int main(int argc, char* argv[])
{
    // Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
    _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif

    int nRet = 0;
    IDirect3DDevice9* pd3dDevice = NULL;
    SETTINGS settings;
    ZeroMemory( &settings, sizeof(SETTINGS) );

    if( argc < 2 )
    {
        DisplayUsage();
        goto LCleanup;
    }

    if( !ParseCommandLine( &settings ) )
    {
        nRet = 0;
        goto LCleanup;
    }

    if( settings.bVerbose )
    {
        wprintf( L"Input file: %s\n", settings.strInputFile );   
        wprintf( L"Output file: %s\n", settings.strOutputFile );   
        wprintf( L"Overwrite: %d\n", settings.bOverwrite );   
        switch( settings.outputType )
        {
            case MESH_TYPE_X_TEXT: wprintf( L"Output format: .x text\n" ); break;
            case MESH_TYPE_X_BINARY: wprintf( L"Output format: .x binary\n" ); break;
            case MESH_TYPE_SDKMESH: wprintf( L"Output format: sdkmesh\n" ); break;
        }
    }

    // Create NULLREF device 
    pd3dDevice = CreateNULLRefDevice(); 
    if( pd3dDevice == NULL )
    {
        wprintf( L"Error: Can not create NULLREF Direct3D device\n" );
        nRet = 1;
        goto LCleanup;
    }
    else
    {
        if( settings.bVerbose )
        {
            wprintf( L"NULLREF Direct3D 9 device created\n" );   
        }

        // Load the mesh
        CLoader loader;
        if( FAILED(loader.Load( settings.strInputFile, FTT_RELATIVE )) )
        {
            wprintf( L"Cannot Load specified input file\n" );
            goto LCleanup;
            nRet = 1;
        }

        // Convert to Little Endian
        loader.GetMesh()->ConvertToLittleEndian();

        // Create a decl that reflects our inputs
        D3DVERTEXELEMENT9 decl[MAX_VERTEX_ELEMENTS];
        BuildVertexDecl( decl, &settings );

        // Convert the mesh to this decl
        loader.GetMesh()->ConvertVertexData( pd3dDevice, decl, MAX_VERTEX_ELEMENTS );

        // fix up the mesh
        loader.GetMesh()->FixMesh();

        // if we need tangents or binormals, generate them
        if( settings.bGenTangents || settings.bGenBinormals )
        {
            if( !loader.GetMesh()->GenerateTangents( pd3dDevice ) )
                wprintf( L"Warning:  Cannot generate tangent frame information for mesh\n" );
        }

        // Save it out
        if( FAILED( loader.Save( pd3dDevice, settings.strOutputFile, settings.outputType ) ) )
        {
            wprintf( L"Cannot Save specified output file\n" );
            goto LCleanup;
            nRet = 1;
        }

        if( settings.bRetainAnimation )
        {
            WCHAR szOutput[MAX_PATH];
            StringCchCopy( szOutput, MAX_PATH, settings.strOutputFile );
            StringCchCat( szOutput, MAX_PATH, L"_anim" );
            if( FAILED( loader.SaveAnimationData( szOutput ) ) )
            {
                wprintf( L"Cannot Save animation data\n" );
            }
        }
    }

LCleanup:
    wprintf( L"\n" );

#ifdef DEBUG_PRESSKEY
    wprintf( L"Press ENTER to continue.");
    _getch();
#endif 

    // Cleanup
    SAFE_RELEASE( pd3dDevice );

    return nRet;
}