Ejemplo n.º 1
0
/* helper function for the *one functions */
static void do_charone( int iSwitch )
{
   char *pcString;
   size_t sStrLen;
   char *pcDeleteSet;
   size_t sDeleteSetLen;

   /* param check */
   if ( ISCHAR( 1 ) )
   {
      if ( ISCHAR( 2 ) )
      {
         pcString = hb_parc( 2 );
         sStrLen = (size_t)hb_parclen( 2 );
         pcDeleteSet = hb_parc( 1 );
         sDeleteSetLen = (size_t)hb_parclen( 1 );
      }
      else
      {
         pcString = hb_parc( 1 );
         sStrLen = (size_t)hb_parclen( 1 );
         pcDeleteSet = NULL;
         sDeleteSetLen = 0;
      }

      switch ( iSwitch )
      {
         case DO_CHARONE_CHARONE:
         {
            if (sStrLen > 1)
            {
               char *pcSub;
               char *pcRet;
               size_t sRetStrLen = 0;
               char cCurrent = *pcString;

               pcRet = (char *)hb_xgrab( sStrLen );

               /* copy first char */
               pcRet[ sRetStrLen++ ] = cCurrent;

               for ( pcSub = pcString + 1; pcSub < pcString + sStrLen; pcSub++ )
               {
                  if ( *pcSub != cCurrent )
                  {
                     cCurrent = *pcSub;
                     pcRet[ sRetStrLen++ ] = cCurrent;
		  }
		  else if ( pcDeleteSet != NULL
		            && !ct_at_exact_forward( pcDeleteSet, sDeleteSetLen,
		                                     pcSub, 1, NULL ) )
		  {
		     pcRet[ sRetStrLen++ ] = cCurrent;
		  }
	       }

               hb_retclen( pcRet, sRetStrLen );
               hb_xfree( pcRet );
            }
            else  /* if (sStrLen > 1) */
            {
               /* algorithm does nothing to 1-char-strings */
               hb_retclen( pcString, sStrLen );
            }
         }
	 break;

         case DO_CHARONE_WORDONE:
         {
            if ( sStrLen > 3 && sDeleteSetLen >= 2 )
            {
               char *pcSub;
               char *pcRet;
               size_t sRetStrLen = 0;
               char cCurrent1 = pcString[0];
               char cCurrent2 = pcString[1];

               pcRet = (char *)hb_xgrab( sStrLen );

               /* copy first double char */
               pcRet[ sRetStrLen++ ] = cCurrent1;
               pcRet[ sRetStrLen++ ] = cCurrent2;

               for ( pcSub = pcString + 2; pcSub < pcString + sStrLen - 1; pcSub += 2 )
               {
                  if ( !( pcSub[0] == cCurrent1 && pcSub[1] == cCurrent2 ) )
                  {
                     cCurrent1 = pcSub[0];
                     cCurrent2 = pcSub[1];
                     pcRet[ sRetStrLen++ ] = cCurrent1;
                     pcRet[ sRetStrLen++ ] = cCurrent2;
		  }
		  else if ( pcDeleteSet != NULL )
		  {
		     char *pc = NULL;
		     char *pStart = pcDeleteSet;
		     size_t sLen = sDeleteSetLen;
		     
		     while ( sLen >= 2
		             && ( pc = ct_at_exact_forward( pStart, sLen,
		                                            pcSub, 2, NULL ) ) != 0
			     && ( pc - pcDeleteSet ) % 2 == 1 )
		     {
		        pStart = pc + 1;
			sLen = sDeleteSetLen - ( pStart - pcDeleteSet );
		     }
		     
		     if ( pc == NULL )
		     {
		        pcRet[ sRetStrLen++ ] = cCurrent1;
			pcRet[ sRetStrLen++ ] = cCurrent2;
		     }
		  }
               }

               /* copy last character if string len is odd */
               if ( sStrLen % 2 == 1 )
               {
                  pcRet[ sRetStrLen++ ] = pcString[ sStrLen - 1 ];
               }
               hb_retclen( pcRet, sRetStrLen );
               hb_xfree( pcRet );
            }
            else  /* if (sStrLen > 3) */
            {
               /* algorithm does nothing to 3-char-strings */
               hb_retclen( pcString, sStrLen );
            }
         }
	 break;
      } /* switch (iSwitch) */
   }
   else /* if (ISCHAR (1)) */
   {
      PHB_ITEM pSubst = NULL;
      int iArgErrorMode = ct_getargerrormode();
    
      if ( iArgErrorMode != CT_ARGERR_IGNORE )
      {
         pSubst = ct_error_subst( (USHORT)iArgErrorMode, EG_ARG,
                                  ( iSwitch == DO_CHARONE_CHARONE ? CT_ERROR_CHARONE : CT_ERROR_WORDONE ),
                                  NULL,
                                  ( iSwitch == DO_CHARONE_CHARONE ? "CHARONE" : "WORDONE" ),
                                  0, EF_CANSUBSTITUTE, 2,
                                  hb_paramError( 1 ), hb_paramError( 2 ) );
      }
     
      if ( pSubst != NULL )
      {
         hb_itemRelease( hb_itemReturnForward( pSubst ) );
      }
      else
      {
         hb_retc( "" );
      }
   }
}
Ejemplo n.º 2
0
static PHB_FILE s_fileExtOpen( PHB_FILE_FUNCS pFuncs, const char * pszFileName, const char * pDefExt,
                               HB_USHORT uiExFlags, const char * pPaths,
                               PHB_ITEM pError )
{
   PHB_FILE pFile = NULL;

#if defined( HB_OS_UNIX )
   HB_BOOL fResult, fSeek = HB_FALSE;
#  if defined( HB_USE_LARGEFILE64 )
   struct stat64 statbuf;
#  else
   struct stat statbuf;
#  endif
#endif
   HB_BOOL fShared, fReadonly;
   HB_FHANDLE hFile;
   char * pszFile;

   HB_SYMBOL_UNUSED( pFuncs );

   fShared = ( uiExFlags & ( FO_DENYREAD | FO_DENYWRITE | FO_EXCLUSIVE ) ) == 0;
   fReadonly = ( uiExFlags & ( FO_READ | FO_WRITE | FO_READWRITE ) ) == FO_READ;
   pszFile = hb_fsExtName( pszFileName, pDefExt, uiExFlags, pPaths );

   hb_vmUnlock();
#if defined( HB_OS_UNIX )
#  if defined( HB_USE_LARGEFILE64 )
   fResult = stat64( ( char * ) pszFile, &statbuf ) == 0;
#  else
   fResult = stat( ( char * ) pszFile, &statbuf ) == 0;
#  endif
   hb_fsSetIOError( fResult, 0 );

   if( fResult )
   {
      hb_threadEnterCriticalSection( &s_fileMtx );
      pFile = hb_fileFind( statbuf.st_dev, statbuf.st_ino );
      if( pFile )
      {
         if( ! fShared || ! pFile->shared || ( uiExFlags & FXO_TRUNCATE ) != 0 )
            fResult = HB_FALSE;
         else if( ! fReadonly && pFile->readonly )
            pFile = NULL;
         else
            pFile->used++;

         if( ( uiExFlags & FXO_NOSEEKPOS ) == 0 )
         {
#  if defined( HB_OS_VXWORKS )
            fSeek  = ! S_ISFIFO( statbuf.st_mode );
#  else
            fSeek  = ! S_ISFIFO( statbuf.st_mode ) && ! S_ISSOCK( statbuf.st_mode );
#  endif
         }
      }
      hb_threadLeaveCriticalSection( &s_fileMtx );
   }

   if( pFile )
   {
      if( ! fResult )
      {
         hb_fsSetError( ( uiExFlags & FXO_TRUNCATE ) ? 5 : 32 );
         pFile = NULL;
      }
      else if( uiExFlags & FXO_COPYNAME )
         hb_strncpy( ( char * ) pszFileName, pszFile, HB_PATH_MAX - 1 );

      if( pError )
      {
         hb_errPutFileName( pError, pszFile );
         if( ! fResult )
         {
            hb_errPutOsCode( pError, hb_fsError() );
            hb_errPutGenCode( pError, ( HB_ERRCODE ) ( ( uiExFlags & FXO_TRUNCATE ) ? EG_CREATE : EG_OPEN ) );
         }
      }
   }
   else
#endif
   {
      hFile = hb_fsExtOpen( pszFileName, pDefExt, uiExFlags, pPaths, pError );
      if( hFile != FS_ERROR )
      {
         HB_ULONG device = 0, inode = 0;
#if defined( HB_OS_UNIX )
#  if defined( HB_USE_LARGEFILE64 )
         if( fstat64( hFile, &statbuf ) == 0 )
#  else
         if( fstat( hFile, &statbuf ) == 0 )
#  endif
         {
            device = ( HB_ULONG ) statbuf.st_dev;
            inode  = ( HB_ULONG ) statbuf.st_ino;
            if( ( uiExFlags & FXO_NOSEEKPOS ) == 0 )
            {
#  if defined( HB_OS_VXWORKS )
               fSeek  = ! S_ISFIFO( statbuf.st_mode );
#  else
               fSeek  = ! S_ISFIFO( statbuf.st_mode ) && ! S_ISSOCK( statbuf.st_mode );
#  endif
            }
         }
#endif

         hb_threadEnterCriticalSection( &s_fileMtx );
         pFile = hb_fileNew( hFile, fShared, fReadonly, device, inode, HB_TRUE );
         if( pFile->hFile != hFile )
         {
            if( pFile->hFileRO == FS_ERROR && ! fReadonly && pFile->readonly )
            {
               pFile->hFileRO = pFile->hFile;
               pFile->hFile = hFile;
               pFile->readonly = HB_FALSE;
               hFile = FS_ERROR;
            }
            if( pFile->uiLocks == 0 )
            {
#if ! defined( HB_USE_SHARELOCKS ) || defined( HB_USE_BSDLOCKS )
               if( pFile->hFileRO != FS_ERROR )
               {
                  hb_fsClose( pFile->hFileRO );
                  pFile->hFileRO = FS_ERROR;
               }
#endif
               if( hFile != FS_ERROR )
               {
                  hb_fsClose( hFile );
                  hFile = FS_ERROR;
#if defined( HB_USE_SHARELOCKS ) && ! defined( HB_USE_BSDLOCKS )
                  /* TOFIX: possible race condition */
                  hb_fsLockLarge( hFile, HB_SHARELOCK_POS, HB_SHARELOCK_SIZE,
                                  FL_LOCK | FLX_SHARED );
#endif
               }
            }
         }
         else
            hFile = FS_ERROR;
         hb_threadLeaveCriticalSection( &s_fileMtx );

         if( hFile != FS_ERROR )
         {
            /* TOFIX: possible race condition in MT mode,
             *        close() is not safe due to existing locks
             *        which are removed.
             */
            hb_fsClose( hFile );
         }
      }
   }
   hb_xfree( pszFile );

#if defined( HB_OS_UNIX )
   if( pFile && fSeek )
      pFile = hb_fileposNew( pFile );

#endif
   hb_vmLock();

   return pFile;
}
Ejemplo n.º 3
0
HB_WCHAR * hb_fsNameConvU16( const char * szFileName )
{
   char * pszBuffer = NULL;
   HB_WCHAR * lpwFileName;

   if( s_fFnTrim || s_cDirSep != HB_OS_PATH_DELIM_CHR ||
       s_iFileCase != HB_SET_CASE_MIXED || s_iDirCase != HB_SET_CASE_MIXED )
   {
      PHB_FNAME pFileName;
      HB_SIZE nLen;

      szFileName = pszBuffer = hb_strncpy( ( char * ) hb_xgrab( HB_PATH_MAX ),
                                           szFileName, HB_PATH_MAX - 1 );

      if( s_cDirSep != HB_OS_PATH_DELIM_CHR )
      {
         char * p = ( char * ) szFileName;
         while( *p )
         {
            if( *p == s_cDirSep )
               *p = HB_OS_PATH_DELIM_CHR;
            p++;
         }
      }

      pFileName = hb_fsFNameSplit( szFileName );

      /* strip trailing and leading spaces */
      if( s_fFnTrim )
      {
         if( pFileName->szName )
         {
            nLen = strlen( pFileName->szName );
            while( nLen && pFileName->szName[ nLen - 1 ] == ' ' )
               --nLen;
            while( nLen && pFileName->szName[ 0 ] == ' ' )
            {
               ++pFileName->szName;
               --nLen;
            }
            ( ( char * ) pFileName->szName )[ nLen ] = '\0';
         }
         if( pFileName->szExtension )
         {
            nLen = strlen( pFileName->szExtension );
            while( nLen && pFileName->szExtension[ nLen - 1 ] == ' ' )
               --nLen;
            while( nLen && pFileName->szExtension[ 0 ] == ' ' )
            {
               ++pFileName->szExtension;
               --nLen;
            }
            ( ( char * ) pFileName->szExtension )[ nLen ] = '\0';
         }
      }

      /* FILECASE */
      if( s_iFileCase == HB_SET_CASE_LOWER )
      {
         if( pFileName->szName )
            hb_strlow( ( char * ) pFileName->szName );
         if( pFileName->szExtension )
            hb_strlow( ( char * ) pFileName->szExtension );
      }
      else if( s_iFileCase == HB_SET_CASE_UPPER )
      {
         if( pFileName->szName )
            hb_strupr( ( char * ) pFileName->szName );
         if( pFileName->szExtension )
            hb_strupr( ( char * ) pFileName->szExtension );
      }

      /* DIRCASE */
      if( pFileName->szPath )
      {
         if( s_iDirCase == HB_SET_CASE_LOWER )
            hb_strlow( ( char * ) pFileName->szPath );
         else if( s_iDirCase == HB_SET_CASE_UPPER )
            hb_strupr( ( char * ) pFileName->szPath );
      }

      hb_fsFNameMerge( ( char * ) szFileName, pFileName );
      hb_xfree( pFileName );
   }

   lpwFileName = hb_mbtowc( szFileName );
   if( pszBuffer )
      hb_xfree( pszBuffer );

   return lpwFileName;
}
Ejemplo n.º 4
0
HB_BOOL hb_lppRecv( PHB_LPP pSocket, void ** data, HB_SIZE * len, HB_MAXINT timeout )
{
   HB_MAXINT  nTime = 0;
   long       lRecv;

   if( ! pSocket->pRecvBuffer )
   {
      pSocket->pRecvBuffer = ( char * ) hb_xgrab( 4 );
      pSocket->nRecvLen = 0;
      pSocket->fRecvHasSize = HB_FALSE;
   }

   if( timeout > 0 )
      nTime = ( HB_MAXINT ) hb_dateMilliSeconds() + timeout;

   for( ;; )
   {
      if( ! pSocket->fRecvHasSize )
      {
         lRecv = ( long ) ( 4 - pSocket->nRecvLen );
         lRecv = hb_socketRecv( pSocket->sd, pSocket->pRecvBuffer + pSocket->nRecvLen, lRecv, 0, timeout );
         if( lRecv == -1 )
         {
            pSocket->iError = hb_socketGetError();
            return HB_FALSE;
         }
         else if( lRecv == 0 )
         {
            /* peer closed connection */
            pSocket->iError = 0;
            return HB_FALSE;
         }

         pSocket->nRecvLen += lRecv;
         if( pSocket->nRecvLen < 4 )
         {
            pSocket->iError = HB_SOCKET_ERR_TIMEOUT;
            return HB_FALSE;
         }

         pSocket->nRecvSize = HB_GET_UINT32( pSocket->pRecvBuffer );

         if( pSocket->nLimit && pSocket->nRecvSize > pSocket->nLimit )
         {
            /* protection against remote memory exhaust attack */
            pSocket->iError = HB_LPP_ERR_TOOLARGE;
            hb_xfree( pSocket->pRecvBuffer );
            pSocket->pRecvBuffer = NULL;
            return HB_FALSE;
         }

         pSocket->nRecvLen = 0;
         pSocket->fRecvHasSize = HB_TRUE;
         if( pSocket->nRecvSize != 4 )
            pSocket->pRecvBuffer = ( char * ) hb_xrealloc( pSocket->pRecvBuffer, pSocket->nRecvSize );
      }

      if( pSocket->nRecvSize - pSocket->nRecvLen < ( HB_SIZE ) LONG_MAX )
         lRecv = ( long ) ( pSocket->nRecvSize - pSocket->nRecvLen );
      else
         lRecv = LONG_MAX;

      lRecv = hb_socketRecv( pSocket->sd, pSocket->pRecvBuffer + pSocket->nRecvLen, lRecv, 0, timeout );
      if( lRecv == -1 )
      {
         pSocket->iError = hb_socketGetError();
         return HB_FALSE;
      }
      else if( lRecv == 0 )
      {
         /* peer closed connection */
         pSocket->iError = 0;
         return HB_FALSE;
      }

      pSocket->nRecvLen += lRecv;
      if( pSocket->nRecvSize == pSocket->nRecvLen )
      {
         * data = pSocket->pRecvBuffer;
         * len = pSocket->nRecvLen;
         pSocket->pRecvBuffer = NULL;
         pSocket->iError = 0;
         return HB_TRUE;
      }
      if( timeout == 0 ||
          ( timeout > 0 && ( timeout = nTime - ( HB_MAXINT ) hb_dateMilliSeconds() ) <= 0 ) )
      {
         pSocket->iError = HB_SOCKET_ERR_TIMEOUT;
         return HB_FALSE;
      }
   }
}
Ejemplo n.º 5
0
/* helper function for the charswap and wordswap functions */
static void do_charswap( int iSwitch )
{
   /* suppress return value ? */
   int iNoRet = ct_getref() && HB_ISBYREF( 1 );

   /* param check */
   if( HB_ISCHAR( 1 ) )
   {
      const char * pcString = hb_parc( 1 );
      HB_SIZE sStrLen = hb_parclen( 1 );
      char * pcRet;
      HB_SIZE sRetIndex = 0;
      int iShift, iMod;
      const char * pcSub;

      if( sStrLen == 0 )
      {
         if( iNoRet )
            hb_ret();
         else
            hb_retc_null();
         return;
      }

      if( iSwitch == DO_CHARSWAP_WORDSWAP )
      {
         iShift = 4;
         if( hb_parl( 2 ) )
            iSwitch = DO_CHARSWAP_WORDSWAP_CHARSWAP;
      }
      else
         iShift = 2;

      pcRet = ( char * ) hb_xgrab( sStrLen );

      for( pcSub = pcString; pcSub < pcString + sStrLen + 1 - iShift; pcSub += iShift )
      {
         switch( iSwitch )
         {
            case DO_CHARSWAP_WORDSWAP:
               pcRet[ sRetIndex++ ] = pcSub[ 2 ];
               pcRet[ sRetIndex++ ] = pcSub[ 3 ];
               pcRet[ sRetIndex++ ] = pcSub[ 0 ];
               pcRet[ sRetIndex++ ] = pcSub[ 1 ];
               break;

            case DO_CHARSWAP_WORDSWAP_CHARSWAP:
               pcRet[ sRetIndex++ ] = pcSub[ 3 ];
               pcRet[ sRetIndex++ ] = pcSub[ 2 ];
               /* no 'break' here !! */
            case DO_CHARSWAP_CHARSWAP:
               pcRet[ sRetIndex++ ] = pcSub[ 1 ];
               pcRet[ sRetIndex++ ] = pcSub[ 0 ];
         }
      }

      /* copy rest of string */
      if( iSwitch == DO_CHARSWAP_WORDSWAP || iSwitch == DO_CHARSWAP_WORDSWAP_CHARSWAP )
         iMod = sStrLen % 4;
      else
         iMod = sStrLen % 2;

      for( pcSub = pcString + sStrLen - iMod; pcSub < pcString + sStrLen; pcSub++ )
         pcRet[ sRetIndex++ ] = *pcSub;

      /* return string */
      hb_storclen( pcRet, sRetIndex, 1 );

      if( iNoRet )
         hb_retl( HB_FALSE );
      else
         hb_retclen( pcRet, sRetIndex );
      hb_xfree( pcRet );
   }
   else
   {
      PHB_ITEM pSubst = NULL;
      int iArgErrorMode = ct_getargerrormode();

      if( iArgErrorMode != CT_ARGERR_IGNORE )
      {
         if( iSwitch == DO_CHARSWAP_CHARSWAP )
            pSubst = ct_error_subst( ( HB_USHORT ) iArgErrorMode, EG_ARG,
                                     CT_ERROR_CHARSWAP,
                                     NULL, HB_ERR_FUNCNAME, 0, EF_CANSUBSTITUTE,
                                     HB_ERR_ARGS_BASEPARAMS );
         else
            pSubst = ct_error_subst( ( HB_USHORT ) iArgErrorMode, EG_ARG,
                                     CT_ERROR_WORDSWAP,
                                     NULL, HB_ERR_FUNCNAME, 0, EF_CANSUBSTITUTE,
                                     HB_ERR_ARGS_BASEPARAMS );
      }

      if( pSubst != NULL )
         hb_itemReturnRelease( pSubst );
      else if( iNoRet )
         hb_retl( HB_FALSE );
      else
         hb_retc_null();
   }
}
Ejemplo n.º 6
0
double hb_fsDiskSpace( const char * pszPath, HB_USHORT uiType )
{
   char szPathBuf[ 2 ];
   double dSpace = 0.0;

   if( uiType > HB_DISK_TOTAL )
      uiType = HB_DISK_AVAIL;

   if( ! pszPath )
   {
      szPathBuf[ 0 ] = HB_OS_PATH_DELIM_CHR;
      szPathBuf[ 1 ] = '\0';
      pszPath = szPathBuf;
   }

#if defined( HB_OS_WIN )
   {
      LPCTSTR lpPath;
      LPTSTR lpFree;

      lpPath = HB_FSNAMECONV( pszPath, &lpFree );

      {
         UINT uiErrMode = SetErrorMode( SEM_FAILCRITICALERRORS );
         HB_BOOL fResult;

#if ! defined( HB_OS_WIN_CE ) && ! defined( HB_OS_WIN_64 )
         /* NOTE: We need to call this function dynamically to maintain support
                  Win95 first edition. It was introduced in Win95B (aka OSR2) [vszakats] */
         typedef BOOL ( WINAPI * P_GDFSE )( LPCTSTR, PULARGE_INTEGER,
                                            PULARGE_INTEGER, PULARGE_INTEGER );
         static P_GDFSE s_pGetDiskFreeSpaceEx = NULL;
         static HB_BOOL s_fInit = HB_FALSE;

         if( ! s_fInit )
         {
            HMODULE hModule = GetModuleHandle( HB_WINAPI_KERNEL32_DLL() );
            if( hModule )
               s_pGetDiskFreeSpaceEx = ( P_GDFSE )
                  HB_WINAPI_GETPROCADDRESST( hModule, "GetDiskFreeSpaceEx" );
            s_fInit = HB_TRUE;
         }

         if( ! s_pGetDiskFreeSpaceEx )
         {
            DWORD dwSectorsPerCluster;
            DWORD dwBytesPerSector;
            DWORD dwNumberOfFreeClusters;
            DWORD dwTotalNumberOfClusters;

            fResult = GetDiskFreeSpace( lpPath,
                                        &dwSectorsPerCluster,
                                        &dwBytesPerSector,
                                        &dwNumberOfFreeClusters,
                                        &dwTotalNumberOfClusters ) ? HB_TRUE : HB_FALSE;
            hb_fsSetIOError( fResult, 0 );

            if( fResult )
            {
               switch( uiType )
               {
                  case HB_DISK_AVAIL:
                  case HB_DISK_FREE:
                     dSpace = ( double ) dwNumberOfFreeClusters *
                              ( double ) dwSectorsPerCluster *
                              ( double ) dwBytesPerSector;
                     break;

                  case HB_DISK_USED:
                  case HB_DISK_TOTAL:
                     dSpace = ( double ) dwTotalNumberOfClusters *
                              ( double ) dwSectorsPerCluster *
                              ( double ) dwBytesPerSector;

                     if( uiType == HB_DISK_USED )
                        dSpace -= ( double ) dwNumberOfFreeClusters *
                                  ( double ) dwSectorsPerCluster *
                                  ( double ) dwBytesPerSector;
                     break;
               }
            }
         }
         else
#endif
         {
#if defined( _MSC_VER ) || defined( __LCC__ ) || \
    ( defined( __GNUC__ ) && ! defined( __RSXNT__ ) )

#  define HB_GET_LARGE_UINT( v )  ( ( double ) (v).LowPart + \
                                    ( double ) (v).HighPart * \
                                    ( ( ( double ) 0xFFFFFFFF ) + 1 ) )

#else
   /* NOTE: Borland doesn't seem to deal with the un-named
            struct that is part of ULARGE_INTEGER
            [pt] */
#  define HB_GET_LARGE_UINT( v )  ( ( double ) (v).u.LowPart + \
                                    ( double ) (v).u.HighPart * \
                                    ( ( ( double ) 0xFFFFFFFF ) + 1 ) )
#endif

            ULARGE_INTEGER i64FreeBytesToCaller, i64TotalBytes, i64FreeBytes;

#if ! defined( HB_OS_WIN_CE ) && ! defined( HB_OS_WIN_64 )
            fResult = s_pGetDiskFreeSpaceEx( lpPath,
                                             ( PULARGE_INTEGER ) &i64FreeBytesToCaller,
                                             ( PULARGE_INTEGER ) &i64TotalBytes,
                                             ( PULARGE_INTEGER ) &i64FreeBytes );
#else
            fResult = GetDiskFreeSpaceEx( lpPath,
                                          ( PULARGE_INTEGER ) &i64FreeBytesToCaller,
                                          ( PULARGE_INTEGER ) &i64TotalBytes,
                                          ( PULARGE_INTEGER ) &i64FreeBytes );
#endif
            hb_fsSetIOError( fResult, 0 );

            if( fResult )
            {
               switch( uiType )
               {
                  case HB_DISK_AVAIL:
                     dSpace = HB_GET_LARGE_UINT( i64FreeBytesToCaller );
                     break;

                  case HB_DISK_FREE:
                     dSpace = HB_GET_LARGE_UINT( i64FreeBytes );
                     break;

                  case HB_DISK_TOTAL:
                     dSpace = HB_GET_LARGE_UINT( i64TotalBytes );
                     break;

                  case HB_DISK_USED:
                     dSpace = HB_GET_LARGE_UINT( i64TotalBytes ) -
                              HB_GET_LARGE_UINT( i64FreeBytes );
                     break;
               }
            }
         }
         SetErrorMode( uiErrMode );
      }
      if( lpFree )
         hb_xfree( lpFree );
   }
#elif defined( HB_OS_DOS ) || defined( HB_OS_OS2 )
   {
      HB_USHORT uiDrive;

      uiDrive = pszPath == NULL || pszPath[ 0 ] == 0 ||
                pszPath[ 1 ] != HB_OS_DRIVE_DELIM_CHR ? 0 :
                ( pszPath[ 0 ] >= 'A' && pszPath[ 0 ] <= 'Z' ?
                  pszPath[ 0 ] - 'A' + 1 :
                ( pszPath[ 0 ] >= 'a' && pszPath[ 0 ] <= 'z' ?
                  pszPath[ 0 ] - 'a' + 1 : 0 ) );
#if defined( HB_OS_DOS )
      for( ;; )
      {
         union REGS regs;

         regs.HB_XREGS.dx = uiDrive;
         regs.h.ah = 0x36;
         HB_DOS_INT86( 0x21, &regs, &regs );

         if( regs.HB_XREGS.ax != 0xFFFF )
         {
            HB_USHORT uiClusterTotal  = regs.HB_XREGS.dx;
            HB_USHORT uiClusterFree   = regs.HB_XREGS.bx;
            HB_USHORT uiSecPerCluster = regs.HB_XREGS.ax;
            HB_USHORT uiSectorSize    = regs.HB_XREGS.cx;

            switch( uiType )
            {
               case HB_DISK_AVAIL:
               case HB_DISK_FREE:
                  dSpace = ( double ) uiClusterFree *
                           ( double ) uiSecPerCluster *
                           ( double ) uiSectorSize;
                  break;

               case HB_DISK_USED:
               case HB_DISK_TOTAL:
                  dSpace = ( double ) uiClusterTotal *
                           ( double ) uiSecPerCluster *
                           ( double ) uiSectorSize;

                  if( uiType == HB_DISK_USED )
                     dSpace -= ( double ) uiClusterFree *
                               ( double ) uiSecPerCluster *
                               ( double ) uiSectorSize;
                  break;
            }
         }
         else
         {
            if( hb_errRT_BASE_Ext1( EG_OPEN, 2018, NULL, NULL, 0, ( EF_CANDEFAULT | EF_CANRETRY ), HB_ERR_ARGS_BASEPARAMS ) == E_RETRY )
               continue;
         }
         break;
      }
#else /* HB_OS_OS2 */
      {
         struct _FSALLOCATE fsa;
         APIRET rc;
         /* Query level 1 info from filesystem */
         while( ( rc = DosQueryFSInfo( uiDrive, 1, &fsa, sizeof( fsa ) ) ) != NO_ERROR )
         {
            if( hb_errRT_BASE_Ext1( EG_OPEN, 2018, NULL, NULL, 0, ( EF_CANDEFAULT | EF_CANRETRY ), HB_ERR_ARGS_BASEPARAMS ) != E_RETRY )
               break;
         }

         hb_fsSetError( ( HB_ERRCODE ) rc );

         if( rc == NO_ERROR )
         {
            switch( uiType )
            {
               case HB_DISK_AVAIL:
               case HB_DISK_FREE:
                  dSpace = ( double ) fsa.cUnitAvail *
                           ( double ) fsa.cSectorUnit *
                           ( double ) fsa.cbSector;
                  break;

               case HB_DISK_USED:
               case HB_DISK_TOTAL:
                  dSpace = ( double ) fsa.cUnit *
                           ( double ) fsa.cSectorUnit *
                           ( double ) fsa.cbSector;

                  if( uiType == HB_DISK_USED )
                     dSpace -= ( double ) fsa.cUnitAvail *
                               ( double ) fsa.cSectorUnit *
                               ( double ) fsa.cbSector;
                  break;
            }
         }
      }
#endif
   }

#elif defined( HB_OS_UNIX ) && \
      !( defined( __WATCOMC__ ) || defined( __CEGCC__ ) || defined( HB_OS_SYMBIAN ) )
   {
#if defined( HB_OS_DARWIN ) || defined( HB_OS_ANDROID ) || \
    defined( HB_OS_VXWORKS )
      struct statfs sf;
#else
      struct statvfs sf;
#endif
      char * pszFree;

      pszPath = hb_fsNameConv( pszPath, &pszFree );

#if defined( HB_OS_DARWIN ) || defined( HB_OS_ANDROID ) || \
    defined( HB_OS_VXWORKS )
      if( statfs( pszPath, &sf ) == 0 )
#else
      if( statvfs( pszPath, &sf ) == 0 )
#endif
      {
         switch( uiType )
         {
            case HB_DISK_AVAIL:
               dSpace = ( double ) sf.f_bavail * ( double ) sf.f_bsize;
               break;

            case HB_DISK_FREE:
               dSpace = ( double ) sf.f_bfree * ( double ) sf.f_bsize;
               break;

            case HB_DISK_USED:
               dSpace = ( double ) ( sf.f_blocks - sf.f_bfree ) *
                        ( double ) sf.f_bsize;
               break;

            case HB_DISK_TOTAL:
               dSpace = ( double ) sf.f_blocks * ( double ) sf.f_bsize;
               break;
         }
         hb_fsSetIOError( HB_TRUE, 0 );
      }
      else
         hb_fsSetIOError( HB_FALSE, 0 );

      if( pszFree )
         hb_xfree( pszFree );
   }
#else
   {
      int iTODO;

      HB_SYMBOL_UNUSED( uiType );
   }
#endif

   return dSpace;
}
Ejemplo n.º 7
0
static HB_ERRCODE pgsqlOpen( SQLBASEAREAP pArea )
{
   PGconn *       pConn = ( ( SDDCONN * ) pArea->pConnection->pSDDConn )->pConn;
   SDDDATA *      pSDDData;
   PGresult *     pResult;
   ExecStatusType status;
   PHB_ITEM       pItemEof, pItem;
   HB_USHORT      uiFields, uiCount;
   HB_BOOL        bError;
   DBFIELDINFO    pFieldInfo;

   pArea->pSDDData = memset( hb_xgrab( sizeof( SDDDATA ) ), 0, sizeof( SDDDATA ) );
   pSDDData        = ( SDDDATA * ) pArea->pSDDData;

   pResult = PQexec( pConn, pArea->szQuery );
   if( ! pResult )
   {
      hb_errRT_PostgreSQLDD( EG_OPEN, ESQLDD_LOWMEMORY, "Query failed", NULL, 0 );  /* Low memory, etc */
      return HB_FAILURE;
   }

   status = PQresultStatus( pResult );
   if( status != PGRES_TUPLES_OK && status != PGRES_COMMAND_OK )
   {
      hb_errRT_PostgreSQLDD( EG_OPEN, ESQLDD_INVALIDQUERY, PQresultErrorMessage( pResult ), pArea->szQuery, ( HB_ERRCODE ) status );
      PQclear( pResult );
      return HB_FAILURE;
   }

   pSDDData->pResult = pResult;

   uiFields = ( HB_USHORT ) PQnfields( pResult );
   SELF_SETFIELDEXTENT( ( AREAP ) pArea, uiFields );

   pItemEof = hb_itemArrayNew( uiFields );
   pItem    = hb_itemNew( NULL );

   bError = HB_FALSE;
   for( uiCount = 0; uiCount < uiFields; uiCount++ )
   {
      pFieldInfo.atomName = PQfname( pResult, ( int ) uiCount );
      pFieldInfo.uiDec    = 0;

      switch( PQftype( pResult, ( int ) uiCount ) )
      {
         case BPCHAROID:
         case VARCHAROID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = ( HB_USHORT ) PQfmod( pResult, uiCount ) - 4;
            break;

         case TEXTOID:
            pFieldInfo.uiType = HB_FT_MEMO;
            pFieldInfo.uiLen  = 10;
            break;

         case NUMERICOID:
            pFieldInfo.uiType = HB_FT_DOUBLE;
            pFieldInfo.uiLen  = ( PQfmod( pResult, uiCount ) - 4 ) >> 16;
            pFieldInfo.uiDec  = ( PQfmod( pResult, uiCount ) - 4 ) & 0xFFFF;
            break;

         case INT2OID:
            pFieldInfo.uiType = HB_FT_INTEGER;
            pFieldInfo.uiLen  = 6;
            break;

         case INT4OID:
            pFieldInfo.uiType = HB_FT_INTEGER;
            pFieldInfo.uiLen  = 11;
            break;

         case INT8OID:
         case OIDOID:
            pFieldInfo.uiType = HB_FT_LONG;
            pFieldInfo.uiLen  = 20;
            break;

         case FLOAT4OID:
         case FLOAT8OID:
         case CASHOID:  /* TODO: ??? */
            pFieldInfo.uiType = HB_FT_DOUBLE;
            pFieldInfo.uiLen  = 16;
            pFieldInfo.uiDec  = 2;   /* TODO: hb_set.SET_DECIMALS ??? */
            break;

         case BOOLOID:
            pFieldInfo.uiType = HB_FT_LOGICAL;
            pFieldInfo.uiLen  = 1;
            break;

         case DATEOID:
            pFieldInfo.uiType = HB_FT_DATE;
            pFieldInfo.uiLen  = 8;
            break;

         case INETOID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = 29;
            break;

         case CIDROID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = 32;
            break;

         case MACADDROID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = 17;
            break;

         case BITOID:
         case VARBITOID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = ( HB_USHORT ) PQfsize( pResult, uiCount );
            break;

         case TIMEOID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = 12;
            break;

         case TIMESTAMPOID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = 23;
            break;

         case TIMETZOID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = 15;
            break;

         case TIMESTAMPTZOID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = 26;
            break;

         case NAMEOID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = 63;
            break;

         case BYTEAOID:
            pFieldInfo.uiType = HB_FT_STRING;
            pFieldInfo.uiLen  = 0;
            break;

         default:
            pFieldInfo.uiType = 0;
            pFieldInfo.uiLen  = 0;
            bError = HB_TRUE;
            break;
      }
      /* printf( "field:%s \ttype:%d \tsize:%d \tformat:%d \tmod:%d err=%d\n", pFieldInfo.atomName, PQftype( pResult, ( int ) uiCount ), PQfsize( pResult, uiCount ), PQfformat( pResult, uiCount ) , PQfmod( pResult, uiCount ), bError ); */

      if( ! bError )
      {
         switch( pFieldInfo.uiType )
         {
            case HB_FT_STRING:
            {
               char * pStr;

               pStr = ( char * ) hb_xgrab( pFieldInfo.uiLen + 1 );
               memset( pStr, ' ', pFieldInfo.uiLen );
               pStr[ pFieldInfo.uiLen ] = '\0';

               hb_itemPutCL( pItem, pStr, pFieldInfo.uiLen );
               hb_xfree( pStr );
               break;
            }
            case HB_FT_MEMO:
               hb_itemPutC( pItem, NULL );
               hb_itemSetCMemo( pItem );
               break;

            case HB_FT_INTEGER:
               hb_itemPutNI( pItem, 0 );
               break;

            case HB_FT_LONG:
               hb_itemPutNL( pItem, 0 );
               break;

            case HB_FT_DOUBLE:
               hb_itemPutND( pItem, 0.0 );
               break;

            case HB_FT_LOGICAL:
               hb_itemPutL( pItem, HB_FALSE );
               break;

            case HB_FT_DATE:
               hb_itemPutDS( pItem, NULL );
               break;

            default:
               hb_itemClear( pItem );
               bError = HB_TRUE;
               break;
         }

         hb_arraySetForward( pItemEof, uiCount + 1, pItem );

/*       if( pFieldInfo.uiType == HB_IT_DOUBLE || pFieldInfo.uiType == HB_IT_INTEGER )
            pFieldInfo.uiType = HB_IT_LONG;
 */

         if( ! bError )
            bError = ( SELF_ADDFIELD( ( AREAP ) pArea, &pFieldInfo ) == HB_FAILURE );
      }

      if( bError )
         break;
   }

   hb_itemRelease( pItem );

   if( bError )
   {
      hb_itemClear( pItemEof );
      hb_itemRelease( pItemEof );
      hb_errRT_PostgreSQLDD( EG_CORRUPTION, ESQLDD_INVALIDFIELD, "Invalid field type", pArea->szQuery, 0 );
      return HB_FAILURE;
   }

   pArea->ulRecCount = ( HB_ULONG ) PQntuples( pResult );

   pArea->pRow      = ( void ** ) hb_xgrab( ( pArea->ulRecCount + 1 ) * sizeof( void * ) );
   pArea->pRowFlags = ( HB_BYTE * ) hb_xgrab( ( pArea->ulRecCount + 1 ) * sizeof( HB_BYTE ) );
   memset( pArea->pRowFlags, 0, ( pArea->ulRecCount + 1 ) * sizeof( HB_BYTE ) );

   *pArea->pRow = pItemEof;
   pArea->pRowFlags[ 0 ] = SQLDD_FLAG_CACHED;
   pArea->fFetched       = HB_TRUE;

   return HB_SUCCESS;
}
Ejemplo n.º 8
0
static void hb_pcre_free( void * ptr )
{
   hb_xfree( ptr );
}
Ejemplo n.º 9
0
/* the contents of the inserted bytes are indeterminate, i.e. you'll have to
     write to them before they mean anything */
static int _ins_buff( PFT_TEXT ft_text, HB_ISIZ iLen )
{
   char *     ReadBuff  = ( char * ) hb_xgrab( BUFFSIZE );
   char *     WriteBuff = ( char * ) hb_xgrab( BUFFSIZE );
   char *     SaveBuff;
   HB_FOFFSET fpRead, fpWrite;
   HB_ISIZ    WriteLen, ReadLen;
   HB_ISIZ    SaveLen;
   HB_ISIZ    iLenRemaining = iLen;

   /* set target move distance, this allows iLen to be greater than BUFFSIZE */
   iLen = HB_MIN( iLenRemaining, BUFFSIZE );
   iLenRemaining -= iLen;

   /* initialize file pointers */
   fpRead  = ft_text->offset[ ft_text->area ];
   fpWrite = ft_text->offset[ ft_text->area ] + iLen;

   /* do initial load of both buffers */
   hb_fsSeekLarge( ft_text->handles[ ft_text->area ], fpRead, FS_SET );
   WriteLen = hb_fsRead( ft_text->handles[ ft_text->area ], WriteBuff, BUFFSIZE );
   fpRead  += WriteLen;

   ReadLen = hb_fsRead( ft_text->handles[ ft_text->area ], ReadBuff, BUFFSIZE );
   fpRead += ReadLen;

   ft_text->error[ ft_text->area ] = 0;

   while( ! ft_text->error[ ft_text->area ] && iLen > 0 )
   {
      while( WriteLen > 0 )
      {
         /* position to beginning of write area */
         if( hb_fsSeekLarge( ft_text->handles[ ft_text->area ], fpWrite, FS_SET ) != fpWrite )
         {
            ft_text->error[ ft_text->area ] = hb_fsError();
            break;
         }

         SaveLen = hb_fsWriteLarge( ft_text->handles[ ft_text->area ], WriteBuff, WriteLen );

         if( ! SaveLen )
         {
            ft_text->error[ ft_text->area ] = hb_fsError();
            break;
         }

         /* move write pointer */
         fpWrite += SaveLen;

         if( SaveLen != WriteLen )
         {
            /* error, fetch errcode and quit */
            ft_text->error[ ft_text->area ] = hb_fsError();
            break;
         }
#if 0
         WriteLen = SaveLen;
#endif

         /* swap buffers */
         SaveBuff  = WriteBuff;
         WriteBuff = ReadBuff;
         ReadBuff  = SaveBuff;
         WriteLen  = ReadLen;

         /* return to read area and read another buffer */
         hb_fsSeekLarge( ft_text->handles[ ft_text->area ], fpRead, FS_SET );
         ReadLen = hb_fsRead( ft_text->handles[ ft_text->area ], ReadBuff, BUFFSIZE );
         fpRead += ReadLen;
      }

      iLen = HB_MIN( iLenRemaining, BUFFSIZE );
      iLenRemaining -= iLen;
   }

   /* store length in bytes, set legacy EOF marker */
   ft_text->lastbyte[ ft_text->area ] = hb_fsSeekLarge( ft_text->handles[ ft_text->area ], fpWrite, FS_SET );
   hb_fsWrite( ft_text->handles[ ft_text->area ], WriteBuff, 0 );

   /* clear last_rec so next gobot will recount the records */
   ft_text->last_rec[ ft_text->area ] = 0;
   hb_fsSeekLarge( ft_text->handles[ ft_text->area ], ft_text->offset[ ft_text->area ], FS_SET );

   hb_xfree( ReadBuff  );
   hb_xfree( WriteBuff );

   return ft_text->error[ ft_text->area ];
}
Ejemplo n.º 10
0
/*
 * Implementação de printf() para Harbour/xHarbour.
 *
 * TODO: Creio que uma ótima melhoria seria somar o tamanho de todos os argumentos
 * e criar um buffer já pre-determinado com um tamanho +/- necessário para evitar
 * tantas realocações de memoria como ocorre nestes casos.
 * 26/07/2008 - 08:17:42
 */
static
char *wx_printf( ULONG *Length )
{
    PPrintInfo pInfo;
    char c;
    char *result;
    ULONG request_len;

    *Length = 0L;

    // o primeiro argumento tem que ser uma string!
    if ( !ISCHAR(1) )
        return NULL;

    /* Iniciamos a memoria */
    pInfo = (PPrintInfo) hb_xgrab( sizeof(TPrintInfo) );
    memset( pInfo, 0, sizeof(TPrintInfo) );

    pInfo->Mask   = hb_parcx(1);
    pInfo->msk_len= hb_parclen(1);

    pInfo->Result = (char *) hb_xgrab( pInfo->msk_len+1 );
    pInfo->Buffer = pInfo->Result;
    pInfo->cap_len= pInfo->msk_len;

    pInfo->argp ++;

    /* processamos a string como um todo */
    while (pInfo->error == NONE   &&
            pInfo->msk_len         &&
            pInfo->Mask[0] )
    {
        c = pInfo->Mask[0];

        switch (c)
        {
        case '%':
        {
            /*
             * Se nao tem nenhum item de argumento, e o proximo caracter de escape nao for
             * o "%", entao temos que abortar a rotina... indicando erro de argumento!
             */
            if (pInfo->Mask[1] == '%')
            {
                printf_add_str( pInfo, "%", 1L );
                pInfo->Mask    += 2;
                pInfo->msk_len -= 2;
                continue;
            }

            pInfo->argp ++;
            printf_add_conv( pInfo, hb_param( pInfo->argp, HB_IT_ANY ));
            continue;
        }

        default:
        {
            // Precisa realocar memoria?
            request_len = 1L;

            if (pInfo->out_len+request_len > pInfo->cap_len)
            {
                pInfo->cap_len += request_len;
                pInfo->Result   = (char *) hb_xrealloc( pInfo->Result, pInfo->cap_len+1 );
                pInfo->Buffer   = pInfo->Result + (pInfo->out_len);
                pInfo->out_len += request_len;
            } else {
                pInfo->out_len += request_len;
            }

            /*
             * É um caracter simples ou é uma sequencia de escape a ser add?
             * Links relacionados:
             *    http://docs.sun.com/app/docs/doc/816-0220/6m6nkorp8?a=view
             *    http://docs.sun.com/app/docs/doc/816-0213/6m6ne387j?a=view
             */
            if (c == '\\')
            {
                pInfo->Mask ++;
                pInfo->msk_len--;

                if (!pInfo->msk_len)
                    continue;

                c = pInfo->Mask[0];

                switch(c)
                {
                case '\\':
                    c = '\\';
                    break;
                case '\0':
                    c = '\0';
                    break;
                case 'a':
                    c = '\a';
                    break;
                case 'b':
                    c = '\b';
                    break;
                case 'f':
                    c = '\f';
                    break;
                case 'n':
                    c = '\n';
                    break;
                case 'r':
                    c = '\r';
                    break;
                case 't':
                    c = '\t';
                    break;
                case 'v':
                    c = '\v';
                    break;
                }
            }

            pInfo->Buffer[0] = c;
            pInfo->Buffer ++;

            pInfo->Mask ++;
            pInfo->msk_len--;
            break;
        }
        }
    }
    pInfo->Result[pInfo->out_len] = '\0';

    result  = pInfo->Result;
    *Length = pInfo->out_len;

    /* Liberamos a memoria alocada */
    hb_xfree( pInfo );
    return result;
}
Ejemplo n.º 11
0
// 26/07/2008 - 11:32:47
static
void printf_add_conv( PPrintInfo pInfo, PHB_ITEM pItem )
{
    char flag = 0;
    int width = 0;
    int precision = 0;
    char specifier = '\0';
    char m = '\0';
    char c;
    char mask[20];
    const char *t1;
    const char *t2;

    char * cValue;
    double dValue;
    ULONG  Length;

    /*
     * Procura por uma string de conversao com o formato:
     *        0       1        2         3      4
     *     %[flags][width][.precision][length]specifier
     *
     */
    t1 = pInfo->Mask;
    mask[0] = '\0';

    pInfo->Mask ++;
    pInfo->msk_len--;

    /*
     * Se nao tem nenhum item de argumento, e o proximo caracter de escape nao for
     * o "%", entao temos que abortar a rotina... indicando erro de argumento!
     */
    if (pInfo->msk_len &&
            // pInfo->Mask[0] != '%' &&
            !pItem)
    {
        pInfo->error =  FAILURE;
        return;
    }

    /* processamos a string como um todo */
    while (pInfo->error == NONE   &&
            pInfo->msk_len         &&
            pInfo->Mask[0] )
    {
        c = pInfo->Mask[0];

        // setou o flag?
        if (strchr( "-+ #0", c ))
        {
            flag = c;
            c = 'A';
        }

        // setar o width?
        if (strchr( "1234567890", c ))
        {
            char *t = (char *) hb_xgrab(15);
            char *s = t;

            do
            {
                *t = c;
                t++;
                pInfo->Mask ++;
                pInfo->msk_len--;
                c = pInfo->Mask[0];

            } while (pInfo->msk_len && strchr( "1234567890", c ));

            *t = '\0';
            width = atoi( s );
            hb_xfree(s);
        }

        // setar precision?
        if (c == '.')
        {
            char *t = (char *) hb_xgrab(15);
            char *s = t;

            pInfo->Mask ++;
            pInfo->msk_len--;
            c = pInfo->Mask[0];

            while (pInfo->msk_len && strchr( "1234567890", c ))
            {
                *t = c;
                t++;
                pInfo->Mask ++;
                pInfo->msk_len--;
                c = pInfo->Mask[0];
            }

            *t = '\0';
            precision = atoi( s );
            hb_xfree(s);

            c = pInfo->Mask[0];
        }

        if (c == 'l' && strchr( "idouxX", pInfo->Mask[1] ))
            m = c;
        if (c == 'h' && strchr( "idouxX", pInfo->Mask[1] ))
            m = c;
        if (c == 'L' && strchr( "eEfgG", pInfo->Mask[1] ))
            m = c;

        // Chegou no tipo?
        if (strchr( "cdieEfgGosuxXpn%", c ))
        {
            specifier = c;
            pInfo->Mask ++;
            pInfo->msk_len--;

            t2 = pInfo->Mask;

            switch( specifier )
            {
            case '%':
            {
                printf_add_str( pInfo, "%", 1L );
                break;
            }
            case 'c':
                //  O argumento é tratado como um inteiro, e mostrado como o caractere ASCII correspondente.
            {
                char s[2];
                memset( s, 0, 2 );

                if (HB_IS_STRING( pItem ))
                {
                    const char *t = hb_itemGetCPtr( pItem );
                    s[0] = ((t) ? t[0] : 0);
                } else if( HB_IS_NUMERIC( pItem ) )
                {
                    s[0] = (char) hb_itemGetNI( pItem );
                }

                printf_add_str( pInfo, s, 1L );
                break;
            }
            case 's':
            {
                Length = t2-t1;
                width  = max( hb_itemGetCLen( pItem ), (ULONG) width );
                cValue = (char *) hb_xgrab( width + 1 );

                memmove( mask, t1, Length );
                mask[Length] = '\0';

                cValue[0] = '\0';
                Length = sprintf( cValue, mask, hb_itemGetCPtr( pItem ) );
                printf_add_str( pInfo, cValue, Length );
                hb_xfree( cValue );
                break;
            }
            case 'p':
            {
                char s[9];
                s[0] = '\0';
                sprintf( s, "%p", hb_itemGetPtr( pItem ) );
                printf_add_str( pInfo, s, 8);
                break;
            }

            /*
             * Separamos aqui as operações sobre inteiros
             */
            case 'i':
            case 'd':
            // O argumento é tratado como um INTEIRO, e mostrado como um número decimal com sinal.
            case 'o':
            // O argumento é tratado com um INTEIRO, e mostrado como un número octal.
            case 'u':
            // O argumento é tratado com um INTEIRO, e mostrado como um número decimal sem sinal.
            case 'x':
            // O argumento é tratado como um INTEIRO, e mostrado como um número hexadecimal (com as letras minúsculas).
            case 'X':
                // O argumento é tratado como um INTEIRO, e mostrado como um número hexadecimal (com as letras maiúsculas).
            {
                Length = t2-t1;
                width  = ((width) ? width : 32 );
                cValue = (char *) hb_xgrab( width + 1 );

                memmove( mask, t1, Length );
                mask[Length] = '\0';
                cValue[0] = '\0';

                if (m == '\0')
                    Length = sprintf( cValue, mask, (int) hb_itemGetNI( pItem ));
                if (m == 'l')
                    Length = sprintf( cValue, mask, (LONG) hb_itemGetNL( pItem )); // como LONG ???
                if (m == 'h')
                    Length = sprintf( cValue, mask, (LONG) hb_itemGetNL( pItem )); // como LONG ???

                printf_add_str( pInfo, cValue, Length );
                hb_xfree( cValue );
                break;
            }

            /*
             * Separamos aqui as operações com numeros flutuantes
             */
            case 'e' :
            // O argumento é tratado como notação científica (e.g. 1.2e+2).
            case 'E' :
            // O argumento é tratado como notação científica (e.g. 1.2e+2).
            case 'f' :
            // O argumento é tratado como um float, e mostrado como um número de ponto flutuante.
            case 'F' :
                // O argumento é tratado como um float, e mostrado como um número de ponto flutuante.
            {
                Length = t2-t1;
                width  = ((width) ? width : 64 );
                dValue = (double) hb_itemGetND( pItem );     // converting double --> float ???
                cValue = (char *) hb_xgrab( width + 1 );

                memmove( mask, t1, Length );
                mask[Length] = '\0';

                sprintf( cValue, mask, dValue );
                printf_add_str( pInfo, cValue, strlen( cValue ) );
                hb_xfree( cValue );
                break;
            }

            default:
                break;
            }
            break;
        } else {
            pInfo->Mask ++;
            pInfo->msk_len--;
        }
    }
}
Ejemplo n.º 12
0
static HB_ERRCODE sqlbaseRddInfo( LPRDDNODE pRDD, HB_USHORT uiIndex, ULONG ulConnect, PHB_ITEM pItem )
{
   ULONG ulConn;
   SQLDDCONNECTION * pConn;

   HB_SYMBOL_UNUSED( pRDD );

   ulConn = ulConnect ? ulConnect : s_ulConnectionCurrent;
   if ( ulConn > 0 && ulConn <= s_ulConnectionCount )
      pConn = s_pConnection[ ulConn - 1 ];
   else
      pConn = NULL;

   switch( uiIndex )
   {

      case RDDI_REMOTE:
         hb_itemPutL( pItem, HB_TRUE );
         break;

      case RDDI_CONNECTION:
      {
         ULONG ulNewConnection = 0;

         if ( hb_itemType( pItem ) & HB_IT_NUMERIC )
         {
            ulNewConnection = hb_itemGetNL( pItem );
         }
         hb_itemPutNL( pItem, ulConnect ? ulConnect : s_ulConnectionCurrent );
         if ( ulNewConnection )
         {
            s_ulConnectionCurrent = ulNewConnection;
         }
         break;
      }

      case RDDI_ISDBF:
         hb_itemPutL( pItem, HB_FALSE );
         break;

      case RDDI_CANPUTREC:
         hb_itemPutL( pItem, HB_TRUE );
         break;


      case RDDI_CONNECT:
      {
         PSDDNODE     pNode = NULL;
         ULONG     ul;
         const char * pStr;

         pStr = hb_arrayGetCPtr( pItem, 1 );
         if ( pStr )
         {
            pNode = s_pSdd;
            while ( pNode )
            {
               if ( ! hb_stricmp( pNode->Name, pStr ) )
                  break;
               pNode = pNode->pNext;
            }
         }

         hb_rddsqlSetError( 0, NULL, NULL, NULL, 0 );
         pConn = ( SQLDDCONNECTION * ) hb_xgrab( sizeof( SQLDDCONNECTION ) );
         memset( pConn,  0, sizeof( SQLDDCONNECTION ) );
         if ( pNode && pNode->Connect( pConn, pItem ) == HB_SUCCESS )
         {
            pConn->pSDD = pNode;

            /* Find free connection handle */
            for ( ul = 0; ul < s_ulConnectionCount; ul++ )
            {
               if ( ! s_pConnection[ ul ] )
                  break;
            }
            if ( ul >= s_ulConnectionCount )
            {
               /* Realloc connection table */
               if ( s_pConnection )
                  s_pConnection = ( SQLDDCONNECTION ** ) hb_xrealloc( s_pConnection, sizeof( SQLDDCONNECTION * ) * ( s_ulConnectionCount + CONNECTION_LIST_EXPAND ) );
               else
                  s_pConnection = ( SQLDDCONNECTION ** ) hb_xgrab( sizeof( SQLDDCONNECTION * ) * CONNECTION_LIST_EXPAND );
    
               memset( s_pConnection + s_ulConnectionCount, 0, sizeof( SQLDDCONNECTION * ) * CONNECTION_LIST_EXPAND );
               ul = s_ulConnectionCount;
               s_ulConnectionCount += CONNECTION_LIST_EXPAND;
            }
            s_pConnection[ ul ] = pConn;
            ul++;
            s_ulConnectionCurrent = ul;
         }
         else
         {
            hb_xfree( pConn );
            ul = 0;
         }

         hb_itemPutNI( pItem, ul );
         break;
      }

      case RDDI_DISCONNECT:
      {
         hb_rddsqlSetError( 0, NULL, NULL, NULL, 0 );
         if ( pConn && ! pConn->uiAreaCount && pConn->pSDD->Disconnect( pConn ) == HB_SUCCESS )
         {
            hb_xfree( pConn );
            s_pConnection[ ulConn - 1 ] = NULL;
            if( s_ulConnectionCurrent == ulConn )
            {
               s_ulConnectionCurrent = 0;
            }
            hb_itemPutL( pItem, HB_TRUE );
            return HB_SUCCESS;
         }
         hb_itemPutL( pItem, HB_FALSE );
         return HB_SUCCESS;
      }

      case RDDI_EXECUTE:
      {
         hb_rddsqlSetError( 0, NULL, NULL, NULL, 0 );
         if ( pConn )
            hb_itemPutL( pItem, pConn->pSDD->Execute( pConn, pItem ) == HB_SUCCESS );
         else
            hb_itemPutL( pItem, HB_FALSE );

         return HB_SUCCESS;
      }

      case RDDI_ERROR:
      {
         hb_itemPutC( pItem, s_szError );
         return HB_SUCCESS;
      }

      case RDDI_ERRORNO:
      {
         hb_itemPutNI( pItem, s_errCode );
         return HB_SUCCESS;
      }

      case RDDI_QUERY:
      {
         hb_itemPutC( pItem, s_szQuery );
         return HB_SUCCESS;
      }

      case RDDI_NEWID:
      {
         hb_itemCopy( pItem, s_pItemNewID );
         return HB_SUCCESS;
      }

      case RDDI_AFFECTEDROWS:
      {
         hb_itemPutNInt( pItem, s_ulAffectedRows );
         return HB_SUCCESS;
      }

/*
      default:
         return SUPER_RDDINFO( pRDD, uiIndex, ulConnect, pItem );
*/

   }

   return HB_SUCCESS;
}
Ejemplo n.º 13
0
static HB_ERRCODE sqlbaseCreate( SQLBASEAREAP pArea, LPDBOPENINFO pOpenInfo )
{
   PHB_ITEM    pItemEof, pItem;
   HB_USHORT   uiCount;
   HB_BOOL     bError;

   pArea->ulConnection = pOpenInfo->ulConnection ? pOpenInfo->ulConnection : s_ulConnectionCurrent;

   if ( pArea->ulConnection > s_ulConnectionCount ||
        ( pArea->ulConnection && ! s_pConnection[ pArea->ulConnection - 1 ] ) )
   {
      hb_errRT_SQLBASE( EG_OPEN, ESQLDD_NOTCONNECTED, "Not connected", NULL );
      return HB_FAILURE;
   }

   if ( pArea->ulConnection )
   {
      pArea->pConnection = s_pConnection[ pArea->ulConnection - 1 ];
      pArea->pConnection->uiAreaCount++;
      pArea->pSDD = pArea->pConnection->pSDD;
   }
   else
   {
      pArea->pSDD = &sddNull;
   }

   pItemEof = hb_itemArrayNew( pArea->area.uiFieldCount );

   bError = HB_FALSE;
   for ( uiCount = 0; uiCount < pArea->area.uiFieldCount; uiCount++  )
   {
      LPFIELD pField = pArea->area.lpFields + uiCount;

      switch ( pField->uiType )
      {
         case HB_FT_STRING:
         {
            char*    pStr;

            pStr = ( char * ) hb_xgrab( pField->uiLen + 1 );
            memset( pStr, ' ', pField->uiLen );
            pStr[ pField->uiLen ] = '\0';

            pItem = hb_itemPutCL( NULL, pStr, pField->uiLen );
            hb_xfree( pStr );
            break;
         }

         case HB_FT_MEMO:
            pItem = hb_itemPutC( NULL, NULL );
            break;

         case HB_FT_INTEGER:
            if ( pField->uiDec )
               pItem = hb_itemPutND( NULL, 0.0 );
            else
               pItem = hb_itemPutNI( NULL, 0 );
            break;

         case HB_FT_LONG:
            if ( pField->uiDec )
               pItem = hb_itemPutND( NULL, 0.0 );
            else
               pItem = hb_itemPutNL( NULL, 0 );
            break;

         case HB_FT_FLOAT:
            pItem = hb_itemPutND( NULL, 0.0 );
            break;

         case HB_FT_DOUBLE:
            pItem = hb_itemPutND( NULL, 0.0 );
            break;

         case HB_FT_DATE:
            pItem = hb_itemPutDS( NULL, NULL );
            break;

         case HB_FT_LOGICAL:
            pItem = hb_itemPutL( NULL, HB_FALSE );
            break;

         default:
            pItem = hb_itemNew( NULL );
            bError = HB_TRUE;
            break;
      }

      hb_arraySetForward( pItemEof, uiCount + 1, pItem );
      hb_itemRelease( pItem );

      if ( bError )
         break;
   }

   if ( bError )
   {
      hb_itemClear( pItemEof );
      hb_itemRelease( pItemEof );
      hb_errRT_SQLBASE( EG_CORRUPTION, ESQLDD_INVALIDFIELD, "Invalid field type", NULL );
      SELF_CLOSE( ( AREAP ) pArea );
      return HB_FAILURE;
   }

   pArea->ulRecCount = 0;

   pArea->pRow = ( void ** ) hb_xalloc( SQLDD_ROWSET_RESIZE * sizeof( void * ) );
   pArea->pRowFlags = ( HB_BYTE * ) hb_xalloc( SQLDD_ROWSET_RESIZE * sizeof( HB_BYTE ) );
   pArea->ulRecMax = SQLDD_ROWSET_RESIZE;

   * (pArea->pRow) = pItemEof;
   pArea->pRowFlags[ 0 ] = SQLDD_FLAG_CACHED;
   pArea->fFetched = HB_TRUE;

   if ( SUPER_CREATE( ( AREAP ) pArea, pOpenInfo ) != HB_SUCCESS )
   {
      SELF_CLOSE( ( AREAP ) pArea );
      return HB_FAILURE;
   }

   return SELF_GOTOP( ( AREAP ) pArea );
}
Ejemplo n.º 14
0
static HB_ERRCODE sqlite3Open( SQLBASEAREAP pArea )
{
   sqlite3 *      pDb = ( ( SDDCONN * ) pArea->pConnection->pSDDConn )->pDb;
   sqlite3_stmt * st  = NULL;
   SDDDATA *      pSDDData;
   const char *   pszQuery;
   HB_SIZE        nQueryLen;
   void *         hQuery;
   HB_USHORT      uiFields, uiIndex;
   PHB_ITEM       pItemEof, pItem, pName = NULL;
   HB_ERRCODE     errCode;
   char *         szError;
   HB_BOOL        bError;

   pArea->pSDDData = memset( hb_xgrab( sizeof( SDDDATA ) ), 0, sizeof( SDDDATA ) );
   pSDDData        = ( SDDDATA * ) pArea->pSDDData;

   pItem    = hb_itemPutC( NULL, pArea->szQuery );
   pszQuery = S_HB_ITEMGETSTR( pItem, &hQuery, &nQueryLen );

   if( sqlite3_prepare_v2( pDb, pszQuery, ( int ) nQueryLen, &st, NULL ) != SQLITE_OK )
   {
      hb_strfree( hQuery );
      hb_itemRelease( pItem );
      szError = sqlite3GetError( pDb, &errCode );
      hb_errRT_SQLT3DD( EG_OPEN, ESQLDD_INVALIDQUERY, szError, pArea->szQuery, errCode );
      sqlite3_finalize( st );
      hb_xfree( szError );
      return HB_FAILURE;
   }
   else
   {
      hb_strfree( hQuery );
      hb_itemRelease( pItem );
   }

   if( sqlite3_step( st ) != SQLITE_ROW )
   {
      szError = sqlite3GetError( pDb, &errCode );
      hb_errRT_SQLT3DD( EG_OPEN, ESQLDD_INVALIDQUERY, szError, pArea->szQuery, errCode );
      sqlite3_finalize( st );
      hb_xfree( szError );
      return HB_FAILURE;
   }

   uiFields = ( HB_USHORT ) sqlite3_column_count( st );
   SELF_SETFIELDEXTENT( &pArea->area, uiFields );

   errCode = 0;
   bError  = HB_FALSE;
   pItemEof = hb_itemArrayNew( uiFields );
   for( uiIndex = 0; uiIndex < uiFields; ++uiIndex )
   {
      DBFIELDINFO dbFieldInfo;

      memset( &dbFieldInfo, 0, sizeof( dbFieldInfo ) );
      pName = S_HB_ITEMPUTSTR( pName, sqlite3_column_name( st, uiIndex ) );
      dbFieldInfo.atomName = hb_itemGetCPtr( pName );
      dbFieldInfo.uiType = sqlite3DeclType( st, uiIndex );
      pItem = hb_arrayGetItemPtr( pItemEof, uiIndex + 1 );

      switch( dbFieldInfo.uiType )
      {
         case HB_FT_STRING:
         {
            int iSize = sqlite3_column_bytes( st, uiIndex );
            char * pStr;

            dbFieldInfo.uiLen = ( HB_USHORT ) HB_MAX( iSize, 10 );
            pStr = ( char * ) hb_xgrab( ( HB_SIZE ) dbFieldInfo.uiLen + 1 );
            memset( pStr, ' ', dbFieldInfo.uiLen );
            hb_itemPutCLPtr( pItem, pStr, dbFieldInfo.uiLen );
            break;
         }
         case HB_FT_BLOB:
            dbFieldInfo.uiLen = 4;
            hb_itemPutC( pItem, NULL );
            break;

         case HB_FT_INTEGER:
            dbFieldInfo.uiLen = 8;
            hb_itemPutNInt( pItem, 0 );
            break;

         case HB_FT_LONG:
            dbFieldInfo.uiLen = 20;
            dbFieldInfo.uiDec = ( HB_USHORT ) hb_setGetDecimals();
            hb_itemPutNDDec( pItem, 0.0, dbFieldInfo.uiDec );
            break;

         case HB_FT_ANY:
            dbFieldInfo.uiLen = 6;
            break;

         default:
            bError = HB_TRUE;
      }

      if( ! bError )
         bError = ( SELF_ADDFIELD( &pArea->area, &dbFieldInfo ) == HB_FAILURE );

      if( bError )
         break;
   }
   hb_itemRelease( pName );

   if( bError )
   {
      hb_itemRelease( pItemEof );
      sqlite3_finalize( st );
      hb_errRT_SQLT3DD( EG_CORRUPTION, ESQLDD_INVALIDFIELD, "Invalid field type", pArea->szQuery, errCode );
      return HB_FAILURE;
   }

   pArea->ulRecCount = 0;
   pArea->ulRecMax   = SQLDD_ROWSET_INIT;

   pArea->pRow = ( void ** ) hb_xgrab( SQLDD_ROWSET_INIT * sizeof( void * ) );
   pArea->pRowFlags = ( HB_BYTE * ) hb_xgrab( SQLDD_ROWSET_INIT * sizeof( HB_BYTE ) );

   pArea->pRow[ 0 ]      = pItemEof;
   pArea->pRowFlags[ 0 ] = SQLDD_FLAG_CACHED;

   pSDDData->pStmt = st;
   return HB_SUCCESS;
}
Ejemplo n.º 15
0
int main( int argc, char * argv[] )
{
   char *         szFile         = NULL, * szRuleFile = NULL, * szWordFile = NULL, * szVerFile = NULL;
   char *         szLogFile      = NULL;
   BOOL           fQuiet         = FALSE, fWrite = FALSE, fChgLog = FALSE;
   char *         szChangeLogID  = NULL, * szLastEntry = NULL;
   int            iResult        = 0, i;
   PHB_PP_STATE   pState;

   pState = hb_pp_new();

   if( argc >= 2 )
   {
      szFile = argv[ 1 ];
      for( i = 2; szFile && i < argc; i++ )
      {
         if( ! HB_ISOPTSEP( argv[ i ][ 0 ] ) )
            szFile = NULL;
         else
         {
            switch( argv[ i ][ 1 ] )
            {
               case 'q':
               case 'Q':
                  if( argv[ i ][ 2 ] )
                     szFile = NULL;
                  else
                     fQuiet = TRUE;
                  break;

               case 'w':
               case 'W':
                  if( argv[ i ][ 2 ] )
                     szFile = NULL;
                  else
                     fWrite = TRUE;
                  break;

               case 'c':
               case 'C':
                  fChgLog = TRUE;
                  if( argv[ i ][ 2 ] )
                     szLogFile = argv[ i ] + 2;
                  break;

               case 'i':
               case 'I':
                  if( argv[ i ][ 2 ] )
                     hb_pp_addSearchPath( pState, argv[ i ] + 2, FALSE );
                  else
                     szFile = NULL;
                  break;

               case 'o':
               case 'O':
                  if( argv[ i ][ 2 ] )
                     szRuleFile = argv[ i ] + 2;
                  else
                     szFile = NULL;
                  break;

               case 'x':
               case 'X':
                  if( argv[ i ][ 2 ] )
                     szWordFile = argv[ i ] + 2;
                  else
                     szWordFile = NULL;
                  break;

               case 'v':
               case 'V':
                  if( argv[ i ][ 2 ] )
                     szVerFile = argv[ i ] + 2;
                  else
                     szFile = NULL;
                  break;

               default:
                  szFile = NULL;
                  break;
            }
         }
      }
   }

   if( szFile )
   {
      hb_pp_init( pState, fQuiet, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL );
      if( hb_pp_inFile( pState, szFile, TRUE, NULL, TRUE ) )
      {
         char * szSVNID = ( char * ) hb_xgrab( 10 );
         char * szSVNDateID = ( char * ) hb_xgrab( 10 );
         if( fWrite )
         {
            char        szFileName[ HB_PATH_MAX ];
            PHB_FNAME   pFileName;

            pFileName               = hb_fsFNameSplit( szFile );
            pFileName->szExtension  = ".ppo";
            hb_fsFNameMerge( szFileName, pFileName );
            hb_xfree( pFileName );

            hb_pp_outFile( pState, szFileName, NULL );
         }

         if( fChgLog )
            iResult = hb_pp_parseChangelog( pState, szLogFile, fQuiet,
                                            szSVNID, szSVNDateID, &szChangeLogID, &szLastEntry );

         if( iResult == 0 )
            iResult = hb_pp_preprocesfile( pState, szRuleFile, szWordFile );

         if( iResult == 0 && szVerFile )
            iResult = hb_pp_generateVerInfo( szVerFile, szSVNID, szSVNDateID,
                                             szChangeLogID, szLastEntry );

         hb_xfree( szSVNID );
         hb_xfree( szSVNDateID );
      }
      else
         iResult = 1;
   }
   else
   {
      hb_pp_usage( argv[ 0 ] );
      iResult = 1;
   }

   if( szChangeLogID )
      hb_xfree( szChangeLogID );
   if( szLastEntry )
      hb_xfree( szLastEntry );

   hb_pp_free( pState );

   return iResult;
}
Ejemplo n.º 16
0
/* internal routine to do buffer skips.  Passing a positive value performs
   a downward skip, a negative number does an upward skip.  Passing 0
   skips to the end of file.
   Returns a long indicating the number of records skipped */
static long _ft_skip( long iRecs )
{
   PFT_TEXT ft_text = ( PFT_TEXT ) hb_stackGetTSD( &s_ft_text );

   HB_ISIZ iByteCount;
   HB_ISIZ iBytesRead, iBytesRemaining;
   char *  cPtr;
   long    iSkipped = 0;

   char *     cBuff    = ( char * ) hb_xgrab( BUFFSIZE );
   HB_FOFFSET fpOffset = ft_text->offset[ ft_text->area ];

   ft_text->isBof[ ft_text->area ] = HB_FALSE;
   ft_text->isEof[ ft_text->area ] = HB_FALSE;
   ft_text->error[ ft_text->area ] = 0;

   /* iRecs is zero if they want to find the EOF, start a top of file */
   if( iRecs == 0 )
   {
      fpOffset = 0;
      ft_text->recno[ ft_text->area ] = 1;
   }

   if( iRecs >= 0 )
   {
      do
      {
         cPtr = cBuff;

         /* position file pointer to beginning of current record */
         hb_fsSeekLarge( ft_text->handles[ ft_text->area ], fpOffset, FS_SET );

         /* read a chunk */
         iBytesRead = hb_fsRead( ft_text->handles[ ft_text->area ], cBuff, BUFFSIZE );

         if( ! iBytesRead )
         {
            /* buffer is empty thus EOF, set vars and quit */
            ft_text->isEof[ ft_text->area ]    = HB_TRUE;
            ft_text->last_rec[ ft_text->area ] = ft_text->recno[ ft_text->area ];
            ft_text->last_off[ ft_text->area ] = ft_text->offset[ ft_text->area ];
            ft_text->error[ ft_text->area ]    = hb_fsError();
            break;
         }

         iBytesRemaining = iBytesRead;
         /* parse the buffer while there's still stuff in it */
         do
         {
            /* get count of chars in this line */
            iByteCount = _findeol( cPtr, iBytesRemaining, NULL );

            if( iByteCount > 0 && iByteCount != iBytesRemaining )
            {
               /* found an EOL, iByteCount points to first char of next record */
               iBytesRemaining -= iByteCount;
               fpOffset        += iByteCount;
               cPtr += iByteCount;
               ft_text->offset[ ft_text->area ] = fpOffset;
               ft_text->recno[ ft_text->area ]++;
               iSkipped++;
               if( iRecs && ( iSkipped == iRecs ) )
                  iBytesRemaining = iBytesRead = 0;
            }
            else
            {
               /* no more EOLs in this buffer, or EOL is last chars in the buffer */

               /* check for EOF */
               if( iBytesRead != BUFFSIZE )
               {
                  /* buffer was not full, thus EOF, set vars and quit */
                  iBytesRemaining = 0;
                  ft_text->last_rec[ ft_text->area ] = ft_text->recno[ ft_text->area ];
                  ft_text->last_off[ ft_text->area ] = ft_text->offset[ ft_text->area ];
                  if( iRecs )
                     ft_text->isEof[ ft_text->area ] = HB_TRUE;
               }
               else
               {
                  /* buffer was full, so probably not EOF, but maybe EOL straddled end
                     of buffer, so back up pointer a bit before doing the next read */
                  fpOffset        = hb_fsSeekLarge( ft_text->handles[ ft_text->area ], 0, FS_RELATIVE ) - 1;
                  iBytesRemaining = 0;
               }
            }
         }
         while( iBytesRemaining > 0 );
      }
      while( iBytesRead == BUFFSIZE );
   }
   else
   {
      /* skip backwards */
      iRecs = -iRecs;

      if( ft_text->recno[ ft_text->area ] > iRecs )
      {
         do
         {
            /* calc offset to read area of file ahead of current pointer */
            fpOffset = HB_MAX( ft_text->offset[ ft_text->area ] - BUFFSIZE, 0 );

            /* move file pointer */
            hb_fsSeekLarge( ft_text->handles[ ft_text->area ], fpOffset, FS_SET );

            /* read a chunk */
            iBytesRead =
               hb_fsRead( ft_text->handles[ ft_text->area ], cBuff, BUFFSIZE );

            if( ! iBytesRead )
            {
               /* buffer is empty thus file is zero len, set vars and quit */
               ft_text->isBof[ ft_text->area ]    = HB_TRUE;
               ft_text->isEof[ ft_text->area ]    = HB_TRUE;
               ft_text->recno[ ft_text->area ]    = 0;
               ft_text->offset[ ft_text->area ]   = 0;
               ft_text->last_rec[ ft_text->area ] = 0;
               ft_text->error[ ft_text->area ]    = hb_fsError();
               break;
            }

            /* set pointer within buffer */

            iBytesRemaining = ( int ) ( ft_text->offset[ ft_text->area ] - fpOffset );

            cPtr = cBuff + iBytesRemaining;

            /* parse the buffer while there's still stuff in it */
            do
            {
               /* get count of chars in this line */
               iByteCount = _findbol( cPtr, iBytesRemaining );

               if( iByteCount > 0 )
               {
                  /* found an EOL, iByteCount points to first char of next
                     record */
                  iBytesRemaining -= iByteCount;
                  ft_text->offset[ ft_text->area ] -= iByteCount;
                  cPtr    -= iByteCount;
                  fpOffset = ft_text->offset[ ft_text->area ];
                  ft_text->recno[ ft_text->area ]--;
                  iSkipped++;
                  if( iSkipped == iRecs )
                     iBytesRemaining = iBytesRead = 0;
               }
               else
               {
                  /* no more EOLs in this buffer so we're either at
                     BOF or record crosses buffer boundary */
                  /* check for BOF */
                  if( iBytesRead != BUFFSIZE )
                  {
                     /* buffer was not full, thus BOF, set vars and quit */
                     iBytesRemaining = 0;
                     ft_text->offset[ ft_text->area ] = 0;
                     ft_text->recno[ ft_text->area ]  = 1;
                     ft_text->isBof[ ft_text->area ]  = HB_TRUE;
                  }
                  else
                  {
                     /* buffer was full, so not BOF */
                     iBytesRemaining = 0;
                  }
               }
            }
            while( iBytesRemaining > 0 );
         }
         while( fpOffset > 0 && iBytesRead == BUFFSIZE );
      }
      else
      {
         ft_text->offset[ ft_text->area ] = 0;
         ft_text->recno[ ft_text->area ]  = 1;
         ft_text->isBof[ ft_text->area ]  = HB_TRUE;
      }
   }

   hb_xfree( cBuff );
   return iSkipped;
}
Ejemplo n.º 17
0
static void hb_ParseLine( PHB_ITEM pReturn, const char * szText, int iDelimiter, int * iWord )
{
   if( szText )
   {
      HB_ISIZ nLen = strlen( szText );

      if( nLen > 0 )
      {
         PHB_ITEM pTemp      = hb_itemNew( NULL );
         HB_ISIZ  i          = 0;
         int      word_count = 0;
         /* booked enough memory */
         char * szResult = ( char * ) hb_xgrab( nLen + 1 );

#if 0
         while( nLen )
         {
            if( szText[ nLen - 1 ] && ! HB_ISSPACE( szText[ nLen - 1 ] ) )
               break;

            nLen--;
         }

         szText[ nLen ] = 0;

         nLen = strlen( szText );
#endif

         while( i < nLen )
         {
            HB_ISIZ ui = 0;

            hb_xmemset( szResult, ' ', nLen + 1 );

            /* an '"' found, loop until the next one is found */
            if( szText[ i ] == '"' )
            {
               /* an '"' after '"' ? */
               if( szText[ i + 1 ] != '"' )
                  szResult[ ui ] = szText[ i + 1 ];
               else
                  szResult[ ui ] = '\0';

               ++i;

               while( ++i < nLen )
               {
                  if( szText[ i - 1 ] == '"' )
                  {
                     szResult[ ui + 1 ] = '\0';
                     break;
                  }
                  else
                  {
                     if( szText[ i ] == '"' )
                        szResult[ ui + 1 ] = '\0';
                     else
                        szResult[ ++ui ] = szText[ i ];
                  }
               }
               word_count++;
               hb_arrayAddForward( pReturn, hb_itemPutC( pTemp, szResult ) );
            }
            /* delimiter found */
            else if( szText[ i ] == iDelimiter )
            {
               /* first delimiter found but no word yet */
               if( word_count == 0 )
               {
                  /* add an empty string */
                  szResult[ ui ] = '\0';
               }
               else
               {
                  /* we have already have the first word */
                  /* check next character */
                  if( szText[ i - 1 ] == iDelimiter )
                  {
                     /* delimiter after delimiter */
                     /* just add an empty string */
                     szResult[ ui ] = '\0';
                  }
                  else
                  {
                     /* ",,0" */
                     /* it is not a delimiter */
                     /* move to next character */
                     ++i;
                     szResult[ ui ] = szText[ i ];

                     while( ++i < nLen )
                     {
                        if( szText[ i ] == iDelimiter )
                           break;
                        else
                           szResult[ ++ui ] = szText[ i ];
                     }
                  }
               }
               word_count++;
               szResult[ ui + 1 ] = '\0';
               hb_arrayAddForward( pReturn, hb_itemPutC( pTemp, szResult ) );
            }
            else
            {
               szResult[ ui ] = szText[ i ];

               while( ++i < nLen )
               {
                  if( szText[ i ] == iDelimiter )
                  {
                     szResult[ ui + 1 ] = '\0';
                     break;
                  }
                  else if( szText[ i ] == '"' )
                  {
                     szResult[ ui ] = szText[ i + 1 ];
                     ++i;

                     while( ++i < nLen )
                     {
                        if( szText[ i - 1 ] == '"' )
                        {
                           szResult[ ui + 1 ] = '\0';
                           break;
                        }
                        else
                        {
                           if( szText[ i ] == '"' )
                           {
                              szResult[ ui + 1 ] = '\0';
                              break;
                           }
                           else
                              szResult[ ++ui ] = szText[ i ];
                        }
                     }
                  }
                  else
                     szResult[ ++ui ] = szText[ i ];
               }
               word_count++;
               szResult[ ui + 1 ] = '\0';
               hb_arrayAddForward( pReturn, hb_itemPutC( pTemp, szResult ) );
            }

            i++;
         }

         /* last character in passed string is a delimiter */
         /* just add an empty string */
         if( szText[ nLen - 1 ] == iDelimiter )
         {
            word_count++;
            hb_arrayAddForward( pReturn, hb_itemPutC( pTemp, NULL ) );
         }

         /* store number of words */
         *iWord = word_count;

         /* clean up */
         hb_xfree( szResult );

         hb_itemRelease( pTemp );
      }
   }
}
Ejemplo n.º 18
0
static PHRB_BODY hb_hrbLoad( const char * szHrbBody, HB_SIZE nBodySize, HB_USHORT usMode, const char * szFileName )
{
   PHRB_BODY pHrbBody = NULL;

   if( szHrbBody )
   {
      HB_SIZE nBodyOffset = 0;
      HB_SIZE nSize;                              /* Size of function */
      HB_SIZE nPos;
      HB_ULONG ul;
      char * buffer, ch;
      HB_USHORT usBind = ( usMode & HB_HRB_BIND_MODEMASK );

      PHB_SYMB pSymRead;                           /* Symbols read     */
      PHB_DYNF pDynFunc;                           /* Functions read   */
      PHB_DYNS pDynSym;

      int iVersion = hb_hrbReadHead( szHrbBody, nBodySize, &nBodyOffset );

      if( iVersion == 0 )
      {
         hb_errRT_BASE( EG_CORRUPTION, 9995, NULL, HB_ERR_FUNCNAME, 0 );
         return NULL;
      }

      pHrbBody = ( PHRB_BODY ) hb_xgrab( sizeof( HRB_BODY ) );

      pHrbBody->fInit = HB_FALSE;
      pHrbBody->fExit = HB_FALSE;
      pHrbBody->lSymStart = -1;
      pHrbBody->ulFuncs = 0;
      pHrbBody->pSymRead = NULL;
      pHrbBody->pDynFunc = NULL;
      pHrbBody->pModuleSymbols = NULL;
      if( ! hb_hrbReadValue( szHrbBody, nBodySize, &nBodyOffset, &pHrbBody->ulSymbols ) ||
            pHrbBody->ulSymbols == 0 )
      {
         hb_hrbUnLoad( pHrbBody );
         hb_errRT_BASE( EG_CORRUPTION, 9996, NULL, HB_ERR_FUNCNAME, 0 );
         return NULL;
      }

      /* calculate the size of dynamic symbol table */
      nPos = nBodyOffset;
      nSize = 0;

      for( ul = 0; ul < pHrbBody->ulSymbols; ul++ )  /* Read symbols in .hrb */
      {
         while( nBodyOffset < nBodySize )
         {
            ++nSize;
            if( szHrbBody[ nBodyOffset++ ] == 0 )
               break;
         }
         nBodyOffset += 2;
         if( nBodyOffset >= nBodySize )
         {
            hb_hrbUnLoad( pHrbBody );
            hb_errRT_BASE( EG_CORRUPTION, 9997, NULL, HB_ERR_FUNCNAME, 0 );
            return NULL;
         }
      }

      nBodyOffset = nPos;
      ul = pHrbBody->ulSymbols * sizeof( HB_SYMB );
      pSymRead = ( PHB_SYMB ) hb_xgrab( nSize + ul );
      buffer = ( ( char * ) pSymRead ) + ul;

      for( ul = 0; ul < pHrbBody->ulSymbols; ul++ )  /* Read symbols in .hrb */
      {
         pSymRead[ ul ].szName = buffer;
         do
         {
            ch = *buffer++ = szHrbBody[ nBodyOffset++ ];
         }
         while( ch );
         pSymRead[ ul ].scope.value = ( HB_BYTE ) szHrbBody[ nBodyOffset++ ];
         pSymRead[ ul ].value.pCodeFunc = ( PHB_PCODEFUNC ) ( HB_PTRDIFF ) szHrbBody[ nBodyOffset++ ];
         pSymRead[ ul ].pDynSym = NULL;

         if( pHrbBody->lSymStart == -1 &&
             ( pSymRead[ ul ].scope.value & HB_FS_FIRST ) != 0 &&
             ( pSymRead[ ul ].scope.value & HB_FS_INITEXIT ) == 0 )
         {
            pHrbBody->lSymStart = ul;
         }
      }

      /* Read number of functions */
      if( ! hb_hrbReadValue( szHrbBody, nBodySize, &nBodyOffset, &pHrbBody->ulFuncs ) )
      {
         hb_xfree( pSymRead );
         hb_hrbUnLoad( pHrbBody );
         hb_errRT_BASE( EG_CORRUPTION, 9997, NULL, HB_ERR_FUNCNAME, 0 );
         return NULL;
      }

      pHrbBody->pSymRead = pSymRead;

      if( pHrbBody->ulFuncs )
      {
         pDynFunc = ( PHB_DYNF ) hb_xgrab( pHrbBody->ulFuncs * sizeof( HB_DYNF ) );
         memset( pDynFunc, 0, pHrbBody->ulFuncs * sizeof( HB_DYNF ) );
         pHrbBody->pDynFunc = pDynFunc;

         for( ul = 0; ul < pHrbBody->ulFuncs; ul++ )
         {
            HB_ULONG ulValue;

            /* Read name of function */
            pDynFunc[ ul ].szName = hb_hrbReadId( szHrbBody, nBodySize, &nBodyOffset );
            if( pDynFunc[ ul ].szName == NULL )
               break;

            /* Read size of function */
            if( ! hb_hrbReadValue( szHrbBody, nBodySize, &nBodyOffset, &ulValue ) )
               break;

            nSize = ( HB_SIZE ) ulValue;

            if( nBodyOffset + nSize > nBodySize )
               break;

            /* Copy function body */
            pDynFunc[ ul ].pCode = ( HB_BYTE * ) hb_xgrab( nSize );
            memcpy( ( char * ) pDynFunc[ ul ].pCode, szHrbBody + nBodyOffset, nSize );
            nBodyOffset += nSize;

            pDynFunc[ ul ].pCodeFunc = ( PHB_PCODEFUNC ) hb_xgrab( sizeof( HB_PCODEFUNC ) );
            pDynFunc[ ul ].pCodeFunc->pCode    = pDynFunc[ ul ].pCode;
            pDynFunc[ ul ].pCodeFunc->pSymbols = pSymRead;
         }

         if( ul < pHrbBody->ulFuncs )
         {
            hb_xfree( pSymRead );
            hb_hrbUnLoad( pHrbBody );
            hb_errRT_BASE( EG_CORRUPTION, 9998, NULL, HB_ERR_FUNCNAME, 0 );
            return NULL;
         }
      }

      /* End of PCODE loading, now linking */
      for( ul = 0; ul < pHrbBody->ulSymbols; ul++ )
      {
         if( pSymRead[ ul ].value.pCodeFunc == ( PHB_PCODEFUNC ) SYM_FUNC )
         {
            nPos = hb_hrbFindSymbol( pSymRead[ ul ].szName, pHrbBody->pDynFunc, pHrbBody->ulFuncs );

            if( nPos == SYM_NOT_FOUND )
            {
               pSymRead[ ul ].value.pCodeFunc = ( PHB_PCODEFUNC ) SYM_EXTERN;
            }
            else
            {
               pSymRead[ ul ].value.pCodeFunc = ( PHB_PCODEFUNC ) pHrbBody->pDynFunc[ nPos ].pCodeFunc;
               pSymRead[ ul ].scope.value |= HB_FS_PCODEFUNC | HB_FS_LOCAL |
                  ( usBind == HB_HRB_BIND_FORCELOCAL ? HB_FS_STATIC : 0 );
            }
         }
         else if( pSymRead[ ul ].value.pCodeFunc == ( PHB_PCODEFUNC ) SYM_DEFERRED )
         {
            pSymRead[ ul ].value.pCodeFunc = ( PHB_PCODEFUNC ) SYM_EXTERN;
            pSymRead[ ul ].scope.value |= HB_FS_DEFERRED;
         }

         /* External function */
         if( pSymRead[ ul ].value.pCodeFunc == ( PHB_PCODEFUNC ) SYM_EXTERN )
         {
            pSymRead[ ul ].value.pCodeFunc = NULL;

            pDynSym = hb_dynsymFind( pSymRead[ ul ].szName );

            if( pDynSym )
            {
               pSymRead[ ul ].value.pFunPtr = pDynSym->pSymbol->value.pFunPtr;
               if( pDynSym->pSymbol->scope.value & HB_FS_PCODEFUNC )
               {
                  pSymRead[ ul ].scope.value |= HB_FS_PCODEFUNC;
               }
            }
            else if( ( pSymRead[ ul ].scope.value & HB_FS_DEFERRED ) == 0 )
            {
               if( ( usMode & HB_HRB_BIND_LAZY ) != 0 )
                  pSymRead[ ul ].scope.value |= HB_FS_DEFERRED;
               else
               {
                  char szName[ HB_SYMBOL_NAME_LEN + 1 ];

                  hb_strncpy( szName, pSymRead[ ul ].szName, sizeof( szName ) - 1 );
                  hb_xfree( pSymRead );
                  hb_hrbUnLoad( pHrbBody );
                  hb_errRT_BASE( EG_ARG, 6101, "Unknown or unregistered symbol", szName, 0 );
                  return NULL;
               }
            }
         }
      }

      if( hb_vmLockModuleSymbols() )
      {
         if( usBind == HB_HRB_BIND_LOCAL )
         {
            for( ul = 0; ul < pHrbBody->ulSymbols; ul++ )
            {
               if( ( pSymRead[ ul ].scope.value &
                     ( HB_FS_LOCAL | HB_FS_STATIC ) ) == HB_FS_LOCAL )
               {
                  pDynSym = hb_dynsymFind( pSymRead[ ul ].szName );
                  if( pDynSym )
                  {
                     /* convert public function to static one */
                     pSymRead[ ul ].scope.value |= HB_FS_STATIC;
                  }
               }
            }
         }

         pHrbBody->pModuleSymbols = hb_vmRegisterSymbols( pHrbBody->pSymRead,
                        ( HB_USHORT ) pHrbBody->ulSymbols,
                        szFileName ? szFileName : "pcode.hrb", 0,
                        HB_TRUE, HB_FALSE, usBind == HB_HRB_BIND_OVERLOAD );

         if( pHrbBody->pModuleSymbols->pModuleSymbols != pSymRead )
         {
            /*
             * Old unused symbol table has been recycled - free the one
             * we allocated and disactivate static initialization [druzus]
             */
            pHrbBody->pSymRead = pHrbBody->pModuleSymbols->pModuleSymbols;
            hb_xfree( pSymRead );

            pHrbBody->fInit = HB_TRUE;
         }
         else
         {
            /* mark symbol table as dynamically allocated so HVM will free it on exit */
            pHrbBody->pModuleSymbols->fAllocated = HB_TRUE;

            /* initialize static variables */
            hb_hrbInitStatic( pHrbBody );
         }
         hb_vmUnlockModuleSymbols();
      }
      else
      {
         hb_xfree( pSymRead );
         hb_hrbUnLoad( pHrbBody );
         pHrbBody = NULL;
      }
   }

   return pHrbBody;
}
Ejemplo n.º 19
0
static HB_ERRCODE pgsqlDisconnect( SQLDDCONNECTION * pConnection )
{
   PQfinish( ( ( SDDCONN * ) pConnection->pSDDConn )->pConn );
   hb_xfree( pConnection->pSDDConn );
   return HB_SUCCESS;
}
Ejemplo n.º 20
0
PHB_ITEM hb_libLoad( PHB_ITEM pLibName, PHB_ITEM pArgs )
{
   void * hDynLib = NULL;

   if( hb_itemGetCLen( pLibName ) > 0 )
   {
      int argc = pArgs ? ( int ) hb_arrayLen( pArgs ) : 0, i;
      const char ** argv = NULL;

      if( argc > 0 )
      {
         argv = ( const char ** ) hb_xgrab( sizeof( char * ) * argc );
         for( i = 0; i < argc; ++i )
            argv[ i ] = hb_arrayGetCPtr( pArgs, i + 1 );
      }

      if( hb_vmLockModuleSymbols() )
      {
         /* use stack address as first level marker */
         hb_vmBeginSymbolGroup( ( void * ) hb_stackId(), HB_TRUE );
#if defined( HB_OS_WIN )
         {
            void * hFileName;

            hDynLib = ( void * ) LoadLibraryEx( HB_ITEMGETSTR( pLibName, &hFileName, NULL ), NULL, LOAD_WITH_ALTERED_SEARCH_PATH );

            hb_strfree( hFileName );
         }
#elif defined( HB_OS_OS2 )
         {
            HB_UCHAR LoadError[ 256 ] = "";  /* Area for load failure information */
            HMODULE hDynModule;
            if( DosLoadModule( ( PSZ ) LoadError, sizeof( LoadError ),
                               ( PCSZ ) hb_itemGetCPtr( pLibName ), &hDynModule ) == NO_ERROR )
               hDynLib = ( void * ) hDynModule;
         }
#elif defined( HB_HAS_DLFCN )
         hDynLib = ( void * ) dlopen( hb_itemGetCPtr( pLibName ), RTLD_LAZY | RTLD_GLOBAL );

         if( ! hDynLib )
         {
            HB_TRACE( HB_TR_DEBUG, ( "hb_libLoad(): dlopen(): %s", dlerror() ) );
         }
#elif defined( HB_CAUSEWAY_DLL )
         hDynLib = LoadLibrary( hb_itemGetCPtr( pLibName ) );
#else
         {
            int iTODO;
         }
#endif
         /* set real marker */
         hb_vmInitSymbolGroup( hDynLib, argc, argv );

         hb_vmUnlockModuleSymbols();
      }

      if( argv )
         hb_xfree( ( void * ) argv );
   }

   if( hDynLib )
   {
      void ** pLibPtr = ( void ** ) hb_gcAllocate( sizeof( void * ), &s_gcDynlibFuncs );
      *pLibPtr = hDynLib;
      return hb_itemPutPtrGC( NULL, pLibPtr );
   }

   return NULL;
}
Ejemplo n.º 21
0
PHB_ITEM hb_fsDirectory( const char * pszDirSpec, const char * pszAttributes, HB_BOOL fDateTime )
{
   PHB_ITEM  pDir = hb_itemArrayNew( 0 );
   char *    pszFree = NULL;
   PHB_FFIND ffind;
   HB_FATTR  ulMask;

   /* Get the passed attributes and convert them to Harbour Flags */

   ulMask = HB_FA_ARCHIVE | HB_FA_READONLY;

   if( pszAttributes && *pszAttributes )
      ulMask |= hb_fsAttrEncode( pszAttributes );

   if( pszDirSpec && *pszDirSpec )
   {
      if( ulMask != HB_FA_LABEL )
      {
         /* CA-Cl*pper compatible behavior - add all file mask when
          * last character is directory or drive separator
          */
         HB_SIZE nLen = strlen( pszDirSpec ) - 1;
#ifdef HB_OS_HAS_DRIVE_LETTER
         if( pszDirSpec[ nLen ] == HB_OS_PATH_DELIM_CHR ||
             pszDirSpec[ nLen ] == HB_OS_DRIVE_DELIM_CHR )
#else
         if( pszDirSpec[ nLen ] == HB_OS_PATH_DELIM_CHR )
#endif
            pszDirSpec = pszFree =
                           hb_xstrcpy( NULL, pszDirSpec, HB_OS_ALLFILE_MASK, NULL );
      }
   }
   else
      pszDirSpec = HB_OS_ALLFILE_MASK;

   /* Get the file list */

   if( ( ffind = hb_fsFindFirst( pszDirSpec, ulMask ) ) != NULL )
   {
      PHB_ITEM pSubarray = hb_itemNew( NULL );

      do
      {
         char buffer[ 32 ];

         hb_arrayNew    ( pSubarray, F_LEN );
         hb_arraySetC   ( pSubarray, F_NAME, ffind->szName );
         hb_arraySetNInt( pSubarray, F_SIZE, ffind->size );
         hb_arraySetC   ( pSubarray, F_TIME, ffind->szTime );
         hb_arraySetC   ( pSubarray, F_ATTR, hb_fsAttrDecode( ffind->attr, buffer ) );

         if( fDateTime )
            hb_arraySetTDT( pSubarray, F_DATE, ffind->lDate, ffind->lTime );
         else
            hb_arraySetDL ( pSubarray, F_DATE, ffind->lDate );

         /* Don't exit when array limit is reached */
         hb_arrayAddForward( pDir, pSubarray );
      }
      while( hb_fsFindNext( ffind ) );

      hb_itemRelease( pSubarray );

      hb_fsFindClose( ffind );
   }

   if( pszFree )
      hb_xfree( pszFree );

   return pDir;
}
Ejemplo n.º 22
0
static void s_inetRecvPattern( const char * const * patterns, int * patternsizes,
                               int iPatternsCount, int iParam )
{
   PHB_SOCKET_STRUCT socket = HB_PARSOCKET( 1 );
   PHB_ITEM pResult         = hb_param( iParam, HB_IT_BYREF );
   PHB_ITEM pMaxSize        = hb_param( iParam + 1, HB_IT_NUMERIC );
   PHB_ITEM pBufferSize     = hb_param( iParam + 2, HB_IT_NUMERIC );

   char cChar = '\0';
   char * buffer;
   int iPaternFound = 0;
   int iTimeElapsed = 0;
   int iPos = 0;
   int iLen;
   int iAllocated, iBufferSize, iMax;
   int i;

   if( socket == NULL )
   {
      hb_inetErrRT();
      return;
   }
   else if( ! hb_inetIsOpen( socket ) )
   {
      if( pResult )
         hb_itemPutNI( pResult, -1 );
      hb_retc_null();
      return;
   }


   iBufferSize = pBufferSize ? hb_itemGetNI( pBufferSize ) : 80;
   iMax = pMaxSize ? hb_itemGetNI( pMaxSize ) : 0;

   socket->iError = HB_INET_ERR_OK;

   buffer = ( char * ) hb_xgrab( iBufferSize );
   iAllocated = iBufferSize;

   do
   {
      if( iPos == iAllocated - 1 )
      {
         iAllocated += iBufferSize;
         buffer = ( char * ) hb_xrealloc( buffer, iAllocated );
      }

      iLen = s_inetRecv( socket, &cChar, 1, HB_TRUE, socket->iTimeout );
      if( iLen == -1 && s_inetIsTimeout( socket ) )
      {
         iLen = -2;     /* this signals timeout */
         if( socket->pPeriodicBlock )
         {
            HB_BOOL fResult;

            iTimeElapsed += socket->iTimeout;
            hb_execFromArray( socket->pPeriodicBlock );
            fResult = hb_parl( -1 ) && hb_vmRequestQuery() == 0;

            if( fResult &&
                ( socket->iTimeLimit == -1 || iTimeElapsed < socket->iTimeLimit ) )
               iLen = 1;
         }
      }
      else if( iLen > 0 )
      {
         buffer[ iPos++ ] = cChar;
         for( i = 0; i < iPatternsCount; ++i )
         {
            if( patternsizes[ i ] <= iPos &&
                cChar == patterns[ i ][ patternsizes[ i ] - 1 ] )
            {
               if( memcmp( buffer + iPos - patternsizes[ i ],
                           patterns[ i ], patternsizes[ i ] ) == 0 )
               {
                  iPaternFound = i + 1;
                  break;
               }
            }
         }
      }
   }
   while( iLen > 0 && iPaternFound == 0 && ( iMax == 0 || iPos < iMax ) );

   if( iPaternFound )
   {
      socket->iCount = iPos;
      if( pResult )
         hb_itemPutNI( pResult, iPos );
      hb_retclen_buffer( buffer, iPos - patternsizes[ iPaternFound - 1 ] );
   }
   else
   {
      if( iLen == 0 )
         socket->iError = HB_INET_ERR_CLOSEDCONN;
      else if( iLen < 0 )
         hb_inetGetError( socket );
      else
      {
         socket->iError = HB_INET_ERR_BUFFOVERRUN;
         iLen = -1;
      }
      if( pResult )
         hb_itemPutNI( pResult, iLen );
      hb_xfree( buffer );
      hb_retc_null();
   }
}
Ejemplo n.º 23
0
static HB_BOOL hb_SetDefaultPrinter( LPCTSTR lpPrinterName )
{
#if ! defined( HB_OS_WIN_CE )
   BOOL bFlag;
   DWORD dwNeeded = 0;
   HANDLE hPrinter = NULL;
   PRINTER_INFO_2 * ppi2 = NULL;
   LPTSTR pBuffer = NULL;

   /* If Windows 95 or 98, use SetPrinter. */
   if( hb_iswin9x() )
   {
      /* Open this printer so you can get information about it. */
      bFlag = OpenPrinter( ( LPTSTR ) lpPrinterName, &hPrinter, NULL );
      if( ! bFlag || ! hPrinter )
         return HB_FALSE;

      /* The first GetPrinter() tells you how big our buffer must
         be to hold ALL of PRINTER_INFO_2. Note that this will
         typically return FALSE. This only means that the buffer (the 3rd
         parameter) was not filled in. You do not want it filled in here. */
      SetLastError( 0 );
      bFlag = GetPrinter( hPrinter, 2, 0, 0, &dwNeeded );
      if( ! bFlag )
      {
         if( ( GetLastError() != ERROR_INSUFFICIENT_BUFFER ) || ( dwNeeded == 0 ) )
         {
            ClosePrinter( hPrinter );
            return HB_FALSE;
         }
      }

      /* Allocate enough space for PRINTER_INFO_2. */
      ppi2 = ( PRINTER_INFO_2 * ) hb_xgrab( dwNeeded );

      /* The second GetPrinter() will fill in all the current information
         so that all you have to do is modify what you are interested in. */
      bFlag = GetPrinter( hPrinter, 2, ( LPBYTE ) ppi2, dwNeeded, &dwNeeded );
      if( ! bFlag )
      {
         ClosePrinter( hPrinter );
         hb_xfree( ppi2 );
         return HB_FALSE;
      }

      /* Set default printer attribute for this printer. */
      ppi2->Attributes |= PRINTER_ATTRIBUTE_DEFAULT;
      bFlag = SetPrinter( hPrinter, 2, ( LPBYTE ) ppi2, 0 );
      if( ! bFlag )
      {
         ClosePrinter( hPrinter );
         hb_xfree( ppi2 );
         return HB_FALSE;
      }

      /* Tell all open programs that this change occurred.
         Allow each program 1 second to handle this message. */
      SendMessageTimeout( HWND_BROADCAST, WM_SETTINGCHANGE, 0L, ( LPARAM ) ( LPCTSTR ) TEXT( "windows" ), SMTO_NORMAL, 1000, NULL );
   }
   /* If Windows NT, use the SetDefaultPrinter API for Windows 2000,
      or WriteProfileString for version 4.0 and earlier. */
   else if( hb_iswinnt() )
   {
      if( hb_iswin2k() ) /* Windows 2000 or later (use explicit call) */
      {
         HMODULE hWinSpool;
         typedef BOOL ( WINAPI * DEFPRINTER )( LPCTSTR ); /* stops warnings */
         DEFPRINTER fnSetDefaultPrinter;

         hWinSpool = hbwapi_LoadLibrarySystem( TEXT( "winspool.drv" ) );
         if( ! hWinSpool )
            return HB_FALSE;

         fnSetDefaultPrinter = ( DEFPRINTER ) HB_WINAPI_GETPROCADDRESST( hWinSpool,
            "SetDefaultPrinter" );

         if( ! fnSetDefaultPrinter )
         {
            FreeLibrary( hWinSpool );
            return HB_FALSE;
         }

         bFlag = ( *fnSetDefaultPrinter )( lpPrinterName );
         FreeLibrary( hWinSpool );
         if( ! bFlag )
            return HB_FALSE;
      }
      else /* NT4.0 or earlier */
      {
         HB_ISIZ nStrLen;

         /* Open this printer so you can get information about it. */
         bFlag = OpenPrinter( ( LPTSTR ) lpPrinterName, &hPrinter, NULL );
         if( ! bFlag || ! hPrinter )
            return HB_FALSE;

         /* The first GetPrinter() tells you how big our buffer must
            be to hold ALL of PRINTER_INFO_2. Note that this will
            typically return FALSE. This only means that the buffer (the 3rd
            parameter) was not filled in. You do not want it filled in here. */
         SetLastError( 0 );
         bFlag = GetPrinter( hPrinter, 2, 0, 0, &dwNeeded );
         if( ! bFlag )
         {
            if( ( GetLastError() != ERROR_INSUFFICIENT_BUFFER ) || ( dwNeeded == 0 ) )
            {
               ClosePrinter( hPrinter );
               return HB_FALSE;
            }
         }

         /* Allocate enough space for PRINTER_INFO_2. */
         ppi2 = ( PRINTER_INFO_2 * ) hb_xgrab( dwNeeded );

         /* The second GetPrinter() fills in all the current
            information. */
         bFlag = GetPrinter( hPrinter, 2, ( LPBYTE ) ppi2, dwNeeded, &dwNeeded );
         if( ( ! bFlag ) || ( ! ppi2->pDriverName ) || ( ! ppi2->pPortName ) )
         {
            ClosePrinter( hPrinter );
            hb_xfree( ppi2 );
            return HB_FALSE;
         }

         nStrLen = hbwapi_tstrlen( lpPrinterName ) +
                   hbwapi_tstrlen( ppi2->pDriverName ) +
                   hbwapi_tstrlen( ppi2->pPortName ) + 2;

         /* Allocate buffer big enough for concatenated string.
            String will be in form "printername,drivername,portname". */
         pBuffer = ( LPTSTR ) hb_xgrab( ( nStrLen + 1 ) * sizeof( TCHAR ) );

         pBuffer[ 0 ] = TEXT( '\0' );

         /* Build string in form "printername,drivername,portname". */
         hbwapi_tstrncat( pBuffer, lpPrinterName, nStrLen );
         hbwapi_tstrncat( pBuffer, TEXT( "," ), nStrLen );
         hbwapi_tstrncat( pBuffer, ppi2->pDriverName, nStrLen );
         hbwapi_tstrncat( pBuffer, TEXT( "," ), nStrLen );
         hbwapi_tstrncat( pBuffer, ppi2->pPortName, nStrLen );

         /* Set the default printer in win.ini and registry. */
         bFlag = WriteProfileString( TEXT( "windows" ), TEXT( "device" ), pBuffer );
         if( ! bFlag )
         {
            ClosePrinter( hPrinter );
            hb_xfree( ppi2 );
            hb_xfree( pBuffer );
            return HB_FALSE;
         }
      }

      /* Tell all open programs that this change occurred.
         Allow each app 1 second to handle this message. */
      SendMessageTimeout( HWND_BROADCAST, WM_SETTINGCHANGE, 0L, 0L, SMTO_NORMAL, 1000, NULL );
   }

   /* Clean up. */
   if( hPrinter )
      ClosePrinter( hPrinter );
   if( ppi2 )
      hb_xfree( ppi2 );
   if( pBuffer )
      hb_xfree( pBuffer );

   return HB_TRUE;
#else
   HB_SYMBOL_UNUSED( lpPrinterName );
   return HB_FALSE;
#endif
}
Ejemplo n.º 24
0
/* helper function for the justxxx() functions */
static void do_justify (int iSwitch)
{

  int iNoRet;

  iNoRet = ct_getref() && ISBYREF( 1 );

  if (ISCHAR (1))
  {

    char *pcString = hb_parc (1);
    size_t sStrLen = hb_parclen (1);
    char cJustChar;
    char *pc, *pcRet;
    size_t sJustOffset;

    if ( sStrLen == 0 )
    {
       if (iNoRet)
       {
          hb_ret();
       }
       else
       {
          hb_retc( "" );
       }
       return;
    }

    if (hb_parclen (2) > 0)
      cJustChar = *(hb_parc (2));
    else if (ISNUM (2))
      cJustChar = (char)( hb_parnl (2) % 256 );
    else
      cJustChar = 0x20;

    pcRet = ( char *)hb_xgrab (sStrLen);

    switch (iSwitch)
    {
      case DO_JUSTIFY_JUSTLEFT:
      {
        pc = pcString;
        sJustOffset = 0;
        while ((*pc == cJustChar) && (pc < pcString+sStrLen))
        {
          sJustOffset++;
          pc++;
        }

        hb_xmemcpy (pcRet, pcString+sJustOffset, sStrLen-sJustOffset);
        for (pc = pcRet+sStrLen-sJustOffset; pc < pcRet+sStrLen; pc++)
        {
          *pc = cJustChar;
        }

      }; break;

      case DO_JUSTIFY_JUSTRIGHT:
      {
        pc = pcString+sStrLen-1;
        sJustOffset = 0;
        while ((*pc == cJustChar) && (pc >= pcString))
        {
          sJustOffset++;
          pc--;
        }

        for (pc = pcRet; pc < pcRet+sJustOffset; pc++)
        {
          *pc = cJustChar;
        }
        hb_xmemcpy (pcRet+sJustOffset, pcString, sStrLen-sJustOffset);

      }; break;

    }

    if (ISBYREF (1))
      hb_storclen (pcRet, sStrLen, 1);

    if (iNoRet)
      hb_ret();
    else
      hb_retclen (pcRet, sStrLen);

    hb_xfree (pcRet);

  }
  else /* ISCHAR (1) */
  {
    PHB_ITEM pSubst = NULL;
    int iArgErrorMode = ct_getargerrormode();
    if (iArgErrorMode != CT_ARGERR_IGNORE)
    {
      pSubst = ct_error_subst ((USHORT)iArgErrorMode, EG_ARG,
                               (iSwitch == DO_JUSTIFY_JUSTLEFT ? CT_ERROR_JUSTLEFT : CT_ERROR_JUSTRIGHT),
                               NULL,
                               (iSwitch == DO_JUSTIFY_JUSTLEFT ? "JUSTLEFT" : "JUSTRIGHT"),
                               0, EF_CANSUBSTITUTE, 2,
                               hb_paramError (1), hb_paramError (2));
    }

    if (pSubst != NULL)
    {
      hb_itemRelease( hb_itemReturnForward( pSubst ) );
    }
    else
    {
      if (iNoRet)
        hb_ret();
      else
        hb_retc ("");
    }
  }

  return;

}
Ejemplo n.º 25
0
static void sk_add( PHB_SETKEY * sk_list_ptr, HB_BOOL bReturn,
                    int iKeyCode, PHB_ITEM pAction, PHB_ITEM pIsActive )
{
   if( iKeyCode )
   {
      PHB_SETKEY sk_list_tmp, sk_list_end;

      if( pIsActive && ! HB_IS_EVALITEM( pIsActive ) )
         pIsActive = NULL;
      if( pAction && ! HB_IS_EVALITEM( pAction ) )
         pAction = NULL;

      sk_list_tmp = sk_findkey( iKeyCode, *sk_list_ptr, &sk_list_end );
      if( sk_list_tmp == NULL )
      {
         if( pAction )
         {
            sk_list_tmp = ( PHB_SETKEY ) hb_xgrab( sizeof( HB_SETKEY ) );
            sk_list_tmp->next = NULL;
            sk_list_tmp->iKeyCode = iKeyCode;
            sk_list_tmp->pAction = hb_itemNew( pAction );
            sk_list_tmp->pIsActive = pIsActive ? hb_itemNew( pIsActive ) : NULL;

            if( sk_list_end == NULL )
               *sk_list_ptr = sk_list_tmp;
            else
               sk_list_end->next = sk_list_tmp;
         }
      }
      else
      {
         /* Return the previous value */

         if( bReturn )
            hb_itemReturn( sk_list_tmp->pAction );

         /* Free the previous values */

         hb_itemRelease( sk_list_tmp->pAction );
         if( sk_list_tmp->pIsActive )
         {
            hb_itemRelease( sk_list_tmp->pIsActive );
         }
         /* Set the new values or free the entry */

         if( pAction )
         {
            sk_list_tmp->pAction = hb_itemNew( pAction );
            sk_list_tmp->pIsActive = pIsActive ? hb_itemNew( pIsActive ) : NULL;
         }
         else
         {
            /* if this is true, then the key found is the first key in the list */
            if( sk_list_end == NULL )
            {
               sk_list_tmp = *sk_list_ptr;
               *sk_list_ptr = sk_list_tmp->next;
               hb_xfree( sk_list_tmp );
            }
            else
            {
               sk_list_end->next = sk_list_tmp->next;
               hb_xfree( sk_list_tmp );
            }
         }
      }
   }
}
Ejemplo n.º 26
0
static void hb_pp_generateRules( FILE * fout, FILE * fword, PHB_PP_STATE pState )
{
   PRESERVEDNAME pTemp;
   int  iDefs = 0, iTrans = 0, iCmds = 0;
   UINT wNum = 0;

   fprintf( fout, "/*\n * $Id: ppgen.c 9869 2012-12-08 18:25:43Z andijahja $\n */\n\n/*\n"
            " * Harbour Project source code:\n"
            " *    Build in preprocessor rules.\n"
            " *\n"
            " * Copyright 2006 Przemyslaw Czerpak <druzus / at / priv.onet.pl>\n"
            " * www - http://www.harbour-project.org\n"
            " *\n"
            " * This file is generated automatically by Harbour preprocessor\n"
            " * and is covered by the same license as Harbour PP\n"
            " */\n\n#define _HB_PP_INTERNAL\n#include \"hbpp.h\"\n\n" );

   fprintf( fword, "/*\n * $Id: ppgen.c 9869 2012-12-08 18:25:43Z andijahja $\n */\n\n/*\n"
            " * Harbour Project source code:\n"
            " *    Word list which should not be used as variable names.\n"
            " *\n"
            " * Copyright 2012 Andi Jahja <*****@*****.**>\n"
            " * www - http://www.harbour-project.org\n"
            " *\n"
            " * This file is generated automatically by Harbour preprocessor\n"
            " * and is covered by the same license as Harbour PP\n"
            "*/\n\n#include \"hbapi.h\"\n"
            "#include \"hbcomp.h\"\n"
            "\nstatic const char * s_szReservedName[] = {\n" );

   if( pState->pDefinitions )
      iDefs = hb_pp_writeRules( fout, pState->pDefinitions, "def" );
   if( pState->pTranslations )
      iTrans = hb_pp_writeRules( fout, pState->pTranslations, "trs" );
   if( pState->pCommands )
      iCmds = hb_pp_writeRules( fout, pState->pCommands, "cmd" );

   fprintf( fout, "\nvoid hb_pp_setStdRules( PHB_PP_STATE pState )\n{\n" );
   hb_pp_generateInitFunc( fout, iDefs, "Definitions", "def" );
   hb_pp_generateInitFunc( fout, iTrans, "Translations", "trs" );
   hb_pp_generateInitFunc( fout, iCmds, "Commands", "cmd" );
   fprintf( fout, "}\n" );

   do
   {
      if ( ! hb_pp_NameFound( ( char * ) s_otherReservedName[ wNum ] ) )
         fprintf( fword, "   \"%s\",\n", ( char* ) s_otherReservedName[ wNum ] );

      ++ wNum;
   } while( wNum < sizeof( s_otherReservedName ) / sizeof( char * ) );

   pTemp = s_PPReservedName;

   do
   {
      fprintf( fword, "   \"%s\"", pTemp->szName );
      hb_xfree( pTemp->szName );
      pTemp = pTemp->pNext;
      hb_xfree( ( void * ) s_PPReservedName );
      s_PPReservedName = pTemp;
      fprintf( fword, s_PPReservedName ? ",\n" : "\n" );
   } while( pTemp );

   fprintf( fword, "};\n\n"
            "#define RESERVED_NAMES sizeof( s_szReservedName ) / sizeof( char * )\n\n"
            "BOOL hb_compReservedPPName( char * szName )\n"
            "{\n"
            "   UINT  wNum   = 0;\n"
            "   int   iFound = 1;\n"
            "   int   iLen   = ( int ) strlen( szName );\n\n"
            "   while( wNum < RESERVED_NAMES && iFound )\n"
            "   {\n"
            "      int u = ( int ) strlen( s_szReservedName[ wNum ] ) ;\n\n"
            "      if ( iLen == u )\n"
            "      {\n"
            "         int i, j = 0;\n\n"
            "         for ( i = 0; i < u; i ++ )\n"
            "         {\n"
            "            if ( szName[ i ] == s_szReservedName[ wNum ] [ i ] )\n"
            "               j ++;\n"
            "            else\n"
            "               break;\n"
            "         }\n\n"
            "         if ( j == u )\n"
            "            iFound = 0;\n"
            "      }\n\n"
            "      ++wNum;\n"
            "   }\n\n"
            "   return ( iFound == 0 );\n"
            "}\n" );
}
Ejemplo n.º 27
0
static void s_fileposClose( PHB_FILE pFilePos )
{
   _PHB_FILE->pFuncs->Close( _PHB_FILE );
   hb_xfree( pFilePos );
}
Ejemplo n.º 28
0
static int hb_pp_generateVerInfo( char * szVerFile, char * szCVSID, char * szCVSDateID, char * szChangeLogID, char * szLastEntry )
{
   int      iResult = 0;
   char *   pszEnv;
   FILE *   fout;

   fout = hb_fopen( szVerFile, "w" );
   if( ! fout )
   {
#if ! defined( __MINGW32CE__ ) && ! defined( HB_OS_WIN_CE )
      perror( szVerFile );
#endif
      iResult = 1;
   }
   else
   {
      fprintf( fout, "/*\n * $Id: ppgen.c 9869 2012-12-08 18:25:43Z andijahja $\n */\n\n/*\n"
               " * Harbour Project source code:\n"
               " *    Version information and build time switches.\n"
               " *\n"
               " * Copyright 2008 Przemyslaw Czerpak <druzus / at / priv.onet.pl>\n"
               " * www - http://www.harbour-project.org\n"
               " *\n"
               " * This file is generated automatically by Harbour preprocessor\n"
               " * and is covered by the same license as Harbour PP\n"
               " */\n\n" );

      fprintf( fout, "\n#ifndef __HBVERBLD_INCLUDED" );
      fprintf( fout, "\n#define __HBVERBLD_INCLUDED\n" );

      if( szCVSID )
         fprintf( fout, "\n#define HB_VER_CVSID\t\t%s\n", szCVSID );

      if( szCVSDateID )
      {
         fprintf( fout, "\n#if defined(HB_VER_BUILDDATE)" );
         fprintf( fout, "\n#undef HB_VER_BUILDDATE" );
         fprintf( fout, "\n#endif\n" );
         fprintf( fout, "#define HB_VER_BUILDDATE\t%s\n", szCVSDateID );
      }

      if( szChangeLogID )
      {
         fprintf( fout, "\n#if defined(HB_VER_CHLCVS)" );
         fprintf( fout, "\n#undef HB_VER_CHLCVS" );
         fprintf( fout, "\n#endif\n" );
         fprintf( fout, "\n#define HB_VER_CHLCVS\t\"%s\"\n", szChangeLogID );
      }

      if( szLastEntry )
      {
         fprintf( fout, "\n#if defined(HB_VER_LENTRY)" );
         fprintf( fout, "\n#undef HB_VER_LENTRY" );
         fprintf( fout, "\n#endif\n" );
         fprintf( fout, "\n#define HB_VER_LENTRY\t\"%s\"\n", szLastEntry );
      }

      pszEnv = hb_getenv( "C_USR" );
      if( pszEnv )
      {
         fprintf( fout, "\n#undef  HB_VER_C_USR" );
         fprintf( fout, "\n#define HB_VER_C_USR\t\"%s\"\n", pszEnv );
         hb_xfree( pszEnv );
      }

      pszEnv = hb_getenv( "L_USR" );
      if( pszEnv )
      {
         fprintf( fout, "\n#undef  HB_VER_L_USR" );
         fprintf( fout, "\n#define HB_VER_L_USR\t\"%s\"\n", pszEnv );
         hb_xfree( pszEnv );
      }

      pszEnv = hb_getenv( "PRG_USR" );
      if( pszEnv )
      {
         fprintf( fout, "\n#undef  HB_VER_PRG_USR" );
         fprintf( fout, "\n#define HB_VER_PRG_USR\t\"%s\"\n", pszEnv );
         hb_xfree( pszEnv );
      }

      fprintf( fout, "\n#endif /* __HBVERBLD_INCLUDED */\n" );

      fclose( fout );
   }

   return iResult;
}
Ejemplo n.º 29
0
/* helper function for the *one functions */
static void do_charonly( int iSwitch )
{
   /* param check */
   if( HB_ISCHAR( 1 ) && HB_ISCHAR( 2 ) )
   {
      const char * pcString = hb_parc( 2 );
      HB_SIZE sStrLen = hb_parclen( 2 );
      const char * pcOnlySet = hb_parc( 1 );
      HB_SIZE sOnlySetLen = hb_parclen( 1 );
      char * pcRet;
      HB_SIZE sRetStrLen = 0;
      int iShift, iBool;
      const char * pcSub, * pc;

      /* check for zero-length strings  */
      switch( iSwitch )
      {
         case DO_CHARONLY_CHARONLY:
         case DO_CHARONLY_WORDONLY:
            if( sStrLen == 0 || sOnlySetLen == 0 )
            {
               hb_retc_null();
               return;
            }
            break;

         case DO_CHARONLY_CHARREM:
         case DO_CHARONLY_WORDREM:
            if( sStrLen == 0 )
            {
               hb_retc_null();
               return;
            }
            if( sOnlySetLen == 0 )
            {
               hb_retclen( pcString, sStrLen );
               return;
            }
            break;
      }

      if( iSwitch == DO_CHARONLY_WORDONLY ||
          iSwitch == DO_CHARONLY_WORDREM )
         iShift = 2;
      else
         iShift = 1;

      pcRet = ( char * ) hb_xgrab( sStrLen );

      for( pcSub = pcString; pcSub < pcString + sStrLen + 1 - iShift; pcSub += iShift )
      {
         pc = ct_at_exact_forward( pcOnlySet, sOnlySetLen, pcSub, iShift, NULL );
         iBool = ( ( pc != NULL ) && ( ( ( pc - pcOnlySet ) % iShift ) == 0 ) );
         if( iBool ? ( iSwitch == DO_CHARONLY_CHARONLY ||
                       iSwitch == DO_CHARONLY_WORDONLY )
                   : ( iSwitch == DO_CHARONLY_CHARREM ||
                       iSwitch == DO_CHARONLY_WORDREM ) )
         {
            for( pc = pcSub; pc < pcSub + iShift; pc++ )
               pcRet[ sRetStrLen++ ] = *pc;
         }
      }

      /* copy last character if string len is odd */
      if( iShift == 2 && sStrLen % 2 == 1 )
         pcRet[ sRetStrLen++ ] = pcString[ sStrLen - 1 ];

      hb_retclen( pcRet, sRetStrLen );
      hb_xfree( pcRet );
   }
   else
   {
      PHB_ITEM pSubst = NULL;
      int iArgErrorMode = ct_getargerrormode(), iError = 0;

      if( iArgErrorMode != CT_ARGERR_IGNORE )
      {
         switch( iSwitch )
         {
            case DO_CHARONLY_CHARONLY:
               iError = CT_ERROR_CHARONLY;
               break;

            case DO_CHARONLY_WORDONLY:
               iError = CT_ERROR_WORDONLY;
               break;

            case DO_CHARONLY_CHARREM:
               iError = CT_ERROR_CHARREM;
               break;

            case DO_CHARONLY_WORDREM:
               iError = CT_ERROR_WORDREM;
               break;
         }
         pSubst = ct_error_subst( ( HB_USHORT ) iArgErrorMode, EG_ARG, iError,
                                  NULL, HB_ERR_FUNCNAME, 0, EF_CANSUBSTITUTE,
                                  HB_ERR_ARGS_BASEPARAMS );
      }

      if( pSubst != NULL )
         hb_itemReturnRelease( pSubst );
      else
         hb_retc_null();
   }
}
Ejemplo n.º 30
0
HB_FHANDLE hb_fsProcessOpen( const char * pszFileName,
                             HB_FHANDLE * phStdin, HB_FHANDLE * phStdout,
                             HB_FHANDLE * phStderr,
                             HB_BOOL fDetach, HB_ULONG * pulPID )
{
   HB_FHANDLE hPipeIn [ 2 ] = { FS_ERROR, FS_ERROR },
              hPipeOut[ 2 ] = { FS_ERROR, FS_ERROR },
              hPipeErr[ 2 ] = { FS_ERROR, FS_ERROR };
   HB_FHANDLE hResult = FS_ERROR;
   HB_ERRCODE errCode;
   HB_BOOL fError = HB_FALSE;

   HB_TRACE( HB_TR_DEBUG, ( "hb_fsProcessOpen(%s, %p, %p, %p, %d, %p)", pszFileName, phStdin, phStdout, phStderr, fDetach, pulPID ) );

   if( phStdin != NULL )
      fError = ! hb_fsPipeCreate( hPipeIn );
   if( ! fError && phStdout != NULL )
      fError = ! hb_fsPipeCreate( hPipeOut );
   if( ! fError && phStderr != NULL )
   {
      if( phStdout == phStderr )
      {
         hPipeErr[ 0 ] = hPipeOut[ 0 ];
         hPipeErr[ 1 ] = hPipeOut[ 1 ];
      }
      else
         fError = ! hb_fsPipeCreate( hPipeErr );
   }

   if( ! fError )
   {
#if defined( HB_OS_WIN )

      PROCESS_INFORMATION pi;
      STARTUPINFO si;
      DWORD dwFlags = 0;
      LPTSTR lpCommand = HB_CHARDUP( pszFileName );

#  if ! defined( HB_OS_WIN_CE )
      if( phStdin != NULL )
         SetHandleInformation( ( HANDLE ) hb_fsGetOsHandle( hPipeIn [ 1 ] ), HANDLE_FLAG_INHERIT, 0 );
      if( phStdout != NULL )
         SetHandleInformation( ( HANDLE ) hb_fsGetOsHandle( hPipeOut[ 0 ] ), HANDLE_FLAG_INHERIT, 0 );
      if( phStderr != NULL && phStdout != phStderr )
         SetHandleInformation( ( HANDLE ) hb_fsGetOsHandle( hPipeErr[ 0 ] ), HANDLE_FLAG_INHERIT, 0 );
#  endif

      memset( &pi, 0, sizeof( pi ) );
      memset( &si, 0, sizeof( si ) );
      si.cb = sizeof( si );
#  ifdef STARTF_USESTDHANDLES
      si.dwFlags = STARTF_USESTDHANDLES;
#  endif
      if( fDetach )
      {
#  ifdef STARTF_USESHOWWINDOW
         si.dwFlags |= STARTF_USESHOWWINDOW;
#  endif
         si.wShowWindow = SW_HIDE;
         si.hStdInput  = ( HANDLE ) hb_fsGetOsHandle( hPipeIn [ 0 ] );
         si.hStdOutput = ( HANDLE ) hb_fsGetOsHandle( hPipeOut[ 1 ] );
         si.hStdError  = ( HANDLE ) hb_fsGetOsHandle( hPipeErr[ 1 ] );
#  ifdef DETACHED_PROCESS
         dwFlags |= DETACHED_PROCESS;
#  endif
      }
      else
      {
         si.hStdInput  = phStdin  ? ( HANDLE ) hb_fsGetOsHandle( hPipeIn [ 0 ] ) : GetStdHandle( STD_INPUT_HANDLE );
         si.hStdOutput = phStdout ? ( HANDLE ) hb_fsGetOsHandle( hPipeOut[ 1 ] ) : GetStdHandle( STD_OUTPUT_HANDLE );
         si.hStdError  = phStderr ? ( HANDLE ) hb_fsGetOsHandle( hPipeErr[ 1 ] ) : GetStdHandle( STD_ERROR_HANDLE );
      }
      fError = ! CreateProcess( NULL,           /* lpAppName */
                                lpCommand,
                                NULL,           /* lpProcessAttr */
                                NULL,           /* lpThreadAttr */
                                TRUE,           /* bInheritHandles */
                                dwFlags,        /* dwCreationFlags */
                                NULL,           /* lpEnvironment */
                                NULL,           /* lpCurrentDirectory */
                                &si,
                                &pi );
      hb_fsSetIOError( ! fError, 0 );
      hb_xfree( lpCommand );
      if( ! fError )
      {
         if( phStdin != NULL )
         {
            *phStdin = ( HB_FHANDLE ) hPipeIn[ 1 ];
            hPipeIn[ 1 ] = FS_ERROR;
         }
         if( phStdout != NULL )
         {
            *phStdout = ( HB_FHANDLE ) hPipeOut[ 0 ];
            hPipeOut[ 0 ] = FS_ERROR;
         }
         if( phStderr != NULL )
         {
            *phStderr = ( HB_FHANDLE ) hPipeErr[ 0 ];
            hPipeErr[ 0 ] = FS_ERROR;
         }
         if( pulPID )
            *pulPID = pi.dwProcessId;
         CloseHandle( pi.hThread );
         hResult = ( HB_FHANDLE ) pi.hProcess;
      }

#elif defined( HB_OS_OS2 )

      HFILE hNull = ( HFILE ) FS_ERROR;
      ULONG ulState = 0;
      APIRET ret = NO_ERROR;
      PID pid = ( PID ) -1;
      PHB_GT pGT;

      if( fDetach && ( ! phStdin || ! phStdout || ! phStderr ) )
      {
         HB_FHANDLE hFile;

         ret = hb_fsOS2DosOpen( "NUL:", &hFile, &ulState, 0,
                                FILE_NORMAL, OPEN_ACCESS_READWRITE,
                                OPEN_ACTION_OPEN_IF_EXISTS );
         if( ret == NO_ERROR )
            hNull = ( HFILE ) hFile;
      }

      if( ret == NO_ERROR && phStdin != NULL )
      {
         ret = DosQueryFHState( hPipeIn[ 1 ], &ulState );
         if( ret == NO_ERROR && ( ulState & OPEN_FLAGS_NOINHERIT ) == 0 )
            ret = DosSetFHState( hPipeIn[ 1 ], ( ulState & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
      }
      if( ret == NO_ERROR && phStdout != NULL )
      {
         ret = DosQueryFHState( hPipeOut[ 0 ], &ulState );
         if( ret == NO_ERROR && ( ulState & OPEN_FLAGS_NOINHERIT ) == 0 )
            ret = DosSetFHState( hPipeOut[ 0 ], ( ulState & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
      }
      if( ret == NO_ERROR && phStderr != NULL && phStdout != phStderr )
      {
         ret = DosQueryFHState( hPipeErr[ 0 ], &ulState );
         if( ret == NO_ERROR && ( ulState & OPEN_FLAGS_NOINHERIT ) == 0 )
            ret = DosSetFHState( hPipeErr[ 0 ], ( ulState & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
      }

      if( ret == NO_ERROR && ( pGT = hb_gt_Base() ) != NULL )
      {
         ULONG ulStateIn, ulStateOut, ulStateErr;
         HFILE hStdIn, hStdErr, hStdOut, hDup;

         ulStateIn = ulStateOut = ulStateErr = OPEN_FLAGS_NOINHERIT;
         hStdIn  = hStdErr = hStdOut = ( HFILE ) FS_ERROR;

         if( ret == NO_ERROR && ( phStdin != NULL || fDetach ) )
         {
            hDup = 0;
            ret = DosDupHandle( hDup, &hStdIn );
            if( ret == NO_ERROR )
            {
               ret = DosQueryFHState( hStdIn, &ulStateIn );
               if( ret == NO_ERROR && ( ulStateIn & OPEN_FLAGS_NOINHERIT ) == 0 )
                  ret = DosSetFHState( hStdIn, ( ulStateIn & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
               if( ret == NO_ERROR )
                  ret = DosDupHandle( phStdin != NULL ? ( HFILE ) hPipeIn[ 0 ] : hNull, &hDup );
            }
         }

         if( ret == NO_ERROR && ( phStdout != NULL || fDetach ) )
         {
            hDup = 1;
            ret = DosDupHandle( hDup, &hStdOut );
            if( ret == NO_ERROR )
            {
               ret = DosQueryFHState( hStdOut, &ulStateOut );
               if( ret == NO_ERROR && ( ulStateOut & OPEN_FLAGS_NOINHERIT ) == 0 )
                  ret = DosSetFHState( hStdOut, ( ulStateOut & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
               if( ret == NO_ERROR )
                  ret = DosDupHandle( phStdout != NULL ? ( HFILE ) hPipeOut[ 1 ] : hNull, &hDup );
            }
         }

         if( ret == NO_ERROR && ( phStderr != NULL || fDetach ) )
         {
            hDup = 2;
            ret = DosDupHandle( hDup, &hStdErr );
            if( ret == NO_ERROR )
            {
               ret = DosQueryFHState( hStdErr, &ulStateErr );
               if( ret == NO_ERROR && ( ulStateErr & OPEN_FLAGS_NOINHERIT ) == 0 )
                  ret = DosSetFHState( hStdErr, ( ulStateErr & 0xFF00 ) | OPEN_FLAGS_NOINHERIT );
               if( ret == NO_ERROR )
                  ret = DosDupHandle( phStderr != NULL ? ( HFILE ) hPipeErr[ 1 ] : hNull, &hDup );
            }
         }

         if( ret == NO_ERROR )
         {
            char * pArgs = hb_buildArgsOS2( pszFileName, &ret );
            char uchLoadError[ CCHMAXPATH ] = { 0 };
            RESULTCODES ChildRC = { 0, 0 };

            if( pArgs )
            {
               ret = DosExecPgm( uchLoadError, sizeof( uchLoadError ),
                                 fDetach ? EXEC_BACKGROUND : EXEC_ASYNCRESULT,
                                 ( PCSZ ) pArgs, NULL /* env */,
                                 &ChildRC,
                                 ( PCSZ ) pArgs );
               if( ret == NO_ERROR )
                  pid = ChildRC.codeTerminate;
               hb_freeArgsOS2( pArgs );
            }
         }

         if( hNull != ( HFILE ) FS_ERROR )
            DosClose( hNull );

         if( hStdIn != ( HFILE ) FS_ERROR )
         {
            hDup = 0;
            DosDupHandle( hStdIn, &hDup );
            DosClose( hStdIn );
            if( ( ulStateIn & OPEN_FLAGS_NOINHERIT ) == 0 )
               DosSetFHState( hDup, ulStateIn & 0xFF00 );
         }
         if( hStdOut != ( HFILE ) FS_ERROR )
         {
            hDup = 1;
            DosDupHandle( hStdOut, &hDup );
            DosClose( hStdOut );
            if( ( ulStateOut & OPEN_FLAGS_NOINHERIT ) == 0 )
               DosSetFHState( hDup, ulStateOut & 0xFF00 );
         }
         if( hStdErr != ( HFILE ) FS_ERROR )
         {
            hDup = 2;
            DosDupHandle( hStdErr, &hDup );
            DosClose( hStdErr );
            if( ( ulStateErr & OPEN_FLAGS_NOINHERIT ) == 0 )
               DosSetFHState( hDup, ulStateErr & 0xFF00 );
         }

         hb_gt_BaseFree( pGT );
      }
      else
      {
         if( hNull != ( HFILE ) FS_ERROR )
            DosClose( hNull );
         if( ret == NO_ERROR )
            ret = ( APIRET ) FS_ERROR;
      }

      fError = ret != NO_ERROR;
      if( ! fError )
      {
         if( phStdin != NULL )
         {
            *phStdin = ( HB_FHANDLE ) hPipeIn[ 1 ];
            hPipeIn[ 1 ] = FS_ERROR;
         }
         if( phStdout != NULL )
         {
            *phStdout = ( HB_FHANDLE ) hPipeOut[ 0 ];
            hPipeOut[ 0 ] = FS_ERROR;
         }
         if( phStderr != NULL )
         {
            *phStderr = ( HB_FHANDLE ) hPipeErr[ 0 ];
            hPipeErr[ 0 ] = FS_ERROR;
         }
         if( pulPID )
            *pulPID = pid;
         hResult = ( HB_FHANDLE ) pid;
      }

      hb_fsSetError( ( HB_ERRCODE ) ret );

#elif defined( HB_OS_UNIX ) && \
      ! defined( HB_OS_VXWORKS ) && ! defined( HB_OS_SYMBIAN )

      char ** argv = hb_buildArgs( pszFileName );
      pid_t pid = fork();

      if( pid == -1 )
         fError = HB_TRUE;
      else if( pid != 0 )    /* parent process */
      {
         if( phStdin != NULL )
         {
            *phStdin = ( HB_FHANDLE ) hPipeIn[ 1 ];
            hPipeIn[ 1 ] = FS_ERROR;
         }
         if( phStdout != NULL )
         {
            *phStdout = ( HB_FHANDLE ) hPipeOut[ 0 ];
            hPipeOut[ 0 ] = FS_ERROR;
         }
         if( phStderr != NULL )
         {
            *phStderr = ( HB_FHANDLE ) hPipeErr[ 0 ];
            hPipeErr[ 0 ] = FS_ERROR;
         }
         if( pulPID )
            *pulPID = pid;
         hResult = ( HB_FHANDLE ) pid;
      }
      else                    /* child process */
      {
         if( fDetach && ( ! phStdin || ! phStdout || ! phStderr ) )
         {
            HB_FHANDLE hNull = open( "/dev/null", O_RDWR );

            if( ! phStdin )
               dup2( hNull, 0 );
            if( ! phStdout )
               dup2( hNull, 1 );
            if( ! phStderr )
               dup2( hNull, 2 );

            if( hNull != FS_ERROR )
               hb_fsClose( hNull );
         }

         if( phStdin != NULL )
         {
            dup2( hPipeIn[ 0 ], 0 );
            hb_fsClose( hPipeIn[ 1 ] );
         }
         if( phStdout != NULL )
         {
            dup2( hPipeOut[ 1 ], 1 );
            hb_fsClose( hPipeOut[ 0 ] );
         }
         if( phStderr != NULL )
         {
            dup2( hPipeErr[ 1 ], 2 );
            if( phStdout != phStderr )
               hb_fsClose( hPipeErr[ 0 ] );
         }

         /* close all non std* handles */
         {
            int iMaxFD, i;
            iMaxFD = sysconf( _SC_OPEN_MAX );
            if( iMaxFD < 3 )
               iMaxFD = 1024;
            for( i = 3; i < iMaxFD; ++i )
               hb_fsClose( i );
         }

         /* reset extended process attributes */
         if( setuid( getuid() ) == -1 ) {}
         if( setgid( getgid() ) == -1 ) {}

         /* execute command */
         {
#  if defined( __WATCOMC__ )
            execvp( argv[ 0 ], ( const char ** ) argv );
#  else
            execvp( argv[ 0 ], argv );
#  endif
            exit( -1 );
         }
      }
      hb_fsSetIOError( ! fError, 0 );

      hb_freeArgs( argv );

#elif defined( HB_OS_OS2 ) || defined( HB_OS_WIN )

      int hStdIn, hStdOut, hStdErr;
      char ** argv;
      int pid;

      hStdIn  = dup( 0 );
      hStdOut = dup( 1 );
      hStdErr = dup( 2 );

      if( fDetach && ( ! phStdin || ! phStdout || ! phStderr ) )
      {
         HB_FHANDLE hNull = open( "NUL:", O_RDWR );

         if( ! phStdin )
            dup2( hNull, 0 );
         if( ! phStdout )
            dup2( hNull, 1 );
         if( ! phStderr )
            dup2( hNull, 2 );

         if( hNull != FS_ERROR )
            close( hNull );
      }

      if( phStdin != NULL )
         dup2( hPipeIn[ 0 ], 0 );
      if( phStdout != NULL )
         dup2( hPipeOut[ 1 ], 1 );
      if( phStderr != NULL )
         dup2( hPipeErr[ 1 ], 2 );

      argv = hb_buildArgs( pszFileName );

#if defined( _MSC_VER ) || defined( __LCC__ ) || \
    defined( __XCC__ ) || defined( __POCC__ )
      pid = _spawnvp( _P_NOWAIT, argv[ 0 ], argv );
#elif defined( __MINGW32__ ) || defined( __WATCOMC__ )
      pid = spawnvp( P_NOWAIT, argv[ 0 ], ( const char * const * ) argv );
#else
      pid = spawnvp( P_NOWAIT, argv[ 0 ], ( char * const * ) argv );
#endif
      hb_freeArgs( argv );

      dup2( hStdIn,  0 );
      close( hStdIn );

      dup2( hStdOut, 1 );
      close( hStdOut );

      dup2( hStdErr, 2 );
      close( hStdErr );

      if( pid < 0 )
         fError = HB_TRUE;
      else if( pid != 0 )    /* parent process */
      {
         if( phStdin != NULL )
         {
            *phStdin = ( HB_FHANDLE ) hPipeIn[ 1 ];
            hPipeIn[ 1 ] = FS_ERROR;
         }
         if( phStdout != NULL )
         {
            *phStdout = ( HB_FHANDLE ) hPipeOut[ 0 ];
            hPipeOut[ 0 ] = FS_ERROR;
         }
         if( phStderr != NULL )
         {
            *phStderr = ( HB_FHANDLE ) hPipeErr[ 0 ];
            hPipeErr[ 0 ] = FS_ERROR;
         }
         if( pulPID )
            *pulPID = pid;
         hResult = ( HB_FHANDLE ) pid;
      }

      hb_fsSetIOError( ! fError, 0 );

#else
      int iTODO; /* TODO: for given platform */

      HB_SYMBOL_UNUSED( pszFileName );
      HB_SYMBOL_UNUSED( fDetach );
      HB_SYMBOL_UNUSED( pulPID );

      hb_fsSetError( ( HB_ERRCODE ) FS_ERROR );
#endif
   }

   errCode = hb_fsError();

   if( hPipeIn[ 0 ] != FS_ERROR )
      hb_fsClose( hPipeIn[ 0 ] );
   if( hPipeIn[ 1 ] != FS_ERROR )
      hb_fsClose( hPipeIn[ 1 ] );
   if( hPipeOut[ 0 ] != FS_ERROR )
      hb_fsClose( hPipeOut[ 0 ] );
   if( hPipeOut[ 1 ] != FS_ERROR )
      hb_fsClose( hPipeOut[ 1 ] );
   if( phStdout != phStderr )
   {
      if( hPipeErr[ 0 ] != FS_ERROR )
         hb_fsClose( hPipeErr[ 0 ] );
      if( hPipeErr[ 1 ] != FS_ERROR )
         hb_fsClose( hPipeErr[ 1 ] );
   }

   hb_fsSetError( errCode );

   return hResult;
}