Example #1
0
bool EncryptedStore::openWrite(const QString& name)
{
    Q_D(KOdfStore);
    if (bad())
        return false;
    if (isToBeEncrypted(name)) {
        // Encrypted files will be compressed by this class and should be stored in the zip as not compressed
        m_pZip->setCompression(KZip::NoCompression);
    } else {
        m_pZip->setCompression(KZip::DeflateCompression);
    }
    d->stream = new QBuffer();
    (static_cast< QBuffer* >(d->stream))->open(QIODevice::WriteOnly);
    if (name == MANIFEST_FILE)
        return true;
    return m_pZip->prepareWriting(name, "", "", 0);
}
Example #2
0
bool Foam::Istream::getBack(token& t)
{
    if (bad())
    {
        FatalIOErrorInFunction(*this)
            << "Attempt to get back from bad stream"
            << exit(FatalIOError);
    }
    else if (putBack_)
    {
        t = putBackToken_;
        putBack_ = false;
        return true;
    }

    return false;
}
Example #3
0
void control_transfer(usb_dev_handle *dev, const char *pquestion) {
    int r,i;

    char question[reqIntLen];
    
    memcpy(question, pquestion, sizeof question);

    r = usb_control_msg(dev, 0x21, 0x09, 0x0200, 0x01, (char *) question, reqIntLen, timeout);
    if( r < 0 )
    {
          perror("USB control write"); bad("USB write failed"); 
    }

    if(debug) {
        for (i=0;i<reqIntLen; i++) printf("%02x ",question[i]  & 0xFF);
        printf("\n");
    }
}
Example #4
0
void interrupt_read(usb_dev_handle *dev) {
 
    int r,i;
    unsigned char answer[reqIntLen];
    bzero(answer, reqIntLen);
    
    r = usb_interrupt_read(dev, 0x82, answer, reqIntLen, timeout);
    if( r != reqIntLen )
    {
          perror("USB interrupt read"); bad("USB read failed"); 
    }

    if(debug) {
       for (i=0;i<reqIntLen; i++) printf("%02x ",answer[i]  & 0xFF);
    
       printf("\n");
    }
}
Example #5
0
float interrupt_read_temperature(usb_dev_handle *dev) {
  int r,i;
  unsigned char answer[reqIntLen];
  bzero(answer, reqIntLen);

  r = usb_interrupt_read(dev, 0x82, (char*)answer, reqIntLen, timeout);
  if (r != reqIntLen) {
    perror("USB interrupt read3"); bad("USB read failed");
  }

  if (debug) {
    for (i=0; i < reqIntLen; i++) {
      printf("%02x ", answer[i] & 0xFF);
    }
    printf("\n");
  }

  /* Temperature in C is a 16-bit signed fixed-point number, big-endian */
  return (float)(signed char)answer[tempOffset] + answer[tempOffset+1] / 256.0f;
}
// Keep the put back token
void Istream::putBack(const token& t)
{
    if (bad())
    {
        FatalIOErrorIn("void Istream::putBack(const token& t)", *this)
            << "Attempt to put back onto bad stream"
            << exit(FatalIOError);
    }
    else if (putBack_)
    {
        FatalIOErrorIn("void Istream::putBack(const token& t)", *this)
            << "Attempt to put back another token"
            << exit(FatalIOError);
    }
    else
    {
        putBackToken_ = t;
        putBack_ = true;
    }
}
Example #7
0
void example_result()
{
    auto result01 = open_for_reading("/dev/null");
    assert(result01.ok());
    assert(result01.value() != nullptr);
    assert(fclose(result01.take()) == 0);
    (void) result01;
    
    auto result02 = open_for_reading("/dev/mem");
    assert(!result02.ok());
    assert(result02.bad());
    assert(result02.error() == EACCES);
    (void) result02;
    
    assert(divide(1, 1).ok());
    assert(divide(1, 1).value() == 1);
    assert(divide(1, 1).take() == 1);
    assert(!divide(1, 0).ok());
    assert(divide(1, 0).take_or(1) == 1);
    assert(divide(1, 0).error() == "division by zero");
}
// Set t to the put back token if there is one and return true, 
// otherwise return false
bool Istream::getBack(token& t)
{
    if (bad())
    {
        FatalIOErrorIn("void Istream::getBack(token& t)", *this)
            << "Attempt to get back from bad stream"
            << exit(FatalIOError);

        return false;
    }
    else if (putBack_)
    {
        t = putBackToken_;
        putBack_ = false;
        return true;
    }
    else
    {
        return false;
    }
}
Example #9
0
void interrupt_transfer(usb_dev_handle *dev) {
 
    int r,i;
    char answer[reqIntLen];
    char question[reqIntLen];
    for (i=0;i<reqIntLen; i++) question[i]=i;
    r = usb_interrupt_write(dev, endpoint_Int_out, question, reqIntLen, timeout);
    if( r < 0 )
    {
          r = usb_interrupt_read(dev, endpoint_Int_in, answer, reqIntLen, timeout);
    }
    if( r != reqIntLen )
    {
          perror("USB interrupt read"); bad("USB read failed"); 
    }

    if(debug) {
       for (i=0;i<reqIntLen; i++) printf("%i, %i, \n",question[i],answer[i]);
    }
 
    usb_release_interface(dev, 0);
}
void VESPERS2DScanConfigurationView::axesAcceptable()
{
	QPalette good(this->palette());
	QPalette bad(good);
	bad.setColor(QPalette::Base, Qt::red);

	AMScanAxisRegion *region = configuration_->scanAxisAt(0)->regionAt(0);

	if (double(region->regionStart()) < double(region->regionEnd()) && double(region->regionStep()) > 0)
		hStep_->setPalette(good);

	else
		hStep_->setPalette(bad);

	region = configuration_->scanAxisAt(1)->regionAt(0);

	if (double(region->regionStart()) < double(region->regionEnd()) && double(region->regionStep()) > 0)
		vStep_->setPalette(good);

	else
		vStep_->setPalette(bad);
}
Example #11
0
int
sdbm_delete(register DBM *db, datum key)
{
	if (db == NULL || bad(key))
		return errno = EINVAL, -1;
	if (sdbm_rdonly(db))
		return errno = EPERM, -1;

	if (getpage(db, exhash(key))) {
		if (!delpair(db->pagbuf, key))
			return -1;
/*
 * update the page file
 */
		if (lseek(db->pagf, OFF_PAG(db->pagbno), SEEK_SET) < 0
		    || write(db->pagf, db->pagbuf, PBLKSIZ) < 0)
			return ioerr(db), -1;

		return 0;
	}

	return ioerr(db), -1;
}
Example #12
0
void interrupt_read_temperatura(usb_dev_handle *dev, float *tempC) {
 
    int r,i, temperature;
    unsigned char answer[reqIntLen];
    bzero(answer, reqIntLen);
    
    r = usb_interrupt_read(dev, 0x82, answer, reqIntLen, timeout);
    if( r != reqIntLen )
    {
          perror("USB interrupt read"); bad("USB read failed"); 
    }


    if(debug) {
      for (i=0;i<reqIntLen; i++) printf("%02x ",answer[i]  & 0xFF);
    
      printf("\n");
    }
    
    temperature = (answer[3] & 0xFF) + (answer[2] << 8);
    temperature += calibration;
    *tempC = temperature * (125.0 / 32000.0);

}
Example #13
0
 bool good() const {
     return !bad();
 }
Example #14
0
int main(int argc, char * argv[])
{
  bad();
  return 0;
}
namespace lifetime {
  constexpr int &&id(int &&n) { return static_cast<int&&>(n); }
  constexpr int &&dead() { return id(0); } // expected-note {{temporary created here}}
  constexpr int bad() { int &&n = dead(); n = 1; return n; } // expected-note {{assignment to temporary whose lifetime has ended}}
  static_assert(bad(), ""); // expected-error {{constant expression}} expected-note {{in call}}
}
Example #16
0
int auth_userdb_passwd(const char *service,
		      const char *uid,
		      const char *opwd_buf,
		      const char *npwd_buf)
{
	char *opwd;
	char *npwd;
	int rc;
	int hmac_flag=0;

	if (bad(uid) ||
	    bad(service) ||
	    bad(opwd_buf) ||
	    bad(npwd_buf) ||
	    strchr(uid, '/'))
	{
		errno=EPERM;
		return (1);
	}

#if HAVE_HMACLIB

	if (strncmp(service, "hmac-", 5) == 0)
	{
		opwd=hmacpw(opwd_buf, service+5);
		npwd=hmacpw(npwd_buf, service+5);

		if (!opwd)
		{
			if (npwd)
				free(npwd);
			errno=EPERM;
			return (1);
		}
		hmac_flag=1;
	}
	else
#endif
	{
		opwd=strdup(opwd_buf);
		if (!opwd)
		{
			errno=EPERM;
			return (1);
		}

		npwd=userdb_mkmd5pw(npwd_buf);
		if (!npwd || !(npwd=strdup(npwd)))
		{
			free(opwd);
			errno=EPERM;
			return (1);
		}
	}


	rc=dochangepwd1(service, uid, opwd, npwd, hmac_flag);

	free(opwd);
	free(npwd);
	return (rc);
}
Example #17
0
void test_result()
{
    auto result01 = rr::result<bool, int>(0);
    assert(!result01.ok());
    assert(result01.bad());
    assert(result01.ok() != result01.bad());
    assert(result01.error() == 0);
    assert(result01.take_or(true));
    (void) result01;
    
    rr::result<std::string, bool> result02 = false;
    assert(result02.bad());
    assert(!result02.ok());
    assert(result02.ok() != result02.bad());
    assert(result02.error() == false);
    assert(result02.take_or("Hello, World!") == "Hello, World!");
    (void) result02;

    auto result03 = rr::result<unsigned int, int>(0U);
    assert(result03.ok());
    assert(result03.value() == 0);
    assert(result03.take_or(42) == 0);
    result03 = 0U;
    result03.value() = 42;
    assert(result03.value() == 42);
    (void) result03;
    
    auto result04 = rr::result<int, std::string>("Hello, World!");
    assert(result04.bad());
    assert(result04.error() == "Hello, World!");
    (void) result04;
    
    auto result05 = rr::result<std::string, int>("Hello, World!");
    assert(result05.ok());
    assert(result05.value() == "Hello, World!");
    assert(result05.take() == "Hello, World!");
    
    result05 = "Goodbye, World!";
    assert(result05.ok());
    assert(result05.value() == "Goodbye, World!");
    
    result05 = EINVAL;
    assert(!result05.ok());
    assert(result05.bad());
    assert(result05.error() == EINVAL);
    (void) result05;
    
    auto result06 = rr::result<std::vector<std::string>, int>(0);
    result06 = std::vector<std::string>({ "A", "B", "C", "D" });
    assert(result06.ok());
    assert(!result06.bad());
    assert(result06.value()[0] == "A");
    assert(result06.value()[1] == "B");
    assert(result06.value()[2] == "C");
    assert(result06.value()[3] == "D");
    assert(result06.value().size() == 4);
    
    auto v1 = result06.take();
    assert(v1[0] == "A");
    assert(v1[1] == "B");
    assert(v1[2] == "C");
    assert(v1[3] == "D");
    assert(v1.size() == 4);
    
    result06 = EINVAL;
    assert(result06.take_or(v1)[3] == "D");
    assert(result06.take_or(std::move(v1))[3] == "D");
    assert(result06.bad());
    
    result06 = std::vector<std::string>({ "X", "Y", "Z" });
    assert(result06.value()[0] == "X");
    assert(result06.value()[1] == "Y");
    assert(result06.value()[2] == "Z");
    assert(result06.value().size() == 3);
    assert(result06.ok());

    auto result07 = std::move(result06);
    assert(result07.ok());
    (void) result06;
    auto result08 = result07;
    assert(result07.ok());
    assert(result08.ok());
    (void) result07;
    
    rr::result<std::vector<std::string>, double> result09 = result08.take();
    assert(result09.ok());
    assert(result09.value()[0] == "X");
    assert(result09.value()[1] == "Y");
    assert(result09.value()[2] == "Z");
    assert(result09.value().size() == 3);
    (void) result09;
}
Example #18
0
        void run() {
            good("A");
            good("\xC2\xA2"); // cent: ¢
            good("\xE2\x82\xAC"); // euro: €
            good("\xF0\x9D\x90\x80"); // Blackboard A: 𝐀

            //abrupt end
            bad("\xC2");
            bad("\xE2\x82");
            bad("\xF0\x9D\x90");
            bad("\xC2 ");
            bad("\xE2\x82 ");
            bad("\xF0\x9D\x90 ");

            //too long
            bad("\xF8\x80\x80\x80\x80");
            bad("\xFC\x80\x80\x80\x80\x80");
            bad("\xFE\x80\x80\x80\x80\x80\x80");
            bad("\xFF\x80\x80\x80\x80\x80\x80\x80");

            bad("\xF5\x80\x80\x80"); // U+140000 > U+10FFFF
            bad("\x80"); //cant start with continuation byte
            bad("\xC0\x80"); // 2-byte version of ASCII NUL
#undef good
#undef bad
        }
Example #19
0
 void range(int value,int lo,int hi,const char *what) {
   if (value<lo || value>=hi) {
     CkPrintf("ERROR! %s: %d is out of range (%d,%d)!\n",what,value,lo,hi);
     bad("Internal FEM data structure corruption! (out of range)\n");
   }
 }
 void insert_line(ll m, ll b) {
   auto y = insert({ m, b });
   y->succ = [=] { return next(y) == end() ? 0 : &*next(y); };
   if (bad(y)) { erase(y); return; }
   while (next(y) != end() && bad(next(y))) erase(next(y));
   while (y != begin() && bad(prev(y))) erase(prev(y)); }
// set the put pointer's position
ostream _FAR & ostream::seekp(streamoff off, ios::seek_dir dir)
{
    if( bad()  ||  bp->seekoff(off, dir, ios::out) == EOF )
        setstate(ios::failbit);
    return *this;
}
Example #22
0
bool EncryptedStore::openRead(const QString& name)
{
    Q_D(KOdfStore);
    if (bad())
        return false;

    const KArchiveEntry* fileArchiveEntry = m_pZip->directory()->entry(name);
    if (!fileArchiveEntry) {
        return false;
    }
    if (fileArchiveEntry->isDirectory()) {
        kWarning(30002) << name << " is a directory!";
        return false;
    }
    const KZipFileEntry* fileZipEntry = static_cast<const KZipFileEntry*>(fileArchiveEntry);

    delete d->stream;
    d->stream = fileZipEntry->createDevice();
    d->size = fileZipEntry->size();
    if (m_encryptionData.contains(name)) {
        // This file is encrypted, do some decryption first
        if (m_bPasswordDeclined) {
            // The user has already declined to give a password
            // Open the file as empty
            d->stream->close();
            delete d->stream;
            d->stream = new QBuffer();
            d->stream->open(QIODevice::ReadOnly);
            d->size = 0;
            return true;
        }
        QCA::SecureArray encryptedFile(d->stream->readAll());
        if (encryptedFile.size() != d->size) {
            // Read error detected
            d->stream->close();
            delete d->stream;
            d->stream = NULL;
            kWarning(30002) << "read error";
            return false;
        }
        d->stream->close();
        delete d->stream;
        d->stream = NULL;
        KoEncryptedStore_EncryptionData encData = m_encryptionData.value(name);
        QCA::SecureArray decrypted;

        // If we don't have a password yet, try and find one
        if (m_password.isEmpty()) {
            findPasswordInKWallet();
        }

        while (true) {
            QByteArray pass;
            QCA::SecureArray password;
            bool keepPass = false;
            // I already have a password! Let's test it. If it's not good, we can dump it, anyway.
            if (!m_password.isEmpty()) {
                password = m_password;
                m_password = QCA::SecureArray();
            } else {
                if (!m_filename.isNull())
                    keepPass = false;
                QPointer<KPasswordDialog> dlg = new KPasswordDialog(d->window , 
				keepPass ? KPasswordDialog::ShowKeepPassword : static_cast<KPasswordDialog::KPasswordDialogFlags>(0));
                dlg->setPrompt(i18n("Please enter the password to open this file."));
                if (! dlg->exec()) {
                    m_bPasswordDeclined = true;
                    d->stream = new QBuffer();
                    d->stream->open(QIODevice::ReadOnly);
                    d->size = 0;
		    delete dlg;
                    return true;
                }
		if (dlg) {
                    password = QCA::SecureArray(dlg->password().toUtf8());
                    if (keepPass)
                        keepPass = dlg->keepPassword();
                    if (password.isEmpty()) {
		        delete dlg;
                        continue;
                    }
		}
		delete dlg;
            }

            decrypted = decryptFile(encryptedFile, encData, password);
            if (decrypted.isEmpty()) {
                kError(30002) << "empty decrypted file" << endl;
                return false;
            }

            if (!encData.checksum.isEmpty()) {
                QCA::SecureArray checksum;
                if (encData.checksumShort && decrypted.size() > 1024) {
                    // TODO: Eww!!!! I don't want to convert via insecure arrays to get the first 1K characters of a secure array <- fix QCA?
                    checksum = QCA::Hash("sha1").hash(QCA::SecureArray(decrypted.toByteArray().left(1024)));
                } else {
                    checksum = QCA::Hash("sha1").hash(decrypted);
                }
                if (checksum != encData.checksum) {
                    continue;
                }
            }

            // The password passed all possible tests, so let's accept it
            m_password = password;
            m_bPasswordUsed = true;

            if (keepPass) {
                savePasswordInKWallet();
            }

            break;
        }

        QByteArray *resultArray = new QByteArray(decrypted.toByteArray());
        QIODevice *resultDevice = KFilterDev::device(new QBuffer(resultArray, NULL), "application/x-gzip");
        if (!resultDevice) {
            delete resultArray;
            return false;
        }
        static_cast<KFilterDev*>(resultDevice)->setSkipHeaders();
        d->stream = resultDevice;
        d->size = encData.filesize;
    }
    d->stream->open(QIODevice::ReadOnly);

    return true;
}
Example #23
0
bool wxFBIPC::VerifySingleInstance( const wxString& file, bool switchTo )
{
    // Possible send a message to the running instance through this string later, for now it is left empty
    wxString expression = wxEmptyString;

    // Make path absolute
    wxFileName path( file );
    if ( !path.IsOk() )
    {
        wxLogError( wxT("This path is invalid: %s"), file.c_str() );
        return false;
    }

    if ( !path.IsAbsolute() )
    {
        if ( !path.MakeAbsolute() )
        {
            wxLogError( wxT("Could not make path absolute: %s"), file.c_str() );
            return false;
        }
    }

    // Check for single instance

    // Create lockfile/mutex name
    wxString name = wxString::Format( wxT("wxFormBuilder-%s-%s"), wxGetUserId().c_str(), path.GetFullPath().c_str() );

    // Get forbidden characters
    wxString forbidden = wxFileName::GetForbiddenChars();

    // Repace forbidded characters
    for ( size_t c = 0; c < forbidden.Length(); ++c )
    {
        wxString bad( forbidden.GetChar( c ) );
        name.Replace( bad.c_str(), wxT("_") );
    }

    // Paths are not case sensitive in windows
#ifdef __WXMSW__
    name = name.MakeLower();
#endif

    // GetForbiddenChars is missing "/" in unix. Prepend '.' to make lockfiles hidden
#ifndef __WXMSW__
    name.Replace( wxT("/"), wxT("_") );
    name.Prepend( wxT(".") );
#endif

    // Check to see if I already have a server with this name - if so, no need to make another!
    if ( m_server.get() )
    {
        if ( m_server->m_name == name )
        {
            return true;
        }
    }

    std::auto_ptr< wxSingleInstanceChecker > checker;
    {
        // Suspend logging, because error messages here are not useful
#ifndef __WXFB_DEBUG__
        wxLogNull stopLogging;
#endif
        checker.reset( new wxSingleInstanceChecker( name ) );
    }

    if ( !checker->IsAnotherRunning() )
    {
        // This is the first instance of this project, so setup a server and save the single instance checker
        if ( CreateServer( name ) )
        {
            m_checker = checker;
            return true;
        }
        else
        {
            return false;
        }
    }
    else if ( switchTo )
    {
        // Suspend logging, because error messages here are not useful
#ifndef __WXFB_DEBUG__
        wxLogNull stopLogging;
#endif

        // There is another app, so connect and send the expression

        // Cannot have a client and a server at the same time, due to the implementation of wxTCPServer and wxTCPClient,
        // so temporarily drop the server if there is one
        bool hadServer = false;
        wxString oldName;
        if ( m_server.get() != NULL )
        {
            oldName = m_server->m_name;
            m_server.reset();
            hadServer = true;
        }

        // Create the client
        std::auto_ptr< AppClient > client( new AppClient );

        // Create the connection
        std::auto_ptr< wxConnectionBase > connection;
#ifdef __WXMSW__
        connection.reset( client->MakeConnection( wxT("localhost"), name, name ) );
#else
        bool connected = false;
        for ( int i = m_port; i < m_port + 20; ++i )
        {
#if wxVERSION_NUMBER < 2900
            wxString nameWithPort = wxString::Format( wxT("%i%s"), i, name.c_str() );
            connection.reset( client->MakeConnection( wxT("127.0.0.1"), nameWithPort, name ) );
#else
            wxString sPort = wxString::Format( "%i", i );
            connection.reset( client->MakeConnection( "localhost", sPort, name ) );
#endif
            if ( NULL != connection.get() )
            {
                connected = true;
                wxChar* pid = (wxChar*)connection->Request( wxT("PID"), NULL );
                if ( NULL != pid )
                {
                    wxLogStatus( wxT("%s already open in process %s"), file.c_str(), pid );
                }
                break;
            }
        }
        if ( !connected )
        {
            wxLogError( wxT("There is a lockfile named '%s', but unable to make a connection to that instance."), name.c_str() );
        }
#endif

        // Drop the connection and client
        connection.reset();
        client.reset();

        // Create the server again, if necessary
        if ( hadServer )
        {
            CreateServer( oldName );
        }
    }
    return false;
}
Example #24
0
 va_dcl
#else
	(char *s, const char *fmt, ...)
#endif
{
	char *s0;
	va_list ap;
	long L, *Lp;
	int i, *ip, rc = 0;

#ifdef KR_headers
	char *fmt, *s;
	va_start(ap);
	s = va_arg(ap, char*);
	fmt = va_arg(ap, char*);
#else
	va_start(ap, fmt);
#endif
	for(;;) {
		for(;;) {
			switch(i = *(unsigned char *)fmt++) {
				case 0:
					goto done;
				case '%':
					break;
				default:
					if (i <= ' ') {
						while(*s <= ' ')
							if (!*s++)
								return rc;
						}
					else if (*s++ != i)
						return rc;
					continue;
				}
			break;
			}
		switch(*fmt++) {
			case 'l':
				if (*fmt != 'd')
					bad(fmt);
				fmt++;
				Lp = va_arg(ap, long*);
				L = strtol(s0 = s, &s, 10);
				if (s > s0) {
					rc++;
					*Lp = L;
					continue;
					}
				return rc;
			case 'd':
				ip = va_arg(ap, int*);
				L = strtol(s0 = s, &s, 10);
				if (s > s0) {
					rc++;
					*ip = (int)L;
					continue;
					}
				return rc;
			default:
				bad(fmt);
			}
		}
 done:
	return rc;
	}
Example #25
0
 va_dcl
#else
	(char *outbuf, const char *fmt, ...)
#endif
{
	char *ob0, *s;
	char buf[32];
	va_list ap;
	long i, j;
	int rc = 0;

#ifdef KR_headers
	char *outbuf, *fmt;
	va_start(ap);
	outbuf = va_arg(ap, char*);
	fmt = va_arg(ap, char*);
#else
	va_start(ap, fmt);
#endif
	ob0 = outbuf;
	for(;;) {
		for(;;) {
			switch(i = *fmt++) {
				case 0:
					goto done;
				case '%':
					break;
				default:
					put(i);
					continue;
				}
			break;
			}
		switch(*fmt++) {
			case 'c':
				i = va_arg(ap, int);
				put(i);
				continue;
			case 'l':
				if (*fmt != 'd')
					bad(fmt);
				fmt++;
				i = va_arg(ap, long);
				goto have_i;
			case 'd':
				i = va_arg(ap, int);
 have_i:
				if (i < 0) {
					put('-');
					i = -i;
					}
				s = buf;
				do {
					j = i / 10;
					*s++ = i - 10*j + '0';
					}
					while(i = j);
				do {
					i = *--s;
					put(i);
					}
					while(s > buf);
				continue;
			case 's':
				s = va_arg(ap, char*);
 have_s:
				while(i = *s++)
					{ put(i); }
				continue;
			default:
				bad(fmt);
			}
		}
 done:
	*outbuf = 0;
	return outbuf - ob0;
	}
int main(void) {
    bad();
    return 0;
}
Example #27
0
void InitOffsets()
{
  int j;
  int argid;
  INSTR_InstrCategory instrCat;
  INSTR_OperandType* opType;

  j=1;
  argid=0;
  instrCat = INSTR_instrType(call);
  opType = INSTR_operandTypes(instrCat);
  do{
    switch(opType[argid])
    {
      case INSTR_P:
        j++;
        break;
          
      case INSTR_WP:
        j+=sizeof(Word);
        break;
          
      case INSTR_I1:
        callOffsets[CALL][ADDR][ARITY]=j++;
        break;

      case INSTR_L:
        callOffsets[CALL][ADDR][LABEL]=j;
        j+=sizeof(CodeInd);
        break;
      default:
        bad("Internal Error: in code.c InitOffsets():A\n");
        EM_THROW(LK_LinkError);
    }
    argid++;
  }while(opType[argid]!=INSTR_X);
  
  j=1;
  argid=0;
  instrCat = INSTR_instrType(execute);
  opType = INSTR_operandTypes(instrCat);
  do{
    switch(opType[argid])
    {
      case INSTR_P:
        j++;
        break;
          
      case INSTR_WP:
        j+=sizeof(Word);
        break;
 
      case INSTR_L:
        callOffsets[EXECUTE][ADDR][LABEL]=j;
        j+=sizeof(CodeInd);
        break;
      default:
        bad("Internal Error: in code.c InitOffsets():B\n");
        EM_THROW(LK_LinkError);
    }
    argid++;
  }while(opType[argid]!=INSTR_X);
  
  j=1;
  argid=0;
  instrCat = INSTR_instrType(call_name);
  opType = INSTR_operandTypes(instrCat);
  do{
    switch(opType[argid])
    {
      case INSTR_P:
        j++;
        break;
          
      case INSTR_WP:
        j+=sizeof(Word);
        break;
          
      case INSTR_I1:
        callOffsets[CALL][NAME][ARITY]=j++;
        break;
        
      case INSTR_C:
        callOffsets[CALL][NAME][LABEL]=j;
        j+=sizeof(ConstInd);
        break;
      default:
        bad("Internal Error: in code.c InitOffsets():C %x\n",opType[argid]);
        EM_THROW(LK_LinkError);
    }
    argid++;
  }while(opType[argid]!=INSTR_X);
  
  j=1;
  argid=0;
  instrCat = INSTR_instrType(execute_name);
  opType = INSTR_operandTypes(instrCat);
  do{
    switch(opType[argid])
    {
      case INSTR_P:
        j++;
        break;
          
      case INSTR_WP:
        j+=sizeof(Word);
        break;
          
      case INSTR_C:
        callOffsets[EXECUTE][NAME][LABEL]=j;
        j+=sizeof(ConstInd);
        break;
      default:
        bad("Internal Error: in code.c InitOffsets():D\n");
        EM_THROW(LK_LinkError);
    }
    argid++;
  }while(opType[argid]!=INSTR_X);
}
Example #28
0
void WriteCode(int fd)
{
  Word i,j;
  Word size=LK_VECTOR_Size(&Code);
  char* code=(char *)LK_VECTOR_GetPtr(&Code,0);
  Byte opcode=-1;
  INSTR_InstrCategory instrCat=INSTR_CAT_X;
  INSTR_OperandType* opType=NULL;
  int argid=0;

  debug("Writing 0x%lx bytes of instructions at %lx.\n",size,lseek(fd,0,SEEK_CUR));
  
  for(i=0;i<size;)
  {
    j=i;
    
    opcode=code[j++];
    instrCat=INSTR_instrType(opcode);
    opType=INSTR_operandTypes(instrCat);
    argid=-1;
    LK_FILE_PUT1(fd,opcode);
    debug("\t%lx:%lx:[%x]%s ",lseek(fd,0,SEEK_CUR)-1,i,opcode,INSTR_instrName(opcode));
    do{
      argid++;
      switch(opType[argid])
      {
        case INSTR_P:
          j++;
          break;
          
        case INSTR_WP:
          j+=sizeof(Word);
          break;
        
        case INSTR_SEG:
          debug("SEG %d ",*(Byte*)(code+j));
        case INSTR_R:
        case INSTR_E:
        case INSTR_N:
        case INSTR_I1:
        case INSTR_CE:
          LK_FILE_PUT1(fd,*(Byte*)(code+j));
          j+=sizeof(Byte);
          break;

//         case INSTR_I2:
//           PUT2(*(TwoBytes*)(code+j));
//           j+=sizeof(TwoBytes);
//           break;
          
        case INSTR_C:
          PutConstInd(fd,UnPackConstInd(*(TwoBytes*)(code+j)));
          j+=sizeof(TwoBytes);
          break;
          
        case INSTR_K:
          PutKindInd(fd,UnPackKindInd(*(TwoBytes*)(code+j)));
          j+=sizeof(TwoBytes);
          break;
          
        case INSTR_MT:
          PutImportTabInd(fd,*(ImportTabInd*)(code+j));
          j+=sizeof(ImportTabInd);
          break;
          
        case INSTR_IT:
          PutImplGoalInd(fd,*(ImplGoalInd*)(code+j));
          j+=sizeof(ImplGoalInd);
          break;
          
        case INSTR_HT:
          PutHashTabInd(fd,*(HashTabInd*)(code+j));
          j+=sizeof(HashTabInd);
          break;
          
        case INSTR_BVT:
          PutBvrTabInd(fd,*(BvrTabInd*)(code+j));
          j+=sizeof(BvrTabInd);
          break;
          
        case INSTR_S:
          PutStringInd(fd,*(StringInd*)(code+j));
          j+=sizeof(StringInd);
          break;
        
        case INSTR_L:
          debug("L(%lx) ",*(CodeInd*)(code+j));
          PutCodeInd(fd,*(CodeInd*)(code+j));
          j+=sizeof(CodeInd);
          break;
          
        case INSTR_I:
          LK_FILE_PUT4(fd,*(INT4*)(code+j));
          j+=sizeof(INT4);
          break;

        case INSTR_F:
          PutFloat(fd,*(INT4*)(code+j));
          j+=sizeof(INT4);
          break;
          
        case INSTR_X:
          break;
        default:
          bad("\nUnknown Operand Type %d\n",opType[argid]);
          EM_THROW(LK_LinkError);
          break;     /* null instruction */
      }
    }
    while(opType[argid]!=INSTR_X);
    debug("\n");
    i+=INSTR_instrSize(opcode);
  }
}
Example #29
0
void LoadCode(int fd, struct Module_st* CMData)
{
  Word i,j;
  Word offset=CMData->CodeOffset;
  Word size=CMData->CodeSize;
  Byte* code;
  Byte opcode;
  ConstInd tmpIndex;
  INSTR_InstrCategory instrCat;
  INSTR_OperandType* opType;
  int argid=0;

  if(size<=0){
    debug("No code for current module.\n");
    return;
  }
  debug("Loading 0x%lx bytes of code at %lx to offset 0x%lx.\n",size,lseek(fd,0,SEEK_CUR),offset);
  code=(Byte*)LK_VECTOR_GetPtr(&Code,offset);
  debug("After get\n");
  
  opcode=-1;
  instrCat=INSTR_CAT_X;
  opType=NULL;
  
  for(i=0;i<size;)
  {
    j=i;
    opcode=code[j++]=LK_FILE_GET1(fd);
    debug("\t%lx:%lx:[%x]%s\t",lseek(fd,0,SEEK_CUR)-1,i,opcode,INSTR_instrName(opcode));
    if(opcode==call_link_only)
    {
      code[j]=LK_FILE_GET1(fd);
      tmpIndex=GetConstInd(fd,CMData);
      PushCall(CMData->Pit,tmpIndex,offset+i,code[j]);
      i += INSTR_instrSize(opcode);
      
      continue;
    }
    else if(opcode==execute_link_only)
    {
      tmpIndex=GetConstInd(fd,CMData);
      PushCall(CMData->Pit,tmpIndex,offset+i,-1);
      i += INSTR_instrSize(opcode);
      continue;
    }
    
    instrCat=INSTR_instrType(opcode);
    opType=INSTR_operandTypes(instrCat);
    argid=0;
    do{
      switch(opType[argid])
      {
        case INSTR_P:
          j++;
          break;
          
        case INSTR_WP:
          j+=sizeof(Word);
          break;
          
        case INSTR_SEG:
          LK_FILE_GET1(fd);//Consume dummy argument
          *(Byte*)(code+j)=CMData->SegmentID;
          debug("ID:%d\t",CMData->SegmentID);
          j+=sizeof(Byte);
          break;
        
        case INSTR_R:
        case INSTR_E:
        case INSTR_N:
        case INSTR_I1:
        case INSTR_CE:
          *(Byte*)(code+j)=LK_FILE_GET1(fd);
          debug("%d\t",*(Byte*)(code+j));
          j+=sizeof(Byte);
          break;

//         case INSTR_I2:
//           *(TwoBytes*)(code+j)=GET2();
//           j+=sizeof(TwoBytes);
//           break;
          
        case INSTR_C:
          *(TwoBytes*)(code+j)=PackConstInd(GetConstInd(fd,CMData));
          debug("C:%d\t",*(TwoBytes*)(code+j));
          j+=sizeof(TwoBytes);
          break;
          
        case INSTR_K:
          *(TwoBytes*)(code+j)=PackKindInd(GetKindInd(fd,CMData));
          debug("K:%d\t",*(TwoBytes*)(code+j));
          j+=sizeof(TwoBytes);
          break;
          
        case INSTR_MT:
          *(ImportTabInd*)(code+j)=GetImportTabInd(fd,CMData);
          debug("IT:%d\t",*(ImportTabInd*)(code+j));
          j+=sizeof(ImportTabInd);
          break;
          
        case INSTR_IT:
          *(ImplGoalInd*)(code+j)=GetImplGoalInd(fd,CMData);
          debug("IG:%d\t",*(ImplGoalInd*)(code+j));
          j+=sizeof(ImplGoalInd);
          break;
          
        case INSTR_HT:
          *(HashTabInd*)(code+j)=GetHashTabInd(fd,CMData);
          debug("HT:%d\t",*(HashTabInd*)(code+j));
          j+=sizeof(HashTabInd);
          break;
          
        case INSTR_BVT:
          *(BvrTabInd*)(code+j)=GetBvrTabInd(fd,CMData);
          debug("BT:%d\t",*(BvrTabInd*)(code+j));
          j+=sizeof(BvrTabInd);
          break;
          
        case INSTR_S:
          *(StringInd*)(code+j)=GetStringInd(fd,CMData);
          debug("S:%d\t",*(StringInd*)(code+j));
          j+=sizeof(StringInd);
          break;
        
        case INSTR_L:
          *(CodeInd*)(code+j)=GetCodeInd(fd,CMData);
          debug("L:%d\t",*(CodeInd*)(code+j));
          j+=sizeof(CodeInd);
          break;
          
        case INSTR_I:
          *(INT4*)(code+j)=LK_FILE_GET4(fd);
          debug("I:%d\t",*(INT4*)(code+j));
          j+=sizeof(INT4);
          break;

        case INSTR_F:
          *(INT4*)(code+j)=GetFloat(fd);
          debug("F:%d\t",*(INT4*)(code+j));
          j+=sizeof(INT4);
          break;
          
        case INSTR_X:
          break;
        default:
          bad("Unknown Operand Type %d\n",opType[argid]);
          EM_THROW(LK_LinkError);
          break;
      }
      argid++;
    }
    while(opType[argid]!=INSTR_X);
    debug("\n");
    i += INSTR_instrSize(opcode);
  }
  debug("NOWD -> %d[%d,%d]\n",166,(*(ConstInd*)(code+166)).gl_flag,(*(ConstInd*)(code+166)).index);
          
}
Example #30
-1
void ini_control_transfer(usb_dev_handle *dev) {
    int r,i;

    char question[] = { 0x01,0x01 };

    r = usb_control_msg(dev, 0x21, 0x09, 0x0201, 0x00, (char *) question, 2, timeout);
    if( r < 0 )
    {
          perror("USB control write"); bad("USB write failed"); 
    }


    if(debug) {
      for (i=0;i<reqIntLen; i++) printf("%02x ",question[i] & 0xFF);
      printf("\n");
    }
}