コード例 #1
0
ファイル: fstemp.c プロジェクト: AmericoBalboa/core
/* NOTE: pszTempDir must be at least HB_PATH_MAX long. */
HB_ERRCODE hb_fsTempDir( char * pszTempDir )
{
   HB_ERRCODE nResult = ( HB_ERRCODE ) FS_ERROR;

   pszTempDir[ 0 ] = '\0';

#if defined( HB_OS_UNIX )
   {
      char * pszTempDirEnv = hb_getenv( "TMPDIR" );

      if( fsGetTempDirByCase( pszTempDir, pszTempDirEnv, HB_FALSE ) )
         nResult = 0;
#ifdef P_tmpdir
      else if( fsGetTempDirByCase( pszTempDir, P_tmpdir, HB_TRUE ) )
         nResult = 0;
#endif
      else if( fsGetTempDirByCase( pszTempDir, "/tmp", HB_TRUE ) )
         nResult = 0;

      if( pszTempDirEnv )
         hb_xfree( pszTempDirEnv );
   }
#elif defined( HB_OS_WIN )
   {
      TCHAR lpDir[ HB_PATH_MAX ];

      if( GetTempPath( HB_PATH_MAX, lpDir ) )
      {
         nResult = 0;
         lpDir[ HB_PATH_MAX - 1 ] = TEXT( '\0' );
         HB_OSSTRDUP2( lpDir, pszTempDir, HB_PATH_MAX - 1 );
      }
   }
#else
   {
#if ! defined( HB_OS_OS2 )
      char szBuffer[ L_tmpnam ];

      if( tmpnam( szBuffer ) != NULL )
      {
         PHB_FNAME pTempName = hb_fsFNameSplit( szBuffer );
         if( fsGetTempDirByCase( pszTempDir, pTempName->szPath, HB_TRUE ) )
            nResult = 0;
         hb_xfree( pTempName );
      }
      if( nResult != 0 )
#endif
      {
         static const char * env_tmp[] = { "TEMP", "TMP", "TMPDIR", NULL };

         const char ** tmp = env_tmp;

         while( *tmp && nResult != 0 )
         {
            char * pszTempDirEnv = hb_getenv( *tmp++ );

            if( pszTempDirEnv )
            {
               if( fsGetTempDirByCase( pszTempDir, pszTempDirEnv, HB_FALSE ) )
                  nResult = 0;
               hb_xfree( pszTempDirEnv );
            }
         }
      }
   }
#endif

   if( nResult == 0 && pszTempDir[ 0 ] != '\0' )
   {
      int len = ( int ) strlen( pszTempDir );
      if( pszTempDir[ len - 1 ] != HB_OS_PATH_DELIM_CHR &&
          len < HB_PATH_MAX - 1 )
      {
         pszTempDir[ len ] = HB_OS_PATH_DELIM_CHR;
         pszTempDir[ len + 1 ] = '\0';
      }
   }
   else
   {
      pszTempDir[ 0 ] = '.';
      pszTempDir[ 1 ] = HB_OS_PATH_DELIM_CHR;
      pszTempDir[ 2 ] = '\0';
   }

   return nResult;
}
コード例 #2
0
ファイル: CDDialog.cpp プロジェクト: kthxbyte/KDE1-Linaro
void CDDialog::upload(){

  if(!checkit())
    return;

  /*
  switch( QMessageBox::information( this,klocale->translate("Message"),

klocale->translate(
"The submission you are about to make will go to the test server\n"\
"[email protected]. This is because this is the first release of\n"\
"the cddb addition to Kscd and I need to avoid corruption\n"\
"of the remote cddb data bases due to possible bugs in Kscd.\n"\
"Since we need about a 100 error free test submissions\n"\
"before we will be granted write acces to the 'true' cddb databases, 
I would like you ask you to upload as many test submissions as possible.\n"\
"You don't need to try to find a CD that is not in the database \n"\
"(thought that would be helpful),it suffices to submit existing\n"\
"entries with Kscd.\n"\
"After submission you should receive a mail notifying you of success or\n"\
"or failure of your submission. Should you receive a failure notice\n"\
"please forward the failure report to me: <*****@*****.**>\n"\
"Check back often for the availablity of a fully enabled version of kscd.\n"\
"Thank you for your support.\n"),
				    klocale->translate("OK"),
				    klocale->translate("Cancel"),
				    0,
				    1 ) ){

  case 0: 
    break;
  case 1: 
    return;
    break;
  }

  */


  InexactDialog *dialog;

  dialog = new InexactDialog(0,"Dialog",true);


  QStrList catlist;

  catlist.append("rock");
  catlist.append("classical");
  catlist.append("jazz");
  catlist.append("soundtrack");
  catlist.append("newage");
  catlist.append("blues");
  catlist.append("folk");
  catlist.append("country");
  catlist.append("reggae");
  catlist.append("misc");
  catlist.append("data");

  dialog->insertList(catlist);
  dialog->setErrorString((char *)klocale->translate("Please select a Category or press Cancel"));
  dialog->setTitle((char *)klocale->translate("To which category does the CD belong?"));
  if(dialog->exec() != QDialog::Accepted){
    delete dialog;
    return;
  }

  dialog->getSelection(submitcat);
  delete dialog;

  QString tempfile;
  tempfile = tempfile.sprintf("%s",tmpnam(0L));

  save_cddb_entry(tempfile,true);

  mykapp->processEvents();
  mykapp->flushX();


/*  QString subject;
  subject.sprintf("cddb %s %08lx",submitcat.data(),cdinfo.magicID);

  QString formatstr;
  //  formatstr = mailcmd + " [email protected]";
  formatstr = mailcmd;
  formatstr += " ";
  formatstr += submitaddress;
  */
  if(smtpConfigData->enabled){
      if(debugflag)
          printf("Submitting cddb entry via SMTP...\n");
      QFile file(tempfile);

      file.open(IO_ReadOnly);
      QTextStream ti(&file);

      QString s;
      QString subject;
      
      while (!ti.eof()){
          s += ti.readLine() + "\r\n";
//          if(!ti.eof()){
              //  mimetranslate(s);
//              to << s.data() << '\n';
 //         }
      }

//      smtpMailer = new SMTP;

      smtpMailer->setServerHost(smtpConfigData->serverHost.data());
      smtpMailer->setPort(smtpConfigData->serverPort.toInt());
      
      smtpMailer->setSenderAddress(smtpConfigData->senderAddress.data());
      smtpMailer->setRecipientAddress(submitaddress.data());
      
      subject.sprintf("cddb %s %08lx", submitcat.data(), cdinfo.magicID);
      smtpMailer->setMessageSubject(subject.data());
      smtpMailer->setMessageBody(s.data());

      smtpMailer->sendMessage();
      
      return;
  }

      
  QString cmd;
  //  cmd = cmd.sprintf("mail -s \"%s\" [email protected]",subject.data());
  //  cmd = cmd.sprintf("sendmail [email protected]");
  cmd = cmd.sprintf("sendmail -tU");
  //  cmd = cmd.sprintf(formatstr.data(),subject.data());

  if (debugflag ) printf(klocale->translate("Submitting cddb entry: %s\n"),cmd.data());
  
  FILE* mailpipe;
  mailpipe = popen(cmd.data(),"w");

  if(mailpipe == NULL){
    QString str;
    str.sprintf(klocale->translate("Could not pipe contents into:\n %s"),cmd.data());

    QMessageBox::critical(this, "Kscd", str.data());
    pclose(mailpipe);
    return;
    
  }
  
  QFile file(tempfile);
  //  QFile file2("/home/wuebben/test.txt"); // ******

  file.open(IO_ReadOnly);
  //file2.open(IO_ReadWrite); // ******
  QTextStream ti(&file);
  //QTextStream to(&file2); // ******

  QTextStream to(mailpipe,IO_WriteOnly );

  QString s;

  //to << "Content-Transfer-Encoding: quoted-printable\n";

  while ( !ti.eof() ) {
      s = ti.readLine();
      if(!ti.eof()){
          //  mimetranslate(s);
          to << s.data() << '\n';
      }
  }

  pclose(mailpipe);

  file.close();
  //  file2.close();   // *****

  unlink(tempfile.data());
  if ( debugflag ) printf("DONE SENDING\n");
}
コード例 #3
0
ファイル: loadsave.cpp プロジェクト: glo/ee384b
static void*
imdecode_( const Vector<uchar>& buf, int flags, int hdrtype, Mat* mat=0 )
{
    IplImage* image = 0;
    CvMat *matrix = 0;
    Mat temp, *data = &temp;
    char fnamebuf[L_tmpnam];
    const char* filename = 0;

    ImageDecoder decoder = findDecoder(buf);
    if( !decoder.obj )
        return 0;

    if( !decoder->setSource(buf) )
    {
        filename = tmpnam(fnamebuf);
        FILE* f = fopen( filename, "wb" );
        if( !f )
            return 0;
        fwrite( &buf[0], 1, buf.size(), f );
        fclose(f);
        decoder->setSource(filename);
    }

    if( !decoder->readHeader() )
    {
        if( filename )
            unlink(filename);
        return 0;
    }

    CvSize size;
    size.width = decoder->width();
    size.height = decoder->height();

    int type = decoder->type();
    if( flags != -1 )
    {
        if( (flags & CV_LOAD_IMAGE_ANYDEPTH) == 0 )
            type = CV_MAKETYPE(CV_8U, CV_MAT_CN(type));

        if( (flags & CV_LOAD_IMAGE_COLOR) != 0 ||
           ((flags & CV_LOAD_IMAGE_ANYCOLOR) != 0 && CV_MAT_CN(type) > 1) )
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 3);
        else
            type = CV_MAKETYPE(CV_MAT_DEPTH(type), 1);
    }

    if( hdrtype == LOAD_CVMAT || hdrtype == LOAD_MAT )
    {
        if( hdrtype == LOAD_CVMAT )
        {
            matrix = cvCreateMat( size.height, size.width, type );
            temp = cvarrToMat(matrix);
        }
        else
        {
            mat->create( size.height, size.width, type );
            data = mat;
        }
    }
    else
    {
        image = cvCreateImage( size, cvIplDepth(type), CV_MAT_CN(type) );
        temp = cvarrToMat(image);
    }

    bool code = decoder->readData( *data );
    if( filename )
        unlink(filename);

    if( !code )
    {
        cvReleaseImage( &image );
        cvReleaseMat( &matrix );
        if( mat )
            mat->release();
        return 0;
    }

    return hdrtype == LOAD_CVMAT ? (void*)matrix :
        hdrtype == LOAD_IMAGE ? (void*)image : (void*)mat;
}
コード例 #4
0
ファイル: spawn.c プロジェクト: pavanvunnava/open-watcom-v2
long MySpawn( const char *cmd )
{
    bool        cp;
    long        rc;
    exec_block  exeparm;
    _fcb        fcb1, fcb2;
    cmd_struct  cmds;
    char        path[_MAX_PATH], file[_MAX_PATH];
    tiny_ret_t  ret;
    int         i;
    char        chkfname[L_tmpnam];

    minMemoryLeft = MaxMemFree & ~((long)MAX_IO_BUFFER - 1);
    chkSwapSize = 1 + (unsigned short)
                  (((minMemoryLeft + ((long)MAX_IO_BUFFER - 1)) & ~((long)MAX_IO_BUFFER - 1)) /
                   (long)MAX_IO_BUFFER);

    /*
     * set up checkpoint file stuff:
     */
#ifndef NOEMS
    if( !EMSBlockTest( chkSwapSize ) ) {
        xHandle = alloca( chkSwapSize * sizeof( long ) );
        xSize = alloca( chkSwapSize * sizeof( short ) );
        for( i = 0; i < chkSwapSize; i++ ) {
            EMSGetBlock( &xHandle[i] );
        }
        isWhere = IN_EMS;
        currMem = 0;
        goto evil_goto;
    }
#endif
#ifndef NOXMS
    if( !XMSBlockTest( chkSwapSize ) ) {
        xHandle = alloca( chkSwapSize * sizeof( long ) );
        xSize = alloca( chkSwapSize * sizeof( short ) );
        for( i = 0; i < chkSwapSize; i++ ) {
            XMSGetBlock( &xHandle[i] );
        }
        isWhere = IN_XMS;
        currMem = 0;
        goto evil_goto;
    }
#endif
    file[0] = 0;
    tmpnam( chkfname );
    StrMerge( 3, file, TmpDir, FILE_SEP_STR, chkfname );
    fullName = file;
    ret = TinyCreate( fullName, TIO_NORMAL );
    if( ret < 0 ) {
        return( 0 );
    }
    fileHandle = ret;
    isWhere = ON_DISK;

    /*
     * build command line
     */
evil_goto:
    GetSpawnCommandLine( path, cmd, &cmds );

    /*
     * set up parm block
     */
    exeparm.envp = 0;
    exeparm.cmdline = &cmds;
    exeparm.fcb1 = fcb1;
    exeparm.fcb2 = fcb2;
    GetFcb( &cmds.cmd, &fcb1 );
    GetFcb( &cmds.cmd, &fcb2 );

    /*
     * spawn the command
     */
    cp = checkPointMem( minMemoryLeft / 16 );
    rc = DoSpawn( path, &exeparm );
    if( cp ) {
        CheckPointRestore();
    }

    return( rc );
}
コード例 #5
0
ファイル: hsys.c プロジェクト: ajinkya93/OpenBSD
int HandleSysMessage(Packet *packet, hsys_state *stateptr)
{
  unsigned int reason_code, mode, len, c, nbytes, nbtotal, nbtogo = 0;
  long posn, fl;
  char character;
  int err;

  /* Note: We must not free the buffer passed in as the callback handler */
  /* expects to do this.  Freeing any other buffers we have malloced */
  /* ourselves is acceptable */

  unsigned char *buffp = ((unsigned char *)BUFFERDATA(packet->pk_buffer))+16;
                                          /* buffp points to the parameters*/
                                          /* the invidual messages, excluding*/
                                          /* standard SYS fields (debugID, */
                                          /* osinfo and reasoncode) */
  unsigned char *buffhead = (unsigned char *)(packet->pk_buffer);

  int DebugID, OSInfo1, OSInfo2, count;

  const char* fmode[] = {"r","rb","r+","r+b",
                               "w","wb","w+","w+b",
                               "a","ab","a+","a+b",
                               "r","r","r","r"} /* last 4 are illegal */ ;

  FILEHANDLE fh;  /* fh is used as an index to the real file handle
                         * in OSptr */  
  FILE *fhreal;
  unpack_message(BUFFERDATA(buffhead), "%w%w%w%w", &reason_code,
                 &DebugID, &OSInfo1, &OSInfo2);
                                        /* Extract reason code from buffer. */
  reason_code &= 0xFFFF;        /* Strip away direction bit, OSInfo and     */
                                /* DebugInfo fields.  Will want to do some  */
                                /* sort of validation on this later.        */
  
  switch(reason_code)
  {

  case CL_WriteC:   /* Write a character to the terminal. */
                    /* byte data -> word status           */
    {
#ifdef DEBUG
      int c = (int)(*buffp);
      printf("CL_WriteC: [%02x]>%c<", c, isprint(c) ? c : '.');
#endif
      stateptr->hostif->writec(stateptr->hostif->hostosarg, (int)(*buffp));
      DevSW_FreePacket(packet);
      return msgsend(CI_CLIB,"%w%w%w%w%w", CL_WriteC|HtoT,
                    DebugID, OSInfo1, OSInfo2, NoError);
    }

  case CL_Write0:  /* Write a null terminated string to the terminal. */
    {
      unpack_message(buffp, "%w", &len);
      DebugCheckNullTermString("CL_Write0", TRUE, len, buffp+4);
      stateptr->hostif->write(stateptr->hostif->hostosarg,
                              (char *) buffp+4, len);
      DevSW_FreePacket(packet);
      return msgsend(CI_CLIB, "%w%w%w%w%w", CL_Write0|HtoT, DebugID, 
                    OSInfo1, OSInfo2, NoError);
    }

  case CL_ReadC:   /* Read a byte from the terminal */
    {
      DebugPrintF(("CL_ReadC: "));
      DevSW_FreePacket(packet);

      character = stateptr->hostif->readc(stateptr->hostif->hostosarg);
      DebugPrintF(("\nCL_ReadC returning [%02x]>%c<\n", character,
                   isprint(character) ? character : '.'));

      return msgsend(CI_CLIB, "%w%w%w%w%w%b", CL_ReadC|HtoT,
                    DebugID, OSInfo1, OSInfo2, NoError, character);
    }

  case CL_System:  /* Pass NULL terminated string to the hosts command 
                    * interpreter. As it is nULL terminated we dont need
                    * the length
                    */
    {
      unpack_message(buffp, "%w", &len);
      DebugCheckNullTermString("CL_System", TRUE, len, buffp+4);

      err = system((char *)buffp+4); /* Use the string in the buffer */
      stateptr->last_errno = errno;
      DebugCheckErr("system", TRUE, err, stateptr->last_errno);

      err = msgsend(CI_CLIB, "%w%w%w%w%w%w", CL_System|HtoT,
                    DebugID, OSInfo1, OSInfo2, NoError, err);
      DevSW_FreePacket(packet);
      return err;
    }

  case CL_GetCmdLine:  /* Returns the command line used to call the program */
    {
      /* Note: we reuse the packet here, this may not always be desirable */
      /* /* TODO: Use long buffers if possible */
      DebugPrintF(("CL_GetCmdLine: \"%s\"\n", *(stateptr->CommandLine)));

      if (buffhead!=NULL) {
        len = strlen(*(stateptr->CommandLine));
        if (len > Armsd_BufferSize-24) len = Armsd_BufferSize-24; 
        packet->pk_length = len + msgbuild(BUFFERDATA(buffhead),
                                           "%w%w%w%w%w%w", CL_GetCmdLine|HtoT,
                                           DebugID, OSInfo1, OSInfo2,
                                           NoError, len);
        strncpy((char *) BUFFERDATA(buffhead)+24,*(stateptr->CommandLine),
                len);
        
        Adp_ChannelWrite(CI_CLIB, packet);/* Send message. */
        return 0;
      }
      else return -1;
    }

  case CL_Clock:   /* Return the number of centiseconds since the support */
                   /* code started executing */
    {
      time_t retTime = time(NULL);
      if (retTime == (time_t)-1)
             stateptr->last_errno = errno;
      else
             retTime *=100;

      DebugPrintF(("CL_Clock: %lu\n", retTime));
      DebugCheckErr("time", TRUE, (retTime == (time_t)-1),
                    stateptr->last_errno);

      DevSW_FreePacket(packet);
      return msgsend(CI_CLIB, "%w%w%w%w%w%w",CL_Clock|HtoT,
                         DebugID, OSInfo1, OSInfo2, NoError, retTime);
    }

  case CL_Time:    /* return time, in seconds since the start of 1970 */
    {
      time_t retTime = time(NULL);
      if (retTime == (time_t)-1)
              stateptr->last_errno = errno;

      DebugPrintF(("CL_Time: %lu\n", retTime));
      DebugCheckErr("time", TRUE, (retTime == (time_t)-1),
                    stateptr->last_errno);

      DevSW_FreePacket(packet);
      return msgsend(CI_CLIB,"%w%w%w%w%w%w",CL_Time|HtoT,
                         DebugID, OSInfo1, OSInfo2, NoError, retTime);
    }

  case CL_Remove:  /* delete named in the null terminated string */
    {
      /* Removing an open file will cause problems but once again
       * its not our problem, likely result is a tangled FileTable */
      /* As the filename is passed with a null terminator we can use it
       * straight out of the buffer without copying it.*/

      unpack_message(buffp, "%w", &len);
      DebugCheckNullTermString("CL_Remove", TRUE, len, buffp+4);

      err=remove((char *)buffp+4);
      stateptr->last_errno = errno;
      DevSW_FreePacket(packet);
      DebugCheckErr("remove", TRUE, err, stateptr->last_errno);

      return msgsend(CI_CLIB, "%w%w%w%w%w", CL_Remove|HtoT,
                     DebugID, OSInfo1, OSInfo2, err?-1:NoError);
    }

  case CL_Rename:  /* rename file */
    {
      /* Rename(word nbytes, bytes oname, word nbytes, bytes nname)
      * return(byte status)
      */
      unsigned int len2;

      unpack_message(buffp, "%w", &len);
      DebugCheckNullTermString("CL_Rename", FALSE, len, buffp+4);
      unpack_message(buffp+5+len, "%w", &len2);
      DebugCheckNullTermString("to", TRUE, len2, buffp+9+len);

      /* Both names are passed with null terminators so we can use them
       * directly from the buffer. */
      err = rename((char *)buffp+4, (char *)buffp+9+len);
      stateptr->last_errno = errno;
      DebugCheckErr("rename", TRUE, err, stateptr->last_errno);
      DevSW_FreePacket(packet);

      return msgsend(CI_CLIB, "%w%w%w%w%w",  CL_Rename|HtoT,
                     DebugID, OSInfo1, OSInfo2, (err==0)? NoError : -1);
    }
  
  case CL_Open:    /* open the file */
    {
      /* Open(word nbytes, bytes name, byte mode)
      * return(word handle)
      */
      unpack_message(buffp, "%w", &len);
      /* get the open mode */
      unpack_message((buffp)+4+len+1, "%w", &mode);
      DebugCheckNullTermString("CL_Open", FALSE, len, buffp+4);
      DebugPrintF(("mode: %d\n", mode));

      /* do some checking on the file first? */
      /* check if its a tty */
      if (strcmp((char *)buffp+4, ":tt")==0 && (mode==0||mode==1)) {
        /* opening tty "r" */
        fhreal = stdin;
        stateptr->last_errno = errno;
        DebugPrintF(("\tstdin "));
      }
      else if (strcmp((char *)buffp+4, ":tt")== 0 && (mode==4||mode==5)) {
        /* opening tty "w" */
        fhreal = stdout;
        stateptr->last_errno = errno;
        DebugPrintF(("\tstdout "));
      }
      else
      {
        fhreal = fopen((char *)buffp+4, fmode[mode&0xFF]);
        stateptr->last_errno = errno;
        DebugCheckNonNull("fopen", FALSE, fhreal, stateptr->last_errno);
      }
      DevSW_FreePacket(packet);

      c = NONHANDLE;
      if (fhreal != NULL) {
        /* update filetable */
        for (c=3; c < HSYS_FOPEN_MAX; c++) {
          /* allow for stdin, stdout, stderr (!!! WHY? MJG) */
          if (stateptr->OSptr->FileTable[c] == NULL) {
            stateptr->OSptr->FileTable[c]= fhreal;
            stateptr->OSptr->FileFlags[c]= mode & 1;
            DebugPrintF(("fh: %d\n", c));
            break;
          }
          else if (c == HSYS_FOPEN_MAX) {
          /* no filehandles free */
          DebugPrintF(("no free fh: %d\n", c));
          stateptr->last_errno = EMFILE;
          }
        }
      }
      else {
        /*        c = NULL;*/
        DebugPrintF(("error fh: %d\n", c));
      }
      (void) msgsend(CI_CLIB, "%w%w%w%w%w",  CL_Open|HtoT,
                     DebugID, OSInfo1, OSInfo2, c);
      return 0;
    }

  case CL_Close:   /* close the file pointed to by the filehandle */
    {
      unpack_message(buffp, "%w", &fh);
      DebugPrintF(("CL_Close: fh %d\n", fh));
      DevSW_FreePacket(packet);

      fhreal = hsysGetRealFileHandle(stateptr, fh, NULL);
      if (fhreal == NULL)
         err = -1;
      else {
          if (fhreal == stdin || fhreal == stdout || fhreal == stderr) {
              stateptr->last_errno = errno;
              DebugPrintF(("\tskipping close of std*\n"));
              err = 0;
          }
          else {
              err = fclose(fhreal);
              if (err == 0)
                 stateptr->OSptr->FileTable[fh]=NULL;
              stateptr->last_errno = errno;
              DebugCheckErr("fclose", TRUE, err, stateptr->last_errno);
          }
      }
      return msgsend(CI_CLIB,"%w%w%w%w%w",  CL_Close|HtoT, DebugID,
                     OSInfo1, OSInfo2, err);
    }

  case CL_Write:
    {
        /* Write(word handle, word nbtotal, word nbytes, bytes data)
         * return(word nbytes)
         * WriteX(word nbytes, bytes data)
         * return(word nbytes)
         */
      unsigned char *rwdata = NULL, *rwhead = NULL;
      unsigned char *write_source = NULL;
      char flags;
      FILE *fhreal;
      unsigned int ack_reason = CL_Write; /* first ack is for CL_Write */

      err = -1;                 /* err == 0 is fwrite() error indication */
      unpack_message(buffp, "%w%w%w", &fh, &nbtotal, &nbytes); 
      DebugPrintF(("CL_Write: fh %d nbtotal %u nbytes %u\n",
                   fh, nbtotal, nbytes));

      fhreal = hsysGetRealFileHandle(stateptr, fh, &flags);
      nbtogo = nbtotal;

      /* deal with the file handle */
      if (fhreal == NULL)
         err = 0;
      else {
        if (flags & READOP)
           fseek(fhreal,0,SEEK_CUR);
        stateptr->OSptr->FileFlags[fh] = (flags & BINARY) | WRITEOP;

        nbtogo -= nbytes;

        if (nbtogo > 0) {
          write_source = rwdata = rwhead = (unsigned char *)malloc(nbtotal);
          if (rwhead == NULL) {
            fprintf(stderr, "OUT OF MEMORY at line %d in %s\n",
                    __LINE__, __FILE__);
            return -1;
          }
          memcpy(rwdata, buffp+12, nbytes);
          rwdata += nbytes;
        }
        else
           write_source = buffp+12;
      }

      do {
        /* at least once!! */

        if (nbtogo == 0 && err != 0) {
          /* Do the actual write! */
          if (fhreal == stdout || fhreal == stderr) {
            stateptr->hostif->write(stateptr->hostif->hostosarg,
                                    (char *)write_source, nbtotal);
          }
          else 
             err = fwrite(write_source, 1, nbtotal, fhreal);
          stateptr->last_errno = errno;
          DebugCheckErr("fwrite", TRUE, (err == 0), stateptr->last_errno);
        }

        DevSW_FreePacket(packet);
        if (msgsend(CI_CLIB,"%w%w%w%w%w%w", ack_reason|HtoT,
                    DebugID, OSInfo1, OSInfo2, (err == 0), nbtogo))
        {
            fprintf(stderr, "COULD NOT REPLY at line %d in %s\n",
                    __LINE__, __FILE__);
            if (rwhead != NULL)
               free(rwhead);
            return -1;
        }

        if (nbtogo == 0 || err == 0) {
          DebugPrintF(("\twrite complete - returning\n"));
          if (rwhead != NULL)
             free(rwhead);
          return 0;
        }
        else {
          /* await extension */
          ack_reason = CL_WriteX;

          packet = DevSW_AllocatePacket(Armsd_BufferSize);
          if (packet == NULL)
          {
            fprintf(stderr, "COULD NOT ALLOC PACKET at line %d in %s\n",
                    __LINE__, __FILE__);
            if (rwhead != NULL)
               free(rwhead);
            return -1;
          }
          Adp_ChannelRegisterRead(CI_CLIB, NULL, NULL);
          Adp_ChannelRead(CI_CLIB, &packet);
          Adp_ChannelRegisterRead(CI_CLIB,
                                  (ChannelCallback)HandleSysMessage,
                                  stateptr);

          buffhead = packet->pk_buffer;
          unpack_message(BUFFERDATA(buffhead), "%w%w%w%w%w", &reason_code,
                         &DebugID, &OSInfo1, &OSInfo2, &nbytes); 
          if (reason_code != (CL_WriteX|TtoH)) {
            DevSW_FreePacket(packet);
            free(rwhead);
            fprintf(stderr, "EXPECTING CL_WriteX GOT %u at line %d in %s\n",
                    reason_code, __LINE__, __FILE__);
            return -1;
          }

          DebugPrintF(("CL_WriteX: nbytes %u\n", nbytes));
          memcpy(rwdata, BUFFERDATA(buffhead)+20, nbytes);
          rwdata += nbytes;
          nbtogo -= nbytes;
        }

      } while (TRUE);           /* will return when done */
    }

  case CL_WriteX:     /*
                       * NOTE: if we've got here something has gone wrong
                       * CL_WriteX's should all be picked up within the
                       * CL_Write loop, probably best to return an error here
                       * do this for the moment just so we do actually return
                       */
    fprintf(stderr, "ERROR: unexpected CL_WriteX message received\n");
    return -1; 

  case CL_Read:
    {
                   /* Read(word handle, word nbtotal)
                    * return(word nbytes, word nbmore, bytes data)
                    */
                   /* ReadX()
                    * return(word nbytes, word nbmore, bytes data) */
      unsigned char *rwdata, *rwhead;
      int gotlen;
      unsigned int max_data_in_buffer=Armsd_BufferSize-28;
      char flags;
      FILE *fhreal;
      unsigned int nbleft = 0, reason = CL_Read;

      err = NoError;

      unpack_message(buffp, "%w%w", &fh, &nbtotal);
      DebugPrintF(("CL_Read: fh %d, nbtotal %d: ", fh, nbtotal));

      rwdata = rwhead = (unsigned char *)malloc(nbtotal);
      if (rwdata == NULL) {
        fprintf(stderr, "OUT OF MEMORY at line %d in %s\n",
                __LINE__, __FILE__);
        DevSW_FreePacket(packet);
        return -1;
      }

      /* perform the actual read */
      fhreal = hsysGetRealFileHandle(stateptr, fh, &flags);
      if (fhreal == NULL)
      {
        /* bad file handle */
        err = -1;
        nbytes = 0;
        gotlen = 0;
      }
      else
      {
        if (flags & WRITEOP)
          fseek(fhreal,0,SEEK_CUR);
        stateptr->OSptr->FileFlags[fh] = (flags & BINARY) | WRITEOP;
        if (isatty_(fhreal)) {
          /* reading from a tty, so do some nasty stuff, reading into rwdata */
          if (angel_hostif->gets(stateptr->hostif->hostosarg, (char *)rwdata,
                                 nbtotal) != 0)
             gotlen = strlen((char *)rwdata);
          else
             gotlen = 0;
          stateptr->last_errno = errno;
          DebugPrintF(("ttyread %d\n", gotlen));
        }
        else {
          /* not a tty, reading from a real file */
          gotlen = fread(rwdata, 1, nbtotal, fhreal);
          stateptr->last_errno = errno;
          DebugCheckErr("fread", FALSE, (gotlen == 0), stateptr->last_errno);
          DebugPrintF(("(%d)\n", gotlen));
        }
      }

      nbtogo = gotlen;

      do {
        /* at least once */

        if ((unsigned int) nbtogo <= max_data_in_buffer)
           nbytes = nbtogo;
        else
           nbytes = max_data_in_buffer;
        nbtogo -= nbytes;

        /* last ReadX needs subtle adjustment to returned nbtogo */
        if (nbtogo == 0 && err == NoError && reason == CL_ReadX)
           nbleft = nbtotal - gotlen;
        else
           nbleft = nbtogo;

        count = msgbuild(BUFFERDATA(buffhead), "%w%w%w%w%w%w%w",
                         reason|HtoT, 0, ADP_HandleUnknown,
                         ADP_HandleUnknown, err, nbytes, nbleft);

        if (err == NoError) {
          /* copy data into buffptr */   
          memcpy(BUFFERDATA(buffhead)+28, rwdata, nbytes);
          rwdata += nbytes;
          count += nbytes;
        }

        DebugPrintF(("\treplying err %d, nbytes %d, nbtogo %d\n",
                     err, nbytes, nbtogo));

        packet->pk_length = count;
        Adp_ChannelWrite(CI_CLIB, packet);

        if (nbtogo == 0 || err != NoError) {
          /* done */
          free(rwhead);
          return 0;
        }
        else {
          /* await extension */
          reason = CL_ReadX;

          packet = DevSW_AllocatePacket(Armsd_BufferSize);
          if (packet == NULL) {
            fprintf(stderr, "COULD NOT ALLOC PACKET at line %d in %s\n",
                    __LINE__, __FILE__);
            free(rwhead);
            return -1;
          }
          Adp_ChannelRegisterRead(CI_CLIB, NULL, NULL);
          Adp_ChannelRead(CI_CLIB, &packet);
          Adp_ChannelRegisterRead(CI_CLIB,
                                  (ChannelCallback)HandleSysMessage,
                                  stateptr);
          buffhead = packet->pk_buffer;
          unpack_message(BUFFERDATA(buffhead),"%w", &reason_code);
          if (reason_code != (CL_ReadX|TtoH)) {
            fprintf(stderr, "EXPECTING CL_ReadX GOT %u at line %d in %s\n",
                    reason_code, __LINE__, __FILE__);
            DevSW_FreePacket(packet);
            free(rwdata);
            return -1;
          }
        }

      } while (TRUE);           /* will return above on error or when done */
    }

  case CL_ReadX:      /* If we're here something has probably gone wrong */
    fprintf(stderr, "ERROR: Got unexpected CL_ReadX message\n");
    return -1;

  case CL_Seek:
    {
      unpack_message(buffp, "%w%w", &fh, &posn);
      DebugPrintF(("CL_Seek: fh %d, posn %ld\n", fh, posn));
      DevSW_FreePacket(packet);

      fhreal = hsysGetRealFileHandle(stateptr, fh, NULL);
      if (fhreal == NULL)
         err = -1;
      else {
        err = fseek(fhreal, posn, SEEK_SET); 
        stateptr->last_errno = errno;
        DebugCheckErr("fseek", TRUE, err, stateptr->last_errno);
      }

      return msgsend(CI_CLIB, "%w%w%w%w%w", CL_Seek|HtoT, 
                         DebugID, OSInfo1, OSInfo2, err);
    }

  case CL_Flen:
    {
      unpack_message(buffp, "%w", &fh);
      DebugPrintF(("CL_Flen: fh %d ", fh));
      DevSW_FreePacket(packet);

      fhreal = hsysGetRealFileHandle(stateptr, fh, NULL);
      if (fhreal == NULL)
        fl = -1;
      else {
        posn = ftell(fhreal);
        if (fseek(fhreal, 0L, SEEK_END) < 0) {
          fl=-1;
        }
        else {
          fl = ftell(fhreal);
          fseek(fhreal, posn, SEEK_SET);
        }
        stateptr->last_errno = errno;
      }
      DebugPrintF(("returning len %ld\n", fl));
      return msgsend(CI_CLIB, "%w%w%w%w%w", CL_Flen|HtoT, DebugID, OSInfo1,
                     OSInfo2, fl);
    } 

  case CL_IsTTY:
    {
      int  ttyOrNot;
      unpack_message(buffp, "%w", &fh);
      DebugPrintF(("CL_IsTTY: fh %d ", fh));
      DevSW_FreePacket(packet);

      fhreal = hsysGetRealFileHandle(stateptr, fh, NULL);
      if (fhreal == NULL)
         ttyOrNot = FALSE;
      else {
        ttyOrNot = isatty_(fhreal);
        stateptr->last_errno = errno;
      }
      DebugPrintF(("returning %s\n", ttyOrNot ? "tty (1)" : "not (0)"));

      return msgsend(CI_CLIB, "%w%w%w%w%w",CL_IsTTY|HtoT, 
                         DebugID, OSInfo1, OSInfo2, ttyOrNot);
    }

  case CL_TmpNam:
    {
      char *name;
      unsigned int tnamelen, TargetID;
      unpack_message(buffp, "%w%w", &tnamelen, &TargetID); 
      DebugPrintF(("CL_TmpNam: tnamelen %d TargetID %d: ",
                   tnamelen, TargetID));
      DevSW_FreePacket(packet);

      TargetID = TargetID & 0xFF;
      if (stateptr->OSptr->TempNames[TargetID] == NULL) {
        if ((stateptr->OSptr->TempNames[TargetID] =
             (char *)malloc(L_tmpnam)) == NULL)
        {
          fprintf(stderr, "OUT OF MEMORY at line %d in %s\n",
                  __LINE__, __FILE__);
          return -1;
        }
        tmpnam(stateptr->OSptr->TempNames[TargetID]);
      }
      name = stateptr->OSptr->TempNames[TargetID];
      len = strlen(name) + 1;
      packet = DevSW_AllocatePacket(Armsd_BufferSize);
      if (packet == NULL)
      {
          fprintf(stderr, "COULD NOT ALLOC PACKET at line %d in %s\n",
                  __LINE__, __FILE__);
          return -1;
      }
      buffhead = packet->pk_buffer;
      if (len > tnamelen) {
        DebugPrintF(("TMPNAME TOO LONG!\n"));
        count = msgbuild(BUFFERDATA(buffhead), "%w%w%w%w%w",
                           CL_TmpNam|HtoT, DebugID, OSInfo1, OSInfo2, -1);
      }
      else {
        DebugPrintF(("returning \"%s\"\n", name));
        count = msgbuild(BUFFERDATA(buffhead), "%w%w%w%w%w%w", CL_TmpNam|HtoT,
                         DebugID, OSInfo1, OSInfo2, 0, len);
        strcpy((char *)BUFFERDATA(buffhead)+count, name);
        count +=len+1;
      }
      packet->pk_length = count;
      Adp_ChannelWrite(CI_CLIB, packet);/* Send message. */
      return 0;
    }

  case CL_Unrecognised:
    DebugPrintF(("CL_Unrecognised!!\n"));
    return 0;

  default:
    fprintf(stderr, "UNRECOGNISED CL code %08x\n", reason_code);
    break;
/* Need some sort of error handling here. */
/* A call to CL_Unrecognised should suffice */
  }
  return -1;  /* Stop a potential compiler warning */
}
コード例 #6
0
ファイル: stdio.c プロジェクト: AKuHAK2/ps2sdk
/*
**
**  [func] - tmpfile.
**  [desc] - attempts to create a temporary file. if able to create a temporary
**           file then returns the pointer to the FILE stream. else returns NULL.
**  [entr] - none.
**  [exit] - FILE *; the ptr. to the opened temp. file if successful. else NULL.
**  [prec] - none.
**  [post] - a temporary is opened.
**
*/
FILE *tmpfile(void)
{
  return ((tmpnam(NULL) != NULL) ?  fopen(__stdio_tmpnam, "rw+") : NULL);
}
コード例 #7
0
ファイル: link.c プロジェクト: Krox/dmd
int runLINK()
{
#if _WIN32
    if (global.params.is64bit)
    {
        OutBuffer cmdbuf;

        cmdbuf.writestring("/NOLOGO ");

        for (size_t i = 0; i < global.params.objfiles->dim; i++)
        {
            if (i)
                cmdbuf.writeByte(' ');
            const char *p = (*global.params.objfiles)[i];
            const char *basename = FileName::removeExt(FileName::name(p));
            const char *ext = FileName::ext(p);
            if (ext && !strchr(basename, '.'))
            {
                // Write name sans extension (but not if a double extension)
                writeFilename(&cmdbuf, p, ext - p - 1);
            }
            else
                writeFilename(&cmdbuf, p);
            FileName::free(basename);
        }

        if (global.params.resfile)
        {
            cmdbuf.writeByte(' ');
            writeFilename(&cmdbuf, global.params.resfile);
        }

        cmdbuf.writeByte(' ');
        if (global.params.exefile)
        {   cmdbuf.writestring("/OUT:");
            writeFilename(&cmdbuf, global.params.exefile);
        }
        else
        {   /* Generate exe file name from first obj name.
             * No need to add it to cmdbuf because the linker will default to it.
             */
            const char *n = (*global.params.objfiles)[0];
            n = FileName::name(n);
            global.params.exefile = (char *)FileName::forceExt(n, "exe");
        }

        // Make sure path to exe file exists
        ensurePathToNameExists(Loc(), global.params.exefile);

        cmdbuf.writeByte(' ');
        if (global.params.mapfile)
        {   cmdbuf.writestring("/MAP:");
            writeFilename(&cmdbuf, global.params.mapfile);
        }
        else if (global.params.map)
        {
            const char *fn = FileName::forceExt(global.params.exefile, "map");

            const char *path = FileName::path(global.params.exefile);
            const char *p;
            if (path[0] == '\0')
                p = FileName::combine(global.params.objdir, fn);
            else
                p = fn;

            cmdbuf.writestring("/MAP:");
            writeFilename(&cmdbuf, p);
        }

        for (size_t i = 0; i < global.params.libfiles->dim; i++)
        {
            cmdbuf.writeByte(' ');
            cmdbuf.writestring("/DEFAULTLIB:");
            writeFilename(&cmdbuf, (*global.params.libfiles)[i]);
        }

        if (global.params.deffile)
        {
            cmdbuf.writeByte(' ');
            cmdbuf.writestring("/DEF:");
            writeFilename(&cmdbuf, global.params.deffile);
        }

        if (global.params.symdebug)
        {
            cmdbuf.writeByte(' ');
            cmdbuf.writestring("/DEBUG");
        }

        if (global.params.dll)
        {
            cmdbuf.writeByte(' ');
            cmdbuf.writestring("/DLL");
        }

        for (size_t i = 0; i < global.params.linkswitches->dim; i++)
        {
            cmdbuf.writeByte(' ');
            cmdbuf.writestring((*global.params.linkswitches)[i]);
        }

        /* Append the path to the VC lib files, and then the SDK lib files
         */
        const char *vcinstalldir = getenv("VCINSTALLDIR");
        if (vcinstalldir)
        {   cmdbuf.writestring(" \"/LIBPATH:");
            cmdbuf.writestring(vcinstalldir);
            cmdbuf.writestring("lib\\amd64\"");
        }

        const char *windowssdkdir = getenv("WindowsSdkDir");
        if (windowssdkdir)
        {   cmdbuf.writestring(" \"/LIBPATH:");
            cmdbuf.writestring(windowssdkdir);
            cmdbuf.writestring("lib\\x64\"");
        }

        char *p = cmdbuf.peekString();

        const char *lnkfilename = NULL;
        size_t plen = strlen(p);
        if (plen > 7000)
        {
            lnkfilename = FileName::forceExt(global.params.exefile, "lnk");
            File flnk(lnkfilename);
            flnk.setbuffer(p, plen);
            flnk.ref = 1;
            if (flnk.write())
                error(Loc(), "error writing file %s", lnkfilename);
            if (strlen(lnkfilename) < plen)
                sprintf(p, "@%s", lnkfilename);
        }

        const char *linkcmd = getenv("LINKCMD64");
        if (!linkcmd)
            linkcmd = getenv("LINKCMD"); // backward compatible
        if (!linkcmd)
        {
            if (vcinstalldir)
            {
                OutBuffer linkcmdbuf;
                linkcmdbuf.writestring(vcinstalldir);
                linkcmdbuf.writestring("bin\\amd64\\link");
                linkcmd = linkcmdbuf.extractString();
            }
            else
                linkcmd = "link";
        }
        int status = executecmd(linkcmd, p);
        if (lnkfilename)
        {
            remove(lnkfilename);
            FileName::free(lnkfilename);
        }
        return status;
    }
    else
    {
        OutBuffer cmdbuf;

        global.params.libfiles->push("user32");
        global.params.libfiles->push("kernel32");

        for (size_t i = 0; i < global.params.objfiles->dim; i++)
        {
            if (i)
                cmdbuf.writeByte('+');
            const char *p = (*global.params.objfiles)[i];
            const char *basename = FileName::removeExt(FileName::name(p));
            const char *ext = FileName::ext(p);
            if (ext && !strchr(basename, '.'))
            {
                // Write name sans extension (but not if a double extension)
                writeFilename(&cmdbuf, p, ext - p - 1);
            }
            else
                writeFilename(&cmdbuf, p);
            FileName::free(basename);
        }
        cmdbuf.writeByte(',');
        if (global.params.exefile)
            writeFilename(&cmdbuf, global.params.exefile);
        else
        {   /* Generate exe file name from first obj name.
             * No need to add it to cmdbuf because the linker will default to it.
             */
            const char *n = (*global.params.objfiles)[0];
            n = FileName::name(n);
            global.params.exefile = (char *)FileName::forceExt(n, "exe");
        }

        // Make sure path to exe file exists
        ensurePathToNameExists(Loc(), global.params.exefile);

        cmdbuf.writeByte(',');
        if (global.params.mapfile)
            writeFilename(&cmdbuf, global.params.mapfile);
        else if (global.params.map)
        {
            const char *fn = FileName::forceExt(global.params.exefile, "map");

            const char *path = FileName::path(global.params.exefile);
            const char *p;
            if (path[0] == '\0')
                p = FileName::combine(global.params.objdir, fn);
            else
                p = fn;

            writeFilename(&cmdbuf, p);
        }
        else
            cmdbuf.writestring("nul");
        cmdbuf.writeByte(',');

        for (size_t i = 0; i < global.params.libfiles->dim; i++)
        {
            if (i)
                cmdbuf.writeByte('+');
            writeFilename(&cmdbuf, (*global.params.libfiles)[i]);
        }

        if (global.params.deffile)
        {
            cmdbuf.writeByte(',');
            writeFilename(&cmdbuf, global.params.deffile);
        }

        /* Eliminate unnecessary trailing commas    */
        while (1)
        {   size_t i = cmdbuf.offset;
            if (!i || cmdbuf.data[i - 1] != ',')
                break;
            cmdbuf.offset--;
        }

        if (global.params.resfile)
        {
            cmdbuf.writestring("/RC:");
            writeFilename(&cmdbuf, global.params.resfile);
        }

        if (global.params.map || global.params.mapfile)
            cmdbuf.writestring("/m");

#if 0
        if (debuginfo)
            cmdbuf.writestring("/li");
        if (codeview)
        {
            cmdbuf.writestring("/co");
            if (codeview3)
                cmdbuf.writestring(":3");
        }
#else
        if (global.params.symdebug)
            cmdbuf.writestring("/co");
#endif

        cmdbuf.writestring("/noi");
        for (size_t i = 0; i < global.params.linkswitches->dim; i++)
        {
            cmdbuf.writestring((*global.params.linkswitches)[i]);
        }
        cmdbuf.writeByte(';');

        char *p = cmdbuf.peekString();

        const char *lnkfilename = NULL;
        size_t plen = strlen(p);
        if (plen > 7000)
        {
            lnkfilename = FileName::forceExt(global.params.exefile, "lnk");
            File flnk(lnkfilename);
            flnk.setbuffer(p, plen);
            flnk.ref = 1;
            if (flnk.write())
                error(Loc(), "error writing file %s", lnkfilename);
            if (strlen(lnkfilename) < plen)
                sprintf(p, "@%s", lnkfilename);
        }

        const char *linkcmd = getenv("LINKCMD");
        if (!linkcmd)
            linkcmd = "link";
        int status = executecmd(linkcmd, p);
        if (lnkfilename)
        {
            remove(lnkfilename);
            FileName::free(lnkfilename);
        }
        return status;
    }
#elif __linux__ || __APPLE__ || __FreeBSD__ || __OpenBSD__ || __sun
    pid_t childpid;
    int status;

    // Build argv[]
    Strings argv;

    const char *cc = getenv("CC");
    if (!cc)
        cc = "gcc";
    argv.push(cc);
    argv.insert(1, global.params.objfiles);

#if __APPLE__
    // If we are on Mac OS X and linking a dynamic library,
    // add the "-dynamiclib" flag
    if (global.params.dll)
        argv.push("-dynamiclib");
#elif __linux__ || __FreeBSD__ || __OpenBSD__ || __sun
    if (global.params.dll)
        argv.push("-shared");
#endif

    // None of that a.out stuff. Use explicit exe file name, or
    // generate one from name of first source file.
    argv.push("-o");
    if (global.params.exefile)
    {
        argv.push(global.params.exefile);
    }
    else if (global.params.run)
    {
#if 1
        char name[L_tmpnam + 14 + 1];
        strcpy(name, P_tmpdir);
        strcat(name, "/dmd_runXXXXXX");
        int fd = mkstemp(name);
        if (fd == -1)
        {   error(Loc(), "error creating temporary file");
            return 1;
        }
        else
            close(fd);
        global.params.exefile = mem.strdup(name);
        argv.push(global.params.exefile);
#else
        /* The use of tmpnam raises the issue of "is this a security hole"?
         * The hole is that after tmpnam and before the file is opened,
         * the attacker modifies the file system to get control of the
         * file with that name. I do not know if this is an issue in
         * this context.
         * We cannot just replace it with mkstemp, because this name is
         * passed to the linker that actually opens the file and writes to it.
         */
        char s[L_tmpnam + 1];
        char *n = tmpnam(s);
        global.params.exefile = mem.strdup(n);
        argv.push(global.params.exefile);
#endif
    }
    else
    {   // Generate exe file name from first obj name
        const char *n = (*global.params.objfiles)[0];
        char *ex;

        n = FileName::name(n);
        const char *e = FileName::ext(n);
        if (e)
        {
            e--;                        // back up over '.'
            ex = (char *)mem.malloc(e - n + 1);
            memcpy(ex, n, e - n);
            ex[e - n] = 0;
            // If generating dll then force dll extension
            if (global.params.dll)
                ex = (char *)FileName::forceExt(ex, global.dll_ext);
        }
        else
            ex = (char *)"a.out";       // no extension, so give up
        argv.push(ex);
        global.params.exefile = ex;
    }

    // Make sure path to exe file exists
    ensurePathToNameExists(Loc(), global.params.exefile);

    if (global.params.symdebug)
        argv.push("-g");

    if (global.params.is64bit)
        argv.push("-m64");
    else
        argv.push("-m32");

    if (global.params.map || global.params.mapfile)
    {
        argv.push("-Xlinker");
#if __APPLE__
        argv.push("-map");
#else
        argv.push("-Map");
#endif
        if (!global.params.mapfile)
        {
            const char *fn = FileName::forceExt(global.params.exefile, "map");

            const char *path = FileName::path(global.params.exefile);
            const char *p;
            if (path[0] == '\0')
                p = FileName::combine(global.params.objdir, fn);
            else
                p = fn;

            global.params.mapfile = (char *)p;
        }
        argv.push("-Xlinker");
        argv.push(global.params.mapfile);
    }

    if (0 && global.params.exefile)
    {
        /* This switch enables what is known as 'smart linking'
         * in the Windows world, where unreferenced sections
         * are removed from the executable. It eliminates unreferenced
         * functions, essentially making a 'library' out of a module.
         * Although it is documented to work with ld version 2.13,
         * in practice it does not, but just seems to be ignored.
         * Thomas Kuehne has verified that it works with ld 2.16.1.
         * BUG: disabled because it causes exception handling to fail
         * because EH sections are "unreferenced" and elided
         */
        argv.push("-Xlinker");
        argv.push("--gc-sections");
    }

    for (size_t i = 0; i < global.params.linkswitches->dim; i++)
    {   const char *p = (*global.params.linkswitches)[i];
        if (!p || !p[0] || !(p[0] == '-' && (p[1] == 'l' || p[1] == 'L')))
            // Don't need -Xlinker if switch starts with -l or -L.
            // Eliding -Xlinker is significant for -L since it allows our paths
            // to take precedence over gcc defaults.
            argv.push("-Xlinker");
        argv.push(p);
    }

    /* Add each library, prefixing it with "-l".
     * The order of libraries passed is:
     *  1. any libraries passed with -L command line switch
     *  2. libraries specified on the command line
     *  3. libraries specified by pragma(lib), which were appended
     *     to global.params.libfiles.
     *  4. standard libraries.
     */
    for (size_t i = 0; i < global.params.libfiles->dim; i++)
    {   const char *p = (*global.params.libfiles)[i];
        size_t plen = strlen(p);
        if (plen > 2 && p[plen - 2] == '.' && p[plen -1] == 'a')
            argv.push(p);
        else
        {
            char *s = (char *)mem.malloc(plen + 3);
            s[0] = '-';
            s[1] = 'l';
            memcpy(s + 2, p, plen + 1);
            argv.push(s);
        }
    }

    /* Standard libraries must go after user specified libraries
     * passed with -l.
     */
    const char *libname = (global.params.symdebug)
                                ? global.params.debuglibname
                                : global.params.defaultlibname;
    size_t slen = strlen(libname);
    if (slen)
    {
        char *buf = (char *)malloc(3 + slen + 1);
        strcpy(buf, "-l");
        /* Use "-l:libname.a" if the library name is complete
         */
        if (slen > 3 + 2 &&
            memcmp(libname, "lib", 3) == 0 &&
            (memcmp(libname + slen - 2, ".a", 2) == 0 ||
             memcmp(libname + slen - 3, ".so", 3) == 0)
           )
        {
            strcat(buf, ":");
        }
        strcat(buf, libname);
        argv.push(buf);             // turns into /usr/lib/libphobos2.a
    }

#ifdef __sun
    argv.push("-mt");
#endif

//    argv.push("-ldruntime");
    argv.push("-lpthread");
    argv.push("-lm");
#if __linux__
    // Changes in ld for Ubuntu 11.10 require this to appear after phobos2
    argv.push("-lrt");
#endif

    if (global.params.verbose)
    {
        // Print it
        for (size_t i = 0; i < argv.dim; i++)
            fprintf(global.stdmsg, "%s ", argv[i]);
        fprintf(global.stdmsg, "\n");
    }

    argv.push(NULL);

    // set up pipes
    int fds[2];

    if (pipe(fds) == -1)
    {
        perror("Unable to create pipe to linker");
        return -1;
    }

    childpid = fork();
    if (childpid == 0)
    {
        // pipe linker stderr to fds[0]
        dup2(fds[1], STDERR_FILENO);
        close(fds[0]);

        execvp(argv[0], (char **)argv.tdata());
        perror(argv[0]);           // failed to execute
        return -1;
    }
    else if (childpid == -1)
    {
        perror("Unable to fork");
        return -1;
    }
    close(fds[1]);
    const int nme = findNoMainError(fds[0]);
    waitpid(childpid, &status, 0);

    if (WIFEXITED(status))
    {
        status = WEXITSTATUS(status);
        if (status)
        {
            if (nme == -1)
            {
                perror("Error with the linker pipe");
                return -1;
            }
            else
            {
                printf("--- errorlevel %d\n", status);
                if (nme == 1) error(Loc(), "no main function specified");
            }
        }
    }
    else if (WIFSIGNALED(status))
    {
        printf("--- killed by signal %d\n", WTERMSIG(status));
        status = 1;
    }
    return status;
#else
    printf ("Linking is not yet supported for this version of DMD.\n");
    return -1;
#endif
}
コード例 #8
0
ファイル: test-wordexp.c プロジェクト: ArmstrongJ/MiNTLib
int
main (int argc, char *argv[])
{
  const char *globfile[] = { "one", "two", "three", NULL };
  char tmpdir[32];
  struct passwd *pw;
  const char *cwd;
  int test;
  int fail = 0;
  int i;

  if (argc > 1)
    {
      command_line_test (argv[1]);
      return 0;
    }

  cwd = getcwd (NULL, 0);

  /* Set up arena for pathname expansion */
  tmpnam (tmpdir);
  if (mkdir (tmpdir, S_IRWXU) || chdir (tmpdir))
    return -1;
  else
    {
      int fd;

      for (i = 0; globfile[i]; ++i)
	if ((fd = creat (globfile[i], S_IRUSR | S_IWUSR)) == -1
	    || close (fd))
	  return -1;
    }

  for (test = 0; test_case[test].retval != -1; test++)
    if (testit (&test_case[test]))
      ++fail;

  pw = getpwnam ("root");
  if (pw != NULL)
    {
      struct test_case_struct ts;

      ts.retval = 0;
      ts.env = NULL;
      ts.words = "~root";
      ts.flags = 0;
      ts.wordc = 1;
      ts.wordv[0] = pw->pw_dir;
      ts.ifs = IFS;

      if (testit (&ts))
	++fail;
    }

  puts ("tests completed, now cleaning up");

  /* Clean up */
  for (i = 0; globfile[i]; ++i)
    remove (globfile[i]);

  if (cwd == NULL)
    cwd = "..";

  chdir (cwd);
  rmdir (tmpdir);

  printf ("tests failed: %d\n", fail);

  return fail != 0;
}
コード例 #9
0
ファイル: ovexport.c プロジェクト: barak/ivtools-cvs
boolean OvExportCmd::Export (const char* pathname) {
    Editor* editor = GetEditor();
    Selection* s = editor->GetSelection();
    OverlayIdrawComp* real_top = (OverlayIdrawComp*)editor->GetComponent();
    boolean ok = false;
    
    boolean empty = s->IsEmpty();

    OverlayIdrawComp* false_top = new OverlayIdrawComp();
    Iterator i;
    empty ? real_top->First(i) : s->First(i);
    while (empty ? !real_top->Done(i) : !s->Done(i)) {
      if (chooser_->idraw_format() || chooser_->postscript_format()) {
	OverlayComp* oc = empty 
	  ? new OverlayComp(real_top->GetComp(i)->GetGraphic()->Copy())
	  : new OverlayComp(s->GetView(i)->GetGraphicComp()->GetGraphic()->Copy());
	false_top->Append(oc);
      } else {
	OverlayComp* oc = empty 
	  ? (OverlayComp*)real_top->GetComp(i)->Copy()
	  : (OverlayComp*)s->GetView(i)->GetGraphicComp()->Copy();
	false_top->Append(oc);
      }
      empty ? real_top->Next(i) : s->Next(i);
    }
     
    OverlayPS* ovpsv;
    if (chooser_->idraw_format() || chooser_->postscript_format())
      ovpsv = (OverlayPS*) false_top->Create(POSTSCRIPT_VIEW);
    else
      ovpsv = (OverlayPS*) false_top->Create(SCRIPT_VIEW);
    if (ovpsv != nil) {
      
      filebuf fbuf;
      char* tmpfilename;
      
      if (chooser_->to_printer()) {
	tmpfilename = tmpnam(nil);
	false_top->SetPathName(tmpfilename);
	ok = fbuf.open(tmpfilename, output) != 0;
      } else {
	ok = fbuf.open(pathname, output) != 0;
      }
      
      if (ok) {
	ostream out(&fbuf);
	false_top->Attach(ovpsv);
	ovpsv->SetCommand(this);
	if (!chooser_->idraw_format() && !chooser_->postscript_format())
	  ((OverlayIdrawScript*)ovpsv)->SetByPathnameFlag(chooser_->by_pathname_flag());
	ovpsv->Update();
	ok = ovpsv->Emit(out);
	fbuf.close();
	
	if (chooser_->to_printer()) {
	  char cmd[CHARBUFSIZE];
	  if (strstr(pathname, "%s")) {
	    char buf[CHARBUFSIZE];
	    sprintf(buf, pathname, tmpfilename);    
	    sprintf(cmd, "(%s;rm %s)&", buf, tmpfilename);
	  } else
	    sprintf(cmd, "(%s %s;rm %s)&", pathname, tmpfilename, tmpfilename);
	  ok = system(cmd) == 0;
	}
      } 
      delete ovpsv;        
    }
    
    delete false_top;
    return ok;
}
コード例 #10
0
ファイル: TMPTEST.C プロジェクト: cr1901/nwbackup
int main(int argc, char * argv[]) {
  char filename[L_tmpnam];
  char temp_format_str[] = "This implementation of C stdlib supports up to %u temp files.\n" \
                           "Temp filenames can be up to %u bytes in length.\n" \
                           "The current temp file's name is: %s\n";
  char * temp_str_in = NULL;
  char * temp_str_out = NULL;
  int chars_written;
  long int temp_file_position = 0L;
  long int chars_read = 0;

  FILE *fp;
  tmpnam(filename);

  if(filename == NULL) {
    fprintf(stderr, "Attempt to get temporary file failed!\n");
  }

  fprintf(stderr, "%s", filename);

  temp_str_in = malloc(BUFSIZ);
  temp_str_out = malloc(BUFSIZ);
  if(temp_str_in == NULL || temp_str_out == NULL) {
    fprintf(stderr, "Temp string in/out malloc failure!\n");
    return EXIT_FAILURE;
  }

  chars_written = snprintf(temp_str_in, BUFSIZ, temp_format_str, \
                           TMP_MAX, L_tmpnam, filename);
  if(chars_written >= BUFSIZ) {
    fprintf(stderr, "Temp string too small to hold data!\n");
    return EXIT_FAILURE;
  }

  fprintf(stderr, "temp_str_in: ");
  fprintf(stderr, temp_str_in);
  fprintf(stderr, "\n");

  fp = fopen(filename, "w+b");
  if(fp == NULL) {
    perror("Temp file fopen failure");
  }

  fprintf(fp, temp_str_in);
  temp_file_position = ftell(fp);

  if(temp_file_position != -1L) {
    rewind(fp);
    fread(temp_str_out, 1, temp_file_position, fp);
    temp_str_out[temp_file_position] = '\0';
    fprintf(stderr, "temp_str_out: ");
    fprintf(stderr, temp_str_out);
  }
  else {
    perror("Temp file ftell failure");
  }
  fclose( fp );

  if((argc < 2) || strcmp(argv[1], "-k")) {
    remove(filename);
  }

  free(temp_str_in);
  free(temp_str_out);
  return EXIT_SUCCESS;
}
コード例 #11
0
/* ------------------------------------------------------------------------ */
short mtn_cfg_insert_string(FILE *fpSrc, long posn, char *p_config, char *p_parameter)
{
    char buffer[BUFSIZ+1], filename[12];
    long curr_posn;
    int  iNum;
    FILE *fpDest;

    // open a temporary file
    fpDest = NULL;
    tmpnam(filename);
    fopen_s(&fpDest, filename, "w");
    if(fpSrc==NULL || fpDest == NULL)
    {
        sprintf_s(strDebugMessage_MtnConfig, 512, "[%s %d]:Invalid file pointer!\n", __FILE__, __LINE__);
        return MTN_API_ERR_FILE_PTR;
    }

    // Get the number of value in the string
    mtn_cfg_Count_String(p_parameter, &iNum, " ,");

    // Point to the start position of the file
    fseek(fpSrc, 0, SEEK_SET);
    while (!feof(fpSrc))
    {
        curr_posn = ftell(fpSrc);
        if(fgets(buffer, BUFSIZ, fpSrc) != NULL)
        {
            if (curr_posn!=posn)
            {
                fprintf(fpDest, "%s", buffer);
            }
            else
            {
                if (iNum > 1)
                    fprintf(fpDest, "%s = <%s>\n", p_config, p_parameter);
                else
                    fprintf(fpDest, "%s = %s\n", p_config, p_parameter);

                fprintf(fpDest, "%s", buffer);
            }
        }
        // Handling for Block located at the last line
        if (feof(fpSrc))
        {
            curr_posn = ftell(fpSrc);
            if (curr_posn==posn)
            {
                if (iNum > 1)
                    fprintf(fpDest, "%s = <%s>\n", p_config, p_parameter);
                else
                    fprintf(fpDest, "%s = %s\n", p_config, p_parameter);
            }
        }
    }
    fclose(fpSrc);
    fclose(fpDest);
    remove(cfg_file_pathname);
    if (rename(filename, cfg_file_pathname) !=0)
    {
        sprintf_s(strDebugMessage_MtnConfig, 512, "FILE: %s, LINE: %d, Rename failed!\n", __FILE__, __LINE__);
        return MTN_API_ERR_RENAME_FILE;
    }

    // Open the New Configuration file
    mtn_cfg_OpenConfigFile(cfg_file_pathname);
    return MTN_API_OK_ZERO;
}
コード例 #12
0
bool File::OpenTemporaryFile(const std::wstring &dir)
{
	return Open(tmpnam(NULL), MODE_TEMP);
} 
コード例 #13
0
ファイル: bldmemfs.c プロジェクト: biddisco/bgq-source
int main(int argc, char **argv)
{
    int  infile,outfile,i,rc;
    long inBytes,outBytes;
    long numFiles;
    int  memNameLen;
    char *memNamePtr;
    int  opt;
    char tempfileName[L_tmpnam];
    char linkerString[2000];
    char *linkerPath;
    char inputFileName[1024];       // input file name
    long inLen;                     // input file len
    char *memDataPtr;               // pointer to data area
    char *fileDataPtr;              // pointer to file data
    long  fileOffset;               // current offset to file data
    int   currentArg = 0;
    FILE *inNamefile = NULL;
    memFSdata_t *memFSDataPtr;      // pointer to memFS data structure
    struct stat fileStat;

    int  fileOpt = 0;
    int  done = 0;
    int  verbose = 0;
    int   currentFiles = 0;
    char *listPtr=NULL;
    char *outFilePtr = NULL;
    char *imageInFilePtr = NULL;
    char fileName[] = "cnkmemfs.elf";
    mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

    if (2 > argc) {
       printf("%s requires at least 1 input argument\n",argv[0]);
       usage(argv[0]);
       exit(-1);
    }

    opterr = 0;
    while ((opt = getopt (argc, argv, "vhf:o:l:")) != -1) {
       switch (opt)
         {
          case 'o':
            outFilePtr = optarg;
            break;
          case 'f':
            imageInFilePtr = optarg;
            fileOpt = 1;
            break;
          case 'l':
            listPtr = optarg;
            break;
          case 'v':
            verbose = 1;
            break;
          case 'h':
            usage(argv[0]);
            return 0;
          case '?':
            if ((optopt == 'o') || (optopt == 'f') || (optopt == 'l'))
              printf ("Option -%c requires an argument.\n", optopt);
            else
              printf ("invalid option -%c \n", optopt);
            usage(argv[0]);
            exit(-1); 

          }
    }

    // check input parms for sanity

    if (NULL != listPtr && 3<argc)  {
       printf("List option is mutually exclusive with other arguments\n");
       usage(argv[0]);
       exit(-1);
    } else if (NULL != listPtr) {
       // do list and out of here 
       dumpelf(listPtr);
       return 0;
    }

    // check other parms

    if (argc > optind && 1 == fileOpt) {
       printf("Cannot have both file option and argument list\n");
       usage(argv[0]);
       exit(-1);
    }

    if (argc == optind && 0 == fileOpt) {
       printf("The file option or an argument list must be specified\n");
       usage(argv[0]);
       exit(-1);
    }

    if (0 == fileOpt) {
       // input files are command line arguments
       numFiles = argc-optind;
       if (NUM_FILES < numFiles) {
          printf("Too many file arguments\n");
          exit(-1);
       }
    }

    // set elf output file name
    if (NULL == outFilePtr) outFilePtr = fileName;

    // set temp output file name
    tmpnam(tempfileName);

    // set linker path
    linkerPath = getenv("BGQ_LINKERPATH");
    if (NULL == linkerPath) {
       printf("BGQ_LINKERPATH environment variable not set attempting to use\n%s\n",defaultLinker);
       linkerPath=defaultLinker;
    }

    if (verbose) {
        printf("temp file = %s\n",tempfileName);
        printf("output file name = %s\n",outFilePtr);
        printf("linker path = %s\n",linkerPath);

    }
//
// set up memory file system structure
//
    if (NULL == (memDataPtr = malloc(MAX_MEMFILE))) {  // allocate and point to data area
       perror("error allocating work area");
       exit(-1);
    }

    memFSDataPtr = (memFSdata_t*) memDataPtr;   // point to memFS data structure
    memset(memDataPtr,0x00,sizeof(memFSdata_t));  // clear directory area

    fileOffset = sizeof(memFSdata_t);          // start of data is after the header
    fileDataPtr = memDataPtr + fileOffset;

    // set up input type
    if (1 == fileOpt) {
       // input from file
       inNamefile=fopen(imageInFilePtr,"r" );
       if (NULL == inNamefile){
          perror("open error on member name file");
          printf("File in error is %s \n",imageInFilePtr);
          exit(-1);
       }
    } else {
       // input from command line
       currentArg = optind;
    }

//
// copy input files and build directory entries
//
    do {
       i = currentFiles;     // next directory entry slot
       if (0 == fileOpt) {
          // input from arg list
          getnextarg(argv, currentArg, inputFileName, sizeof(inputFileName)-1);
          currentFiles++;
          currentArg++;
          if (currentArg == argc) done = 1;
       } else {
          // get input from file
          rc = getnextentry(inNamefile,inputFileName, sizeof(inputFileName)-1);
          if (0 == rc) {
             currentFiles++;
             if (NUM_FILES < currentFiles)  {
                printf("Too many input files\n");
                exit(-1);
             }
          } else 
             break;       // last entry already processed
       }

       // isolate file name
       memNamePtr = strrchr(inputFileName,'/');       // find end of path
       if (!memNamePtr) 
          memNamePtr = inputFileName;   // name in same dir
       else
          memNamePtr++;                 // skip leading /
       memNameLen = strlen(memNamePtr);
       if (NAME_LEN<memNameLen) {
          printf("input file %s file name too long\n",argv[i+1]);
          exit(-1);
       }
       // copy input file to memFS
       rc = stat(inputFileName,&fileStat);
       if (-1 == rc) {
          perror("error on stat");
          printf("File in error is %s\n",inputFileName);
          exit(-1);
       }
       inLen = fileStat.st_size;
       if (MAX_MEMFILE<(fileOffset + inLen)) {
          printf("memFs not large enough for file %s\n",inputFileName);
          exit(-1);
       }

       infile=open(inputFileName,O_RDONLY );
       if (-1 == infile){
          perror("open error on input");
          printf("File in error is %s \n",inputFileName);
          exit(-1);
       }
       inBytes = read(infile,fileDataPtr,inLen);
       if (inBytes != inLen){
          perror("read error ");
          printf("File in error is %s \n",inputFileName);
          exit(-1);
       }
       if (close(infile)) {
          printf("FileClose on %s failed\n",inputFileName);
          exit(1);
       }
       // build directory entry for file
       memcpy(memFSDataPtr->entry[i].name,memNamePtr,memNameLen);
       memFSDataPtr->entry[i].nameLen = htonl(memNameLen);
       memFSDataPtr->entry[i].fileOffset  = htonl(fileOffset);
       memFSDataPtr->entry[i].fileSize = htonl(inLen);
       // set up for next file
       fileOffset += inLen;
       fileDataPtr += inLen;
    }  while(!done);     // end of input file(s) processing
//
// build rest of header for memFS image
//
    memcpy(memFSDataPtr->id,MEMFS_ID,8);
    memFSDataPtr->totalFSsize = htonl(fileOffset);
    memFSDataPtr->totalFSfiles = htonl(currentFiles);
    
//
// create memFS image file
//
    outfile=creat(tempfileName, mode);
    if (-1 == outfile){
       perror("File create error");
       printf("File in error is temp work area  %s\n",tempfileName);
       exit(-1);
    }
    outBytes = write(outfile,memDataPtr,fileOffset);
    if (outBytes != fileOffset){
       perror("Write error ");
       printf("File in error is temp work area %s\n",tempfileName);
    }
    close(outfile);

    if (verbose)
       dumpdir(memFSDataPtr);
    else
       printf("Total memFS image size is %ld \n",fileOffset);

    free(memDataPtr);           // done with in storage version

    // call linker to create elf wrapper
    sprintf(linkerString,"%s -Tdata=0xc0000000 --entry=0xc0000000 -n -b binary -o %s %s",
              linkerPath,outFilePtr,tempfileName);
    rc = system(linkerString);
    if (0 == rc)
       printf("elf image file %s created\n",outFilePtr); 
    else
       printf("elf image file %s create failed\n",outFilePtr);

    unlink(tempfileName);     // get rid of tempfile

    return 0;
}
コード例 #14
0
ファイル: ibrowserAPI.cpp プロジェクト: Y1Fo/ibrowser_plugin
FB::variant ibrowserAPI::downloadFile(const std::string& url,const std::string& filename,const boost::optional<FB::JSObjectPtr>& pcb, F_ADD)
{
    if(url.empty() || filename.empty())
        ERRO("url or filename is empty!");
    
    THREAD(&ibrowserAPI::downloadFile,url,filename,pcb);
    
    curl_global_init(CURL_GLOBAL_ALL);
    
    double fileSize = -1;
    CURL *fileSizeCurl = curl_easy_init();
    curl_easy_setopt(fileSizeCurl, CURLOPT_URL,url.c_str());
    curl_easy_setopt(fileSizeCurl, CURLOPT_HEADER, 1);
    curl_easy_setopt(fileSizeCurl, CURLOPT_NOBODY, 1);
    curl_easy_perform(fileSizeCurl);
    curl_easy_getinfo(fileSizeCurl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &fileSize);
    curl_easy_cleanup(fileSizeCurl);
    
    log("download file size:%.0f",fileSize);
    if(0 >= fileSize)
    {
        ERRO("get file size error");
    }
    
    char tmpName[1024];
    sprintf(tmpName,"%s/%s",dirname(tmpnam(NULL)),filename.c_str());
    
    log("start download, save file:%s, use %d threads",tmpName,this->downloadThreads);
    
    double partSize=fileSize/this->downloadThreads;
    pthread_t threads[this->downloadThreads];
    std::vector<double> counter;
    for(int i=0;i<this->downloadThreads;i++)
    {
        double start=partSize*i;
        double end=0;
        if(i+1<this->downloadThreads)
            end=partSize*(i+1)-1;
        else
            end=fileSize;
        FILE *tmpFile=fopen(tmpName,"wb+");
        if(!tmpFile)
            ERRO("create tmp file error");
        fseek(tmpFile,start,SEEK_SET);
        counter.push_back(0);
        
        log("threadid:%d,range:%.0f-%.0f",i,start,end);
        DownloadConfig *cfg=new DownloadConfig(i,url,tmpFile,*pcb,fileSize,start,end,&counter);
        pthread_create(&threads[i],NULL,&ibrowserAPI::downloadThread,cfg);
    }
    
    for(int i=0; i< this->downloadThreads; i++) {
        pthread_join(threads[i], NULL);
    }
    
    curl_global_cleanup();
    
    double downloadSize=0;
    int len=counter.size();
    for(int i=0;i<len;i++)
    {
        downloadSize+=counter.at(i);
    }
    //downloadSize+=1;
    log("downloadSize:%.0f",downloadSize);
    if(downloadSize == fileSize)
    {
        SUCC(tmpName);
    }else{
        ERRO("download error");
    }
    
    
    return true;
}
コード例 #15
0
ファイル: killff.c プロジェクト: Eric-Schnipke/snippets
main(int argc, char *argv[])
{
   FILE *in, *out;              /* input and output files        */
   char name[80],               /* name of file to be fixed      */
        temp[80],               /* output file name              */
        *buf;                   /* buffer we will use to write   */
   size_t bad,                  /* check to see if write ok      */
          num;                  /* number of bytes read          */
   int retval  = EXIT_SUCCESS,  /* return value                  */
       tmpflag = 0;             /* non-zero if tmpnam() used     */

   printf("\nKILL FORM FEEDS by Erik VanRiper & Bob Stout\n\n");

   if(argc < 2)                              /* usage info       */
   {
      puts("Usage: KILLFF input_file [output_file]");
      puts("\nIf no output file is given, the input file will "
           "be replaced.");
      return retval;                         /* return to OS     */
   }

   strcpy(name,argv[1]);                     /* input filename   */
   if(argc == 3) strcpy(temp,argv[2]);       /* outfile name     */
   else
   {
      tmpnam(temp);
      tmpflag = -1;
   }

   if((in = fopen(name,"r")) == NULL)        /* Open in file     */
   {
      printf("\nCan't Open Input File %s",name);
      return (retval = EXIT_FAILURE);        /* return to OS     */
   }
   if((out = fopen(temp,"wt")) == NULL)      /* open out file    */
   {
      printf("\nCan't Open Output File %s",temp);
      fclose(in);                            /* close in file    */
      return (retval = EXIT_FAILURE);        /* return to OS     */
   }

   if((buf = malloc(BSIZ)) == NULL)     /* malloc a large buffer */
   {
      printf("\nOut of memory\n");
      return (retval = EXIT_FAILURE);        /* return to OS     */
   }

   printf("Input file: %s Output file: %s\n",
      name,tmpflag ? name : temp);

   /* read in file while chars to read */

   while (0 < (num = fread(buf,sizeof(char),BSIZ,in)))
   {
      size_t i;

      for (i = 0; i < num; ++i)              /* look for FF      */
         if ('\f' == buf[i])
            buf[i] = '\n';                  /* change to newline */

      bad=fwrite(buf,sizeof(char),num,out);  /* write out buf    */
      if(bad != num)                         /* error            */
      {
         printf("\nCan't Write to %s ", temp);
         retval = EXIT_FAILURE;              /* return to OS     */
         break;
      }
   }
   fclose(in);                               /* close in file    */
   fclose(out);                              /* close out file   */
   free(buf);                                /* free memory      */
   if (tmpflag)
   {
      if (remove(name))
      {
         printf("Can't rename %s\n", name);
         printf("Converted file is named %s\n", temp);
      }
      else
         rename(temp, name);
   }
   printf("\nDone!");                        /* Finished         */
   return retval;                            /* return to OS     */
}
コード例 #16
0
ファイル: filesubr.cpp プロジェクト: todace/G-CVSNT
/* There are at least four functions for generating temporary
 * filenames.  We use mkstemp (BSD 4.3) if possible, else tempnam (SVID 3),
 * else mktemp (BSD 4.3), and as last resort tmpnam (POSIX).  Reason is that
 * mkstemp, tempnam, and mktemp both allow to specify the directory in which
 * the temporary file will be created.
 *
 * And the _correct_ way to use the deprecated functions probably involves
 * opening file descriptors using O_EXCL & O_CREAT and even doing the annoying
 * NFS locking thing, but until I hear of more problems, I'm not going to
 * bother.
 */
FILE *cvs_temp_file (char **filename)
{
    char *fn;
    FILE *fp;

    /* FIXME - I'd like to be returning NULL here in noexec mode, but I think
     * some of the rcs & diff functions which rely on a temp file run in
     * noexec mode too.
     */

    assert (filename != NULL);

#ifdef HAVE_MKSTEMP

    {
        int fd;

        fn = (char*)xmalloc (strlen (Tmpdir) + 11);
        sprintf (fn, "%s/%s", Tmpdir, "cvsXXXXXX" );
        fd = mkstemp (fn);

        /* a NULL return will be interpreted by callers as an error and
         * errno should still be set
         */
        if (fd == -1) fp = NULL;
        else if ((fp = CVS_FDOPEN (fd, "w+")) == NULL)
        {
            /* attempt to close and unlink the file since mkstemp returned sucessfully and
             * we believe it's been created and opened
             */
            int save_errno = errno;
            if (close (fd))
                error (0, errno, "Failed to close temporary file %s", fn_root(fn));
            if (CVS_UNLINK (fn))
                error (0, errno, "Failed to unlink temporary file %s", fn_root(fn));
            errno = save_errno;
        }

        if (fp == NULL) xfree (fn);
        /* mkstemp is defined to open mode 0600 using glibc 2.0.7+ */
        /* FIXME - configure can probably tell us which version of glibc we are
         * linking to and not chmod for 2.0.7+
         */
        else chmod (fn, 0600);

    }

#elif HAVE_TEMPNAM

    /* tempnam has been deprecated due to under-specification */

    fn = tempnam (Tmpdir, "cvs");
    if (fn == NULL) fp = NULL;
    else if ((fp = CVS_FOPEN (fn, "w+")) == NULL) xfree (fn);
    else chmod (fn, 0600);

    /* tempnam returns a pointer to a newly malloc'd string, so there's
     * no need for a xstrdup
     */

#elif HAVE_MKTEMP

    /* mktemp has been deprecated due to the BSD 4.3 specification specifying
     * that XXXXXX will be replaced by a PID and a letter, creating only 26
     * possibilities, a security risk, and a race condition.
     */

    {
        char *ifn;

        ifn = xmalloc (strlen (Tmpdir) + 11);
        sprintf (ifn, "%s/%s", Tmpdir, "cvsXXXXXX" );
        fn = mktemp (ifn);

        if (fn == NULL) fp = NULL;
        else fp = CVS_FOPEN (fn, "w+");

        if (fp == NULL) xfree (ifn);
        else chmod (fn, 0600);

    }

#else	/* use tmpnam if all else fails */

    /* tmpnam is deprecated */

    {
        char ifn[L_tmpnam + 1];

        fn = tmpnam (ifn);

        if (fn == NULL) fp = NULL;
        else if ((fp = CVS_FOPEN (ifn, "w+")) != NULL)
        {
            fn = xstrdup (ifn);
            chmod (fn, 0600);
        }

    }

#endif

    *filename = fn;
    return fp;
}
コード例 #17
0
ファイル: IOUtilsUnittest.cpp プロジェクト: wramner/Wave4
void testSizeFunctions() {
	string filename(tmpnam(NULL));
	seb::io::text(filename, "storlekstest");
	assert(seb::io::size(filename) == 12);
	remove(filename.c_str());
}
コード例 #18
0
ファイル: file_io.c プロジェクト: BIC-MNI/minc
/* ----------------------------- MNI Header -----------------------------------
@NAME       : acr_file_read_more
@INPUT      : afp - Acr_File pointer
@OUTPUT     : (none)
@RETURNS    : The next character.
@DESCRIPTION: Gets more input. If the watchpoint is reached, then EOF is 
              returned. This routine will not read past the watchpoint.
@METHOD     : 
@GLOBALS    : 
@CALLS      : 
@CREATED    : November 9, 1993 (Peter Neelin)
@MODIFIED   : February 5, 1997 (P.N.)
---------------------------------------------------------------------------- */
int acr_file_read_more(Acr_File *afp)
{
   int nread, ichar;
   char trace_file[128];
   unsigned char *margin_ptr;
   long byte_shift, bytes_to_read, watchpoint_distance;

   /* Check the pointer */
   if (afp == NULL) {
      return EOF;
   }

   /* Check whether we really need more */
   if (afp->ptr < afp->end) {
      return (int) *(afp->ptr++);
   }

   /* Check for EOF */
   if (afp->reached_eof) return EOF;

   /* Check the stream type */
   switch (afp->stream_type) {
   case ACR_UNKNOWN_STREAM:
      afp->stream_type = ACR_READ_STREAM; break;
   case ACR_READ_STREAM:
      break;
   case ACR_WRITE_STREAM:
   default:
      return EOF;
   }

   /* Work out the amount to read */
   bytes_to_read = afp->maxlength;
   if (afp->watchpoint_set) {
      watchpoint_distance = (afp->start + afp->bytes_to_watchpoint - afp->end);
      if (watchpoint_distance <= 0) {
         return EOF;
      }
      else if (watchpoint_distance < bytes_to_read) {
         bytes_to_read = watchpoint_distance;
      }
   }

   /* Check whether we need to start a new buffer for next read */
   if ((afp->end + bytes_to_read) > (afp->start + afp->buffer_length)) {

      /* Check that things are consistent */
      if ((afp->end - ACR_BUFFER_MARGIN) <= afp->start) {
         (void) fprintf(stderr, "Internal error copying afp buffer margin\n");
         exit(EXIT_FAILURE);
      }

      /* Copy the data down from the top of the buffer */
      margin_ptr = afp->end - ACR_BUFFER_MARGIN;
      for (ichar=0; ichar < ACR_BUFFER_MARGIN; ichar++) {
         afp->start[ichar] = margin_ptr[ichar];
      }

      /* Update the structure */
      byte_shift = margin_ptr - afp->start;
      afp->end = afp->start + ACR_BUFFER_MARGIN;
      afp->ptr = afp->end;
      afp->length = afp->end - afp->start;
      if (afp->watchpoint_set) {
         afp->bytes_to_watchpoint -= byte_shift;
      }
   }


   /* Read in another buffer-full */
   nread=afp->io_routine(afp->io_data, afp->end, bytes_to_read);

   /* Do tracing */
   if (afp->do_trace) {
      if (afp->tracefp == NULL) {
#if HAVE_MKSTEMP
         (void) strcpy(trace_file, Input_trace_file);          
         afp->tracefp = fdopen(mkstemp(trace_file), "w");
#elif HAVE_TMPNAM
         tmpnam(trace_file);
         afp->tracefp = fopen(trace_file, "w");
#else
#error Must have mkstemp() or tmpnam() available.
#endif
         if (afp->tracefp != NULL) {
            (void) fprintf(stderr, "Opened input trace file %s.\n", 
                           trace_file);
            (void) fflush(stderr);
         }
         else {
            (void) fprintf(stderr, "Error opening input trace file %s.\n",
                           trace_file);
            (void) fflush(stderr);
         }
      }
      if (nread > 0) {
         (void) fwrite(afp->end, sizeof(char), nread, afp->tracefp);
         (void) fflush(afp->tracefp);
      }
   }

   /* Check for EOF */
   if (nread <= 0) {
      afp->reached_eof = TRUE;
      return EOF;
   }

   /* Set up variables */
   afp->end += nread;
   afp->length += nread;

   /* Return the next value */
   return (int) *(afp->ptr++);

}
コード例 #19
0
ファイル: user.c プロジェクト: malikcjm/mc-nt
/* FIXME: recode this routine on version 3.0, it could be cleaner */
void execute_menu_command (char *s)
{
    char *commands;
    FILE *cmd_file;
    int  cmd_file_fd;
    int  expand_prefix_found = 0;
    int parameter_found = 0;
    int do_quote;
    char prompt [80] = "";
    int  col;
    char *file_name = tmpnam (0);

#ifdef OS2_NT
    /* OS/2 and NT requires the command to end in .cmd */
    file_name = copy_strings (file_name, ".cmd", NULL);
    file_name = "temp.bat";  // $$ fixme

    if ((cmd_file_fd = open (file_name, O_RDWR | O_CREAT | O_TRUNC | O_EXCL
                                                         | O_TEXT, 0600)) == -1){
    message (1, MSG_ERROR, _(" Can't create temporary command file \n %s "),
         unix_error_string (errno));
    return;
    }
#else
    if ((cmd_file_fd = open (file_name, O_RDWR | O_CREAT | O_TRUNC | O_EXCL, 0600)) == -1){
    message (1, MSG_ERROR, _(" Can't create temporary command file \n %s "),
         unix_error_string (errno));
    return;
    }
#endif
    cmd_file = fdopen (cmd_file_fd, "w");
    commands = strchr (s, '\n');
    if (!commands){
    fclose (cmd_file);
    unlink (file_name);
    return;
    }
    commands++;

    for (col = 0; *commands; commands++){
    if (col == 0 && (*commands != ' ' && *commands != '\t'))
        break;
        else if (col == 0)
        while (*commands == ' ' || *commands == '\t')
            commands++;
    col++;
    if (*commands == '\n')
        col = 0;
    if (parameter_found){
        if (*commands == '}'){
        char *parameter;
        char *tmp;
        parameter_found = 0;
        parameter = input_dialog (_(" Parameter "), prompt, "");
        if (!parameter || !*parameter){
            /* User canceled */
            fclose (cmd_file);
            unlink (file_name);
            return;
        }
        if (do_quote) {
                fputs (tmp = name_quote (parameter, 0), cmd_file);
            free (tmp);
        } else
            fputs (parameter, cmd_file);
        free (parameter);
        } else {
        int len = strlen (prompt);

        if (len+1 < sizeof (prompt)){
            prompt [len] = *commands;
            prompt [len+1] = 0;
        } else
            prompt [sizeof (prompt)-1] = 0;
        }
    } else if (expand_prefix_found){
        expand_prefix_found = 0;
        if (isdigit (*commands)) {
        do_quote = atoi (commands);
        for ( ; isdigit (*commands); commands++)
            ;
        }
        if (*commands == '{')
        parameter_found = 1;
        else{
        char *text = expand_format (*commands, do_quote);
        fputs (text, cmd_file);
        free (text);
        }
    } else {
        if (*commands == '%') {
        do_quote = 1; /* Default: Quote expanded macro */
        expand_prefix_found = 1;
        } else
        fputc (*commands, cmd_file);
    }
    }
    fclose (cmd_file);
    chmod (file_name, S_IRWXU);
    execute (file_name);
    unlink (file_name);
}
コード例 #20
0
ファイル: file_io.c プロジェクト: BIC-MNI/minc
/* ----------------------------- MNI Header -----------------------------------
@NAME       : acr_file_flush
@INPUT      : afp - Acr_File pointer
@OUTPUT     : (none)
@RETURNS    : EOF if an error occurs, otherwise 0.
@DESCRIPTION: Flushes the buffer.
@METHOD     : 
@GLOBALS    : 
@CALLS      : 
@CREATED    : November 9, 1993 (Peter Neelin)
@MODIFIED   : February 5, 1997 (P.N.)
---------------------------------------------------------------------------- */
int acr_file_flush(Acr_File *afp)
{
   int length, nwritten;
   char trace_file[128];

   /* Check the pointer */
   if (afp == NULL) {
      return EOF;
   }

   /* Check for EOF */
   if (afp->reached_eof) return EOF;

   /* Check the stream type */
   switch (afp->stream_type) {
   case ACR_UNKNOWN_STREAM:
      afp->stream_type = ACR_WRITE_STREAM; break;
   case ACR_WRITE_STREAM:
      break;
   case ACR_READ_STREAM:
   default:
      return EOF;
   }

   /* Check for something to write */
   length = afp->ptr - afp->start;
   if (length > 0) {

      /* Do trace, if needed */
      if (afp->do_trace) {
         if (afp->tracefp == NULL) {
#if HAVE_MKSTEMP
            (void) strcpy(trace_file, Output_trace_file);
            afp->tracefp = fdopen(mkstemp(trace_file), "w");
#elif HAVE_TMPNAM
            tmpnam(trace_file);
            afp->tracefp = fopen(trace_file, "w");
#else
#error Must have mkstemp() or tmpnam() available.
#endif
            if (afp->tracefp != NULL) {
               (void) fprintf(stderr, "Opened output trace file %s.\n", 
                              trace_file);
               (void) fflush(stderr);
            }
            else {
               (void) fprintf(stderr, "Error opening output trace file %s.\n",
                              trace_file);
               (void) fflush(stderr);
            }
         }
         (void) fwrite(afp->start, sizeof(char), length, afp->tracefp);
         (void) fflush(afp->tracefp);
      }

      /* Write the data */
      nwritten = afp->io_routine(afp->io_data, afp->start, length);
      if (nwritten != length) {
         (void) fprintf(stderr, "Output error: wrote only %d bytes of %d\n",
                        nwritten, length);
         afp->reached_eof = TRUE;
         return EOF;
      }

   }

   /* Reset the buffer */
   if (afp->watchpoint_set) {
      afp->bytes_to_watchpoint -= length;
   }
   afp->ptr = afp->start;
   afp->length = afp->maxlength;
   if ((afp->bytes_to_watchpoint > 0) && 
       (afp->bytes_to_watchpoint < afp->length)) {
      afp->length = afp->bytes_to_watchpoint;
   }
   afp->end = afp->start + afp->length;

   return 0;
}
コード例 #21
0
ファイル: tool.c プロジェクト: Glebka/Speech-To-Diagram
int main(int argc, char *argv[])
{
	if (argc != 3) {
		printf("Usage: %s <language code> <duration in seconds>\n", argv[0]);
		exit(1);
	}
	
	struct sprec_wav_header *hdr;
	struct sprec_server_response *resp;
	char *flac_file_buf;
	size_t flac_file_len;
	char *text;
	double confidence;
	int err;
	
	/*
	 * Generate two temporary files to store the WAV and FLAC data
	 */
	char wavfile[L_tmpnam + 5];
	char flacfile[L_tmpnam + 6];
	char *tmp_filename_stub = tmpnam(NULL);
	sprintf(wavfile, "%s.wav", tmp_filename_stub);
	sprintf(flacfile, "%s.flac", tmp_filename_stub);
	
	/*
	 * Start recording a WAV: sample rate = 16000Hz, bit depth = 16bps, stereo
	 */
	hdr = sprec_wav_header_from_params(16000, 16, 2);
	if (!hdr) {
		fprintf(stderr, "Error allocating WAV header\n");
		exit(1);
	}
	err = sprec_record_wav(wavfile, hdr, 1000 * strtod(argv[2], NULL));
	if (err) {
		fprintf(stderr, "Error recording WAV file: %d\n", err);
	 	exit(1);
	}
	
	free(hdr);
	
	/*
	 * Make the raw PCM in the WAV file into a FLAC file
	 */
	err = sprec_flac_encode(wavfile, flacfile);
	if (err) {
		fprintf(stderr, "Error converting WAV file to FLAC: %d\n", err);
		exit(1);
	}
	
	/*
	 * Read the entire FLAC file...
	 */
	err = sprec_get_file_contents(flacfile, (void **)&flac_file_buf, &flac_file_len);
	if (err) {
		fprintf(stderr, "Error reading FLAC file: %d\n", err);
		exit(1);
	}
	
	/*
	 * ...and send it to Google
	 */
	resp = sprec_send_audio_data(flac_file_buf, flac_file_len, argv[1], 16000);
	if (!resp) {
		fprintf(stderr, "Error sending audio data\n");
		exit(1);
	}
	
	free(flac_file_buf);
	
	/*
	 * Get the JSON from the response object,
	 * then parse it to get the actual text
	 */
	text = sprec_get_text_from_json(resp->data);
	confidence = sprec_get_confidence_from_json(resp->data);
	sprec_free_response(resp);
	
	printf("%s\n", text ? text : "(no text recognized)");
	printf("Confidence: %d%%\n", (int)(confidence * 100));
	free(text);
	
	/*
	 * Let's not fill up the entire /tmp folder
	 */
	remove(wavfile);
	remove(flacfile);
	
	return 0;
}
コード例 #22
0
void gnuplot_plot_xy(
    gnuplot_ctrl    *   handle,
	double			*	x,
	double			*	y,
    int                 n,
    char            *   title
)
{
    int         i ;
    FILE    *   tmp ;
    char    *   name ;
    char        cmd[GP_CMD_SIZE] ;
    char        line[GP_CMD_SIZE] ;

	if (handle==NULL || x==NULL || y==NULL || (n<1)) return ;

    /* can we open one more temporary file? */
    if (handle->ntmp == GP_MAX_TMP_FILES - 1) {
        fprintf(stderr,
                "maximum # of temporary files reached (%d): cannot open more",
                GP_MAX_TMP_FILES) ;
        return ;
    }

    /* Open temporary file for output   */
    if ((name = tmpnam(NULL)) == (char*)NULL) {
        fprintf(stderr,"cannot create temporary file: exiting plot") ;
        return ;
    }
    if ((tmp = fopen(name, "w")) == NULL) {
        fprintf(stderr,"cannot create temporary file: exiting plot") ;
        return ;
    }

    /* Store file name in array for future deletion */
    strcpy(handle->to_delete[handle->ntmp], name) ;
    handle->ntmp ++ ;

    /* Write data to this file  */
    for (i=0 ; i<n; i++) {
        fprintf(tmp, "%g %g\n", x[i], y[i]) ;
    }
    fflush(tmp) ;
    fclose(tmp) ;

    /* Command to be sent to gnuplot    */
    if (handle->nplots > 0) {
        strcpy(cmd, "replot") ;
    } else {
        strcpy(cmd, "plot") ;
    }
    
    if (title == NULL) {
        sprintf(line, "%s \"%s\" with %s", cmd, name, handle->pstyle) ;
    } else {
        sprintf(line, "%s \"%s\" title \"%s\" with %s", cmd, name,
                      title, handle->pstyle) ;
    }

    /* send command to gnuplot  */
    gnuplot_cmd(handle, line) ;
    handle->nplots++ ;
    return ;
}
コード例 #23
0
ファイル: lat_select.c プロジェクト: ash9211/graphene
int
main(int ac, char **av)
{
	char	c;
	int	n, N, fd, fid;
	pid_t	pid, ppid;
	char	buf[L_tmpnam+256];
	char	fname[L_tmpnam];
	char*	report_file = "Select on %d fd's";
	char*	report_tcp  = "Select on %d tcp fd's";
	char*	report;
	char*	usage = "lat_select tcp|file [n]\n";

	morefds();
	N = 200;
	fname[0] = 0;
	pid = 0;
	c = 0;
	nfds = 0;
	FD_ZERO(&set);
	report = report_file;

	if (ac != 2 && ac != 3) {
		fprintf(stderr, usage);
		exit(1);
	}

	if (streq(av[1], "tcp")) {
		report = report_tcp;
		
		/* Create a socket for clients to connect to */
		fd = tcp_server(TCP_SELECT, SOCKOPT_REUSE);
		if (fd <= 0) {
			perror("lat_select: Could not open tcp server socket");
			exit(1);
		}

		/* Start server process to accept client connections */
		ppid = getpid();
		switch(pid = fork()) {
		case 0:
			/* child server process */
			if (signal(SIGTERM, sigterm) == SIG_ERR) {
				perror("signal(SIGTERM, sigterm) failed");
				exit(1);
			}
			FD_SET(fd, &set);
			while (ppid == getppid()) {
				int newsock = tcp_accept(fd, SOCKOPT_NONE);
				if (newsock >= nfds) nfds = newsock + 1;
				FD_SET(newsock, &set);
			}
			sigterm(SIGTERM);
			/* NOTREACHED */
		case -1:
			/* error */
			perror("lat_select::server(): fork() failed");
			exit(1);
		default:
			break;
		}
		close(fd);
		fd = tcp_connect("127.0.0.1", TCP_SELECT, SOCKOPT_NONE);
		if (fd <= 0) {
			perror("lat_select: Could not open socket");
			exit(1);
		}
	} else if (streq(av[1], "file")) {
		/* Create a temporary file for clients to open */
		tmpnam(fname);
		fd = open(fname, O_RDWR|O_APPEND|O_CREAT, 0666);
		unlink(fname);
		if (fd <= 0) {
			char buf[L_tmpnam+128];
			sprintf(buf, 
				"lat_select: Could not create temp file %s", fname);
			perror(buf);
			exit(1);
		}
	} else {
		fprintf(stderr, usage);
		exit(1);
	}

	if (ac == 3) N = atoi(av[2]);

	for (n = 0; n < N; n++) {
		fid = dup(fd);
		if (fid == -1) break;
		if (fid >= nfds) nfds = fid + 1;
		FD_SET(fid, &set);
	}
	BENCH(doit(nfds, &set), 0);
	sprintf(buf, report, n);
	micro(buf, get_n());

	for (fid = 0; fid < nfds; fid++) {
		if (FD_ISSET(fid, &set)) {
			close(fid);
		}
	}
	close(fd);
	if (pid) kill(pid, SIGTERM);

	exit(0);
}
コード例 #24
0
bool CTimidityCodec::Init(const std::string& filename, unsigned int filecache,
                     int& channels, int& samplerate,
                     int& bitspersample, int64_t& totaltime,
                     int& bitrate, AEDataFormat& format,
                     std::vector<AEChannel>& channellist)
{
  if (m_soundfont.empty())
    return false;

  if (!LoadDll(m_usedLibName)) return false;
  if (!REGISTER_DLL_SYMBOL(Timidity_Init)) return false;
  if (!REGISTER_DLL_SYMBOL(Timidity_Cleanup)) return false;
  if (!REGISTER_DLL_SYMBOL(Timidity_GetLength)) return false;
  if (!REGISTER_DLL_SYMBOL(Timidity_LoadSong)) return false;
  if (!REGISTER_DLL_SYMBOL(Timidity_FreeSong)) return false;
  if (!REGISTER_DLL_SYMBOL(Timidity_FillBuffer)) return false;
  if (!REGISTER_DLL_SYMBOL(Timidity_Seek)) return false;
  if (!REGISTER_DLL_SYMBOL(Timidity_ErrorMsg)) return false;

  int res;
  if (m_soundfont.find(".sf2") != std::string::npos)
    res = Timidity_Init(48000, 16, 2, m_soundfont.c_str(), nullptr); // real soundfont
  else
    res = Timidity_Init(48000, 16, 2, nullptr, m_soundfont.c_str()); // config file

  if (res != 0)
    return false;

  kodi::vfs::CFile file;
  if (!file.OpenFile(filename))
    return false;

  int len = file.GetLength();
  uint8_t* data = new uint8_t[len];
  if (!data)
    return false;

  file.Read(data, len);

  const char* tempfile = tmpnam(nullptr);

  FILE* f = fopen(tempfile,"wb");
  if (!f)
  {
    delete[] data;
    return false;
  }
  fwrite(data, 1, len, f);
  fclose(f);
  delete[] data;

  m_song = Timidity_LoadSong((char*)tempfile);
  unlink(tempfile);
  if (!m_song)
    return false;

  m_pos = 0;

  channels = 2;
  samplerate = 48000;
  bitspersample = 16;
  totaltime = Timidity_GetLength(m_song);
  format = AE_FMT_S16NE;
  channellist = { AE_CH_FL, AE_CH_FR };
  bitrate = 0;

  return true;
}
コード例 #25
0
ファイル: pmlogger.c プロジェクト: jujis008/pcp
/*
 * generate dialog/message when launching application wishes to break
 * its association with pmlogger
 *
 * cmd is one of the following:
 *	D	detach pmlogger and let it run forever
 *	Q	terminate pmlogger
 *	?	display status
 *	X	fatal error or application exit ... user must decide
 *		to detach or quit
 */
void
do_dialog(char cmd)
{
    FILE	*msgf = NULL;
    time_t	now;
    static char	lbuf[100+MAXPATHLEN];
    double	archsize;
    char	*q;
    char	*p = NULL;
    int		nchar;
    char	*msg;
#if HAVE_MKSTEMP
    char	tmp[MAXPATHLEN];
#endif

    time(&now);
    now -= rsc_start;
    if (now == 0)
	/* hack is close enough! */
	now = 1;

    archsize = vol_bytes + ftell(logctl.l_mfp);

    nchar = add_msg(&p, 0, "");
    p[0] = '\0';

    snprintf(lbuf, sizeof(lbuf), "PCP recording for the archive folio \"%s\" and the host", folio_name);
    nchar = add_msg(&p, nchar, lbuf);
    if (now < 240)
	snprintf(lbuf, sizeof(lbuf), " \"%s\" has been in progress for %ld seconds",
	pmcd_host, (long)now);
    else
	snprintf(lbuf, sizeof(lbuf), " \"%s\" has been in progress for %ld minutes",
	pmcd_host, (long)((now + 30)/60));
    nchar = add_msg(&p, nchar, lbuf);
    nchar = add_msg(&p, nchar, " and in that time the pmlogger process has created an");
    nchar = add_msg(&p, nchar, " archive of ");
    q = do_size(archsize);
    nchar = add_msg(&p, nchar, q);
    nchar = add_msg(&p, nchar, ".");
    if (rsc_replay) {
	nchar = add_msg(&p, nchar, "\n\nThis archive may be replayed with the following command:\n");
	snprintf(lbuf, sizeof(lbuf), "  $ pmafm %s replay", folio_name);
	nchar = add_msg(&p, nchar, lbuf);
    }

    if (cmd == 'D') {
	nchar = add_msg(&p, nchar, "\n\nThe application that launched pmlogger has asked pmlogger");
	nchar = add_msg(&p, nchar, " to continue independently and the PCP archive will grow at");
	nchar = add_msg(&p, nchar, " the rate of ");
	q = do_size((archsize * 3600) / now);
	nchar = add_msg(&p, nchar, q);
	nchar = add_msg(&p, nchar, " per hour or ");
	q = do_size((archsize * 3600 * 24) / now);
	nchar = add_msg(&p, nchar, q);
	nchar = add_msg(&p, nchar, " per day.");
    }

    if (cmd == 'X') {
	nchar = add_msg(&p, nchar, "\n\nThe application that launched pmlogger has exited and you");
	nchar = add_msg(&p, nchar, " must decide if the PCP recording session should be terminated");
	nchar = add_msg(&p, nchar, " or continued.  If recording is continued the PCP archive will");
	nchar = add_msg(&p, nchar, " grow at the rate of ");
	q = do_size((archsize * 3600) / now);
	nchar = add_msg(&p, nchar, q);
	nchar = add_msg(&p, nchar, " per hour or ");
	q = do_size((archsize * 3600 * 24) / now);
	nchar = add_msg(&p, nchar, q);
	nchar = add_msg(&p, nchar, " per day.");
    }

    if (cmd == 'Q') {
	nchar = add_msg(&p, nchar, "\n\nThe application that launched pmlogger has terminated");
	nchar = add_msg(&p, nchar, " this PCP recording session.\n");
    }

    if (cmd != 'Q') {
	nchar = add_msg(&p, nchar, "\n\nAt any time this pmlogger process may be terminated with the");
	nchar = add_msg(&p, nchar, " following command:\n");
	snprintf(lbuf, sizeof(lbuf), "  $ pmsignal -s TERM %" FMT_PID "\n", getpid());
	nchar = add_msg(&p, nchar, lbuf);
    }

    if (cmd == 'X')
	nchar = add_msg(&p, nchar, "\n\nTerminate this PCP recording session now?");

    if (nchar > 0) {
	char * xconfirm = __pmNativePath(pmGetConfig("PCP_XCONFIRM_PROG"));
	int fd = -1;

#if HAVE_MKSTEMP
	snprintf(tmp, sizeof(tmp), "%s%cmsgXXXXXX", pmGetConfig("PCP_TMPFILE_DIR"), __pmPathSeparator());
	msg = tmp;
	fd = mkstemp(tmp);
#else
	if ((msg = tmpnam(NULL)) != NULL)
	    fd = open(msg, O_WRONLY|O_CREAT|O_EXCL, 0600);
#endif
	if (fd >= 0)
	    msgf = fdopen(fd, "w");
	if (msgf == NULL) {
	    fprintf(stderr, "\nError: failed create temporary message file for recording session dialog\n");
	    fprintf(stderr, "Reason? %s\n", osstrerror());
	    if (fd != -1)
		close(fd);
	    goto failed;
	}
	fputs(p, msgf);
	fclose(msgf);
	msgf = NULL;

	if (cmd == 'X')
	    snprintf(lbuf, sizeof(lbuf), "%s -c -header \"%s - %s\" -file %s -icon question "
			  "-B Yes -b No 2>/dev/null",
		    xconfirm, dialog_title, rsc_prog, msg);
	else
	    snprintf(lbuf, sizeof(lbuf), "%s -c -header \"%s - %s\" -file %s -icon info "
			  "-b Close 2>/dev/null",
		    xconfirm, dialog_title, rsc_prog, msg);

	if ((msgf = popen(lbuf, "r")) == NULL) {
	    fprintf(stderr, "\nError: failed to start command for recording session dialog\n");
	    fprintf(stderr, "Command: \"%s\"\n", lbuf);
	    goto failed;
	}

	if (fgets(lbuf, sizeof(lbuf), msgf) == NULL) {
	    fprintf(stderr, "\n%s: pmconfirm(1) failed for recording session dialog\n",
		    cmd == '?' ? "Warning" : "Error");
failed:
	    fprintf(stderr, "Dialog:\n");
	    fputs(p, stderr);
	    strcpy(lbuf, "Yes");
	}
	else {
	    /* strip at first newline */
	    for (q = lbuf; *q && *q != '\n'; q++)
		;
	    *q = '\0';
	}

	if (msgf != NULL)
	    pclose(msgf);
	unlink(msg);
    }
    else {
	fprintf(stderr, "Error: failed to create recording session dialog message!\n");
	fprintf(stderr, "Reason? %s\n", osstrerror());
	strcpy(lbuf, "Yes");
    }

    free(p);

    if (cmd == 'Q' || (cmd == 'X' && strcmp(lbuf, "Yes") == 0)) {
	run_done(0, "Recording session terminated");
	/*NOTREACHED*/
    }

    if (cmd != '?') {
	/* detach, silently go off to the races ... */
	close(rsc_fd);
	__pmFD_CLR(rsc_fd, &fds);
	rsc_fd = -1;
    }
}
コード例 #26
0
int sched(int ac, char *av[])
{
	int fifo_schedmin, fifo_schedmax;
	int i;
	struct sched_param rt_param;
	int n_instances = 10;
	int sched;

	verbose = 0;

#if _POSIX_VERSION < 199309
	try_anyway("The _POSIX_VERSION predates P1003.1B\n");
#endif

#if !defined(_POSIX_PRIORITY_SCHEDULING)
	try_anyway(
	"The environment does not claim to support Posix scheduling.\n");
#endif

	/* Is priority scheduling configured?
	 */
	errno = 0;
	if (sysconf(_SC_PRIORITY_SCHEDULING) == -1) {
		if (errno != 0) {
			/* This isn't valid - may be a standard violation
			 */
			quit("(should not happen) sysconf(_SC_PRIORITY_SCHEDULING)");
		}
		else {
			try_anyway(
			"The environment does not have run-time "
			"support for Posix scheduling.\n");
		}
	}

	/* Check that the priorities seem reasonable.
	 */

	checkpris(SCHED_FIFO);
	checkpris(SCHED_RR);
	checkpris(SCHED_OTHER);

/* BSD extensions?
 */
#if defined(SCHED_IDLE)
	checkpris(SCHED_IDLE);
#endif

	fifo_schedmin = sched_get_priority_min(SCHED_FIFO);
	fifo_schedmax = sched_get_priority_max(SCHED_FIFO);

	/* Make sure we can do some basic schedule switching:
	 */
	{
		struct sched_param orig_param, shouldbe;
		int orig_scheduler = sched_is(__LINE__, &orig_param, -1);

		if (verbose)
			fprintf(verbose,
			"The original scheduler is %s and the priority is %d.\n",
			sched_text(orig_scheduler), orig_param.sched_priority);

		/* Basic check: Try to set current settings:
		 */
		q(__LINE__, sched_setscheduler(0, orig_scheduler, &orig_param),
			"sched_setscheduler: Can't set original scheduler");

		rt_param.sched_priority = fifo_schedmin;

		q(__LINE__, sched_setscheduler(0, SCHED_FIFO, &rt_param),
		"sched_setscheduler SCHED_FIFO");

		(void)sched_is(__LINE__, 0, SCHED_FIFO);

		q(__LINE__, sched_getparam(0, &shouldbe), "sched_getparam");

		if (shouldbe.sched_priority != fifo_schedmin)
			quit("sched_setscheduler wrong priority (min)");

		rt_param.sched_priority = fifo_schedmin;

		q(__LINE__, sched_setparam(0, &rt_param),
			"sched_setparam to fifo_schedmin");

		rt_param.sched_priority = fifo_schedmin + 1;

		q(__LINE__, sched_setparam(0, &rt_param),
			"sched_setparam to fifo_schedmin + 1");

		q(__LINE__, sched_getparam(0, &shouldbe),
			"sched_getparam");

		if (shouldbe.sched_priority != fifo_schedmin + 1)
			quit("sched_setscheduler wrong priority (min + 1)");

		q(__LINE__, sched_setscheduler(0, SCHED_RR, &rt_param),
			"sched_setscheduler SCHED_RR");

		(void)sched_is(__LINE__, 0, SCHED_RR);

		q(__LINE__, sched_setscheduler(0, orig_scheduler, &orig_param),
			"sched_setscheduler restoring original scheduler");

		(void)sched_is(__LINE__, 0, orig_scheduler);
	}


	{
#define NAM "P1003_1b_schedXXXX"
		char nam[L_tmpnam];
		int fd;
		pid_t p;
		pid_t *lastrun;

		strcpy(nam, NAM);
		if (tmpnam(nam) != nam)
			q(__LINE__, errno, "tmpnam " NAM);
		q(__LINE__, (fd = open(nam, O_RDWR|O_CREAT, 0666)),
			"open " NAM);

		(void)unlink(nam);

		p = (pid_t)0;

		write(fd, &p, sizeof(p));

		q(__LINE__,  (int)(lastrun = mmap(0, sizeof(*lastrun), PROT_READ|PROT_WRITE,
		MAP_SHARED, fd, 0)), "mmap");

		/* Set our priority at the highest:
		 */
		sched = SCHED_FIFO;
		rt_param.sched_priority = fifo_schedmax;
		q(__LINE__, sched_setscheduler(0, sched, &rt_param),
		"sched_setscheduler sched");

		for (i = 0; i < n_instances; i++)
		{
			pid_t me;

			/* XXX This is completely bogus.  The children never run.
			 */
			if ((me = fork()) != 0)
			{
				/* Parent.
				 */
				(void)sched_is(__LINE__, 0, sched);

				/* Lower our priority:
				 */
				rt_param.sched_priority--;

				q(__LINE__, sched_setscheduler(0, sched, &rt_param),
				"sched_setscheduler sched");

				while (1)
				{
					q(__LINE__, sched_getparam(0, &rt_param), "sched_getparam");

					rt_param.sched_priority--;


					if (rt_param.sched_priority < fifo_schedmin)
						exit(0);

					*lastrun = me;
					q(__LINE__, sched_setparam(0, &rt_param), "sched_setparam");

					if (*lastrun == me)
					{
						/* The child will run twice
						 * at  the end:
						 */
						if (!me || rt_param.sched_priority != 0)
						{
							fprintf(stderr,
							"ran process %ld twice at priority %d\n",
							(long)me, rt_param.sched_priority + 1);
							exit(-1);
						}
					}
				}
			}
		}
	}

	return 0;
}
コード例 #27
0
ファイル: jj.c プロジェクト: htking95/CS252
main(int argc, char *argv[]) {
    register int x,m=0;
    char *cl;
    char w[256];
    char tfile[L_tmpnam];
    int subs,slims,sides,drinks,allow;
    char name[32];
    char phone[10];
    char address[64];
    FILE *tfp,*order;

    printf("Content-type: text/html%c%c",LF,LF);

    cl=getenv("QUERY_STRING");
    if((!cl) || (!cl[0]))
        dump_form();

    tmpnam(tfile);
    if(!(tfp=fopen(tfile,"w"))) {
        printf("<TITLE>Server Error</TITLE>%c",LF);
        printf("<H1>Server Error</H1>%c",LF);
        printf("Server unable to get a temporary file. Please try again later.<P>%c",LF);
        exit(1);
    }

    subs=0;slims=0;sides=0;drinks=0;allow=0;
    name[0]='\0';
    phone[0]='\0';
    address[0]='\0';

    for(x=0;cl[0] != '\0'; x++) {
        m=x;
        getword(w,cl,'=');
        plustospace(w);
        unescape_url(w);
        if(!strcmp(w,"pwd")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            allow=(strcmp(w,PASSWORD) ? 0 : 1);
        }
        if(!strcmp(w,"sub")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            subs |= (1 << atoi(w));
        }
        else if(!strcmp(w,"slj")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            slims |= (1 << atoi(w));
        }
        else if(!strcmp(w,"sde")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            sides |= (1 << atoi(w));
        }
        else if(!strcmp(w,"pop")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            drinks |= (1 << atoi(w));
        }
        else if(!strcmp(w,"name")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            strcpy(name,w);
        }
        else if(!strcmp(w,"phone")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            strcpy(phone,w);
        }
        else if(!strcmp(w,"adr")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            strcpy(address,w);
        }
    }

    if(!name[0]) print_error("you didn't give your name");
    if(!address[0]) print_error("you didn't give your address");
    if(!phone[0]) print_error("you didn't give your phone number");
    if((!subs) && (!slims) && (!sides) && (!drinks)) print_error("you didn't order anything");

    if(allow) {
        char t[256];
        sprintf(t,"/bin/mail %s",JJ_FAX);
        if(!(order=popen(t,"w")))
            print_error("the server was unable to open a pipe to mail");
        printf("<TITLE>Order Sent</TITLE>%c",LF);
        printf("<H1>Order Sent</H1>%c",LF);
        printf("Your order has been sent to the UIUC e-mail to FAX gateway.<P>%c",LF);
    } else {
        printf("<TITLE>Your Order</TITLE>%c",LF);
        printf("<H1>Your Order</H1>%c",LF);
        printf("This is how your order would have looked if it had been sent.<P><PLAINTEXT>%c",LF);
        order=stdout;
    }

    fprintf(order,"My name is %s, and I would like to have the following%c",
            name,LF);
    fprintf(order,"order delivered to %s:%c%c",address,LF,LF);
    for(x=0;x<12;x++)
        if(subs & (1 << x))
            fprintf(order,"\t(1) %s%c",sublist[x],LF);
    for(x=0;x<6;x++)
        if(slims & (1 << x))
            fprintf(order,"\t(1) %s Slim Jim%c",slimlist[x],LF);
    for(x=0;x<2;x++)
        if(sides & (1 << x))
            fprintf(order,"\t(1) %s%c",sidelist[x],LF);
    for(x=0;x<4;x++)
        if(drinks & (1 << x))
            fprintf(order,"\t(1) %s%c",poplist[x],LF);
    fprintf(order,"%cPlease feel free to call me at %s if there is any%c",LF,
            phone,LF);
    fprintf(order,"problem. Thank you.%c%c.%c",LF,LF,LF);
    fclose(order);
    exit(0);
}
コード例 #28
0
ファイル: test_TuxUtils.c プロジェクト: cm-t/tuxdroidserver
void _generateTemporaryPath(char *path)
{
	tmpnam(path);
}
コード例 #29
0
ファイル: main.c プロジェクト: ivanprague90/hypnotoad
int main(int argc, char **argv) {
	   InitializeEnvironment();
       IncrementGCLocks();
       Load("src/main.clp");
       void * module = FindDefmodule("Hypnotoad");
       SetCurrentModule(module);

       zmq = zmq_init(1);
       pub = zmq_socket(zmq, ZMQ_PUB);
       zmq_bind(pub, "tcp://*:5554");

       void * sub = zmq_socket(zmq, ZMQ_SUB);
       zmq_bind(sub, "tcp://*:5555");
       zmq_setsockopt(sub, ZMQ_SUBSCRIBE, "", 0);

	   while (1) {
            char * msg, * topic;
            int topic_size;
            char * remote_filename;
		    zmq_msg_t request;

		    zmq_msg_init (&request);
		    zmq_recv (sub, &request, 0);
		    topic = zmq_msg_data (&request);
            topic_size = zmq_msg_size(&request);

            int fact = !strncmp(topic, "fact", 4);
            if (!fact) {
              remote_filename = (char *) malloc(topic_size + 1);
              strncpy(remote_filename, topic, topic_size);
            }

		    zmq_msg_close (&request);

		    zmq_msg_init (&request);
		    zmq_recv (sub, &request, 0);
		    msg = zmq_msg_data (&request);

            if (fact) {
              LoadFactsFromString(msg, zmq_msg_size(&request));
              Focus(module);
              Run(-1);
            } else {
              char * filename = tmpnam(0);

              /* dump file */
              FILE * f = fopen(filename,"w+");
              fwrite(msg, zmq_msg_size(&request), 1, f);
              fclose(f);

              char * fact = (char *) malloc(1024);
              sprintf(fact, "(remote-file \"%s\" \"%s\")\n",remote_filename,filename);

              /* load file mapping */
              Focus(module);
              LoadFactsFromString(fact, -1);

              Focus(module);
              Run(-1);

#if 0
              DATA_OBJECT res;
              Eval("(facts)",&res);
              fflush(0);
#endif              
              /* cleanup */
              free(fact);
              free(remote_filename);
              unlink(filename);
              free(filename);
            }
		    zmq_msg_close (&request);
	   }

       zmq_close(pub);
       zmq_close(sub);
       zmq_term(zmq);

       DecrementGCLocks();
}
コード例 #30
0
ファイル: fstemp.c プロジェクト: AmericoBalboa/core
static HB_BOOL hb_fsTempName( char * pszBuffer, const char * pszDir, const char * pszPrefix )
{
   HB_BOOL fResult;

   pszBuffer[ 0 ] = '\0';

   hb_vmUnlock();

#if defined( HB_OS_WIN )
   {
      LPCTSTR lpPrefix, lpDir;
      LPTSTR lpPrefixFree = NULL, lpDirFree = NULL;

      TCHAR lpBuffer[ HB_PATH_MAX ];
      TCHAR lpTempDir[ HB_PATH_MAX ];

      lpPrefix = pszPrefix ? HB_FSNAMECONV( pszPrefix, &lpPrefixFree ) : NULL;

      if( pszDir && pszDir[ 0 ] != '\0' )
         lpDir = HB_FSNAMECONV( pszDir, &lpDirFree );
      else
      {
         if( ! GetTempPath( HB_PATH_MAX, lpTempDir ) )
         {
            hb_fsSetIOError( HB_FALSE, 0 );
            return HB_FALSE;
         }
         lpTempDir[ HB_PATH_MAX - 1 ] = TEXT( '\0' );
         lpDir = lpTempDir;
      }

      fResult = GetTempFileName( lpDir, lpPrefix ? lpPrefix : TEXT( "hb" ), 0, lpBuffer );

      if( fResult )
         HB_OSSTRDUP2( lpBuffer, pszBuffer, HB_PATH_MAX - 1 );

      if( lpPrefixFree )
         hb_xfree( lpPrefixFree );
      if( lpDirFree )
         hb_xfree( lpDirFree );
   }
#else
   {
      char * pTmpBuffer = ( char * ) hb_xgrab( L_tmpnam + 1 );

      /* TODO: Implement these: */
      HB_SYMBOL_UNUSED( pszDir );
      HB_SYMBOL_UNUSED( pszPrefix );

      pTmpBuffer[ 0 ] = '\0';
      fResult = ( tmpnam( pszBuffer ) != NULL );
      pTmpBuffer[ L_tmpnam ] = '\0';

      if( fResult )
      {
#  if defined( __DJGPP__ )
         /* convert '/' to '\' */
         char * pszDelim = pTmpBuffer;
         while( ( pszDelim = strchr( pszDelim, '/' ) ) != NULL )
            *pszDelim = '\\';
#  endif
         hb_osStrDecode2( pTmpBuffer, pszBuffer, HB_PATH_MAX - 1 );
      }
      hb_xfree( pTmpBuffer );
   }
#endif

   hb_fsSetIOError( fResult, 0 );
   hb_vmLock();

   return fResult;
}