コード例 #1
0
ファイル: upd7759.c プロジェクト: cdrr/MAME_hack
/*
 *   Update emulation of an uPD7759 output stream
 */
static void UPD7759_update (int chip, INT16 *buffer, int left)
{
	struct UPD7759voice *voice = &updadpcm[chip];
	int i;

	/* see if there's actually any need to generate samples */
	LOG(3,(errorlog,"UPD7759_update %d (%d)\n", left, voice->available));

    if (left > 0)
	{
        /* if this voice is active */
		if (voice->playing)
		{
			voice->available -= left;
			if( upd7759_intf->mode == UPD7759_SLAVE_MODE )
			{
				while( left-- > 0 )
				{
					*buffer++ = voice->data[voice->tail];
#if OVERSAMPLE
					if( (voice->counter++ % OVERSAMPLE) == 0 )
#endif
                    voice->tail = (voice->tail + 1) % DATA_MAX;
				}
			}
			else
			{
				unsigned char *base = voice->base;
                int val;
#if OVERSAMPLING
				int i, delta;
#endif

                while( left > 0 )
				{
					/* compute the new amplitude and update the current voice->step */
					val = base[(voice->sample / 2) & voice->mask] >> (((voice->sample & 1) << 2) ^ 4);
					voice->step = FALL_OFF(voice->step) + index_shift[val & (INDEX_SHIFT_MAX-1)];
					if (voice->step > STEP_MAX) voice->step = STEP_MAX;
					else if (voice->step < STEP_MIN) voice->step = STEP_MIN;
					voice->signal = FALL_OFF(voice->signal) + diff_lookup[voice->step * 16 + (val & 15)];
					if (voice->signal > SIGNAL_MAX) voice->signal = SIGNAL_MAX;
					else if (voice->signal < SIGNAL_MIN) voice->signal = SIGNAL_MIN;
#if OVERSAMPLING
					i = 0;
					delta = voice->signal - voice->old_signal;
					while (voice->counter > 0 && left > 0)
					{
						*sample++ = voice->old_signal + delta * i / oversampling;
						if (++i == oversampling) i = 0;
						voice->counter -= voice->freq;
						left--;
					}
					voice->old_signal = voice->signal;
#else
					while (voice->counter > 0 && left > 0)
					{
						*buffer++ = voice->signal;
						voice->counter -= voice->freq;
						left--;
					}
#endif
					voice->counter += emulation_rate;

					/* next! */
					if( ++voice->sample > voice->count )
					{
						while (left-- > 0)
						{
							*buffer++ = voice->signal;
							voice->signal = FALL_OFF(voice->signal);
						}
						voice->playing = 0;
						break;
					}
				}
            }
		}
		else
		{
			/* voice is not playing */
			for (i = 0; i < left; i++)
コード例 #2
0
void ChangeTimeSpeedFunc(unsigned long newRate)
{
    kSpeedRate = newRate / 1000.0f;
    LOG("New Speed Rate:");
    LOG(kSpeedRate);
}
コード例 #3
0
ファイル: hid.c プロジェクト: adamruul/arduino-project
struct hid_device_info  HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
	libusb_device **devs;
	libusb_device *dev;
	libusb_device_handle *handle;
	ssize_t num_devs;
	int i = 0;

	struct hid_device_info *root = NULL; /* return object */
	struct hid_device_info *cur_dev = NULL;

	hid_init();

	num_devs = libusb_get_device_list(usb_context, &devs);
	if (num_devs < 0)
		return NULL;
	while ((dev = devs[i++]) != NULL) {
		struct libusb_device_descriptor desc;
		struct libusb_config_descriptor *conf_desc = NULL;
		int j, k;
		int interface_num = 0;

		int res = libusb_get_device_descriptor(dev, &desc);
		unsigned short dev_vid = desc.idVendor;
		unsigned short dev_pid = desc.idProduct;

		/* HID's are defined at the interface level. */
		if (desc.bDeviceClass != LIBUSB_CLASS_PER_INTERFACE)
			continue;

		res = libusb_get_active_config_descriptor(dev, &conf_desc);
		if (res < 0)
			libusb_get_config_descriptor(dev, 0, &conf_desc);
		if (conf_desc) {
			for (j = 0; j < conf_desc->bNumInterfaces; j++) {
				const struct libusb_interface *intf = &conf_desc->interface[j];
				for (k = 0; k < intf->num_altsetting; k++) {
					const struct libusb_interface_descriptor *intf_desc;
					intf_desc = &intf->altsetting[k];
					if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
						interface_num = intf_desc->bInterfaceNumber;

						/* Check the VID/PID against the arguments */
						if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
						    (product_id == 0x0 || product_id == dev_pid)) {
							struct hid_device_info *tmp;

							/* VID/PID match. Create the record. */
							tmp = calloc(1, sizeof(struct hid_device_info));
							if (cur_dev) {
								cur_dev->next = tmp;
							}
							else {
								root = tmp;
							}
							cur_dev = tmp;

							/* Fill out the record */
							cur_dev->next = NULL;
							cur_dev->path = make_path(dev, interface_num);

							res = libusb_open(dev, &handle);

							if (res >= 0) {
								/* Serial Number */
								if (desc.iSerialNumber > 0)
									cur_dev->serial_number =
										get_usb_string(handle, desc.iSerialNumber);

								/* Manufacturer and Product strings */
								if (desc.iManufacturer > 0)
									cur_dev->manufacturer_string =
										get_usb_string(handle, desc.iManufacturer);
								if (desc.iProduct > 0)
									cur_dev->product_string =
										get_usb_string(handle, desc.iProduct);

#ifdef INVASIVE_GET_USAGE
{
							/*
							This section is removed because it is too
							invasive on the system. Getting a Usage Page
							and Usage requires parsing the HID Report
							descriptor. Getting a HID Report descriptor
							involves claiming the interface. Claiming the
							interface involves detaching the kernel driver.
							Detaching the kernel driver is hard on the system
							because it will unclaim interfaces (if another
							app has them claimed) and the re-attachment of
							the driver will sometimes change /dev entry names.
							It is for these reasons that this section is
							#if 0. For composite devices, use the interface
							field in the hid_device_info struct to distinguish
							between interfaces. */
								unsigned char data[256];
#ifdef DETACH_KERNEL_DRIVER
								int detached = 0;
								/* Usage Page and Usage */
								res = libusb_kernel_driver_active(handle, interface_num);
								if (res == 1) {
									res = libusb_detach_kernel_driver(handle, interface_num);
									if (res < 0)
										LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
									else
										detached = 1;
								}
#endif
								res = libusb_claim_interface(handle, interface_num);
								if (res >= 0) {
									/* Get the HID Report Descriptor. */
									res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
									if (res >= 0) {
										unsigned short page=0, usage=0;
										/* Parse the usage and usage page
										   out of the report descriptor. */
										get_usage(data, res,  &page, &usage);
										cur_dev->usage_page = page;
										cur_dev->usage = usage;
									}
									else
										LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);

									/* Release the interface */
									res = libusb_release_interface(handle, interface_num);
									if (res < 0)
										LOG("Can't release the interface.\n");
								}
								else
									LOG("Can't claim interface %d\n", res);
#ifdef DETACH_KERNEL_DRIVER
								/* Re-attach kernel driver if necessary. */
								if (detached) {
									res = libusb_attach_kernel_driver(handle, interface_num);
									if (res < 0)
										LOG("Couldn't re-attach kernel driver.\n");
								}
#endif
}
#endif /* INVASIVE_GET_USAGE */

								libusb_close(handle);
							}
							/* VID/PID */
							cur_dev->vendor_id = dev_vid;
							cur_dev->product_id = dev_pid;

							/* Release Number */
							cur_dev->release_number = desc.bcdDevice;

							/* Interface Number */
							cur_dev->interface_number = interface_num;
						}
					}
				} /* altsettings */
			} /* interfaces */
			libusb_free_config_descriptor(conf_desc);
		}
	}

	libusb_free_device_list(devs, 1);

	return root;
}
コード例 #4
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
void Script::AddArgument(ElementHandle argument) {
  LOG(TRACE) << "Entering Script::AddArgument(ElementHandle)";
  this->AddArgument(argument->element());
}
コード例 #5
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
void Script::AddArgument(VARIANT argument) {
  LOG(TRACE) << "Entering Script::AddArgument(VARIANT)";
  CComVariant wrapped_argument(argument);
  this->argument_array_[this->current_arg_index_] = wrapped_argument;
  ++this->current_arg_index_;
}
コード例 #6
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
void Script::AddArgument(const std::string& argument) {
  LOG(TRACE) << "Entering Script::AddArgument(std::string)";
  std::wstring wide_argument = StringUtilities::ToWString(argument);
  this->AddArgument(wide_argument);
}
コード例 #7
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
void Script::AddArgument(const int argument) {
  LOG(TRACE) << "Entering Script::AddArgument(int)";
  CComVariant dest_argument((long)argument);
  this->AddArgument(dest_argument);
}
コード例 #8
0
ファイル: database.cpp プロジェクト: fengjhwa/mongo
    Status Database::dropCollection( OperationContext* txn, const StringData& fullns ) {
        LOG(1) << "dropCollection: " << fullns << endl;
        massertNamespaceNotIndex( fullns, "dropCollection" );

        Collection* collection = getCollection( txn, fullns );
        if ( !collection ) {
            // collection doesn't exist
            return Status::OK();
        }

        {
            NamespaceString s( fullns );
            verify( s.db() == _name );

            if( s.isSystem() ) {
                if( s.coll() == "system.profile" ) {
                    if ( _profile != 0 )
                        return Status( ErrorCodes::IllegalOperation,
                                       "turn off profiling before dropping system.profile collection" );
                }
                else {
                    return Status( ErrorCodes::IllegalOperation, "can't drop system ns" );
                }
            }
        }

        BackgroundOperation::assertNoBgOpInProgForNs( fullns );

        audit::logDropCollection( currentClient.get(), fullns );

        try {
            Status s = collection->getIndexCatalog()->dropAllIndexes(txn, true);
            if ( !s.isOK() ) {
                warning() << "could not drop collection, trying to drop indexes"
                          << fullns << " because of " << s.toString();
                return s;
            }
        }
        catch( DBException& e ) {
            stringstream ss;
            ss << "drop: dropIndexes for collection failed. cause: " << e.what();
            ss << ". See http://dochub.mongodb.org/core/data-recovery";
            warning() << ss.str() << endl;
            return Status( ErrorCodes::InternalError, ss.str() );
        }

        verify( collection->_details->getTotalIndexCount( txn ) == 0 );
        LOG(1) << "\t dropIndexes done" << endl;

        Top::global.collectionDropped( fullns );

        Status s = _dbEntry->dropCollection( txn, fullns );

        _clearCollectionCache( txn, fullns ); // we want to do this always

        if ( !s.isOK() )
            return s;

        DEV {
            // check all index collection entries are gone
            string nstocheck = fullns.toString() + ".$";
            scoped_lock lk( _collectionLock );
            for ( CollectionMap::const_iterator i = _collections.begin();
                  i != _collections.end();
                  ++i ) {
                string temp = i->first;
                if ( temp.find( nstocheck ) != 0 )
                    continue;
                log() << "after drop, bad cache entries for: "
                      << fullns << " have " << temp;
                verify(0);
            }
        }

        return Status::OK();
    }
コード例 #9
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
void Script::AddNullArgument() {
  LOG(TRACE) << "Entering Script::AddNullArgument";
  CComVariant null_arg;
  null_arg.vt = VT_NULL;
  this->AddArgument(null_arg);
}
コード例 #10
0
        void commit( set<DiskLoc>* dupsToDrop,
                     CurOp* op,
                     bool mayInterrupt ) {

            Timer timer;

            IndexCatalogEntry* entry = _real->_btreeState;

            bool dupsAllowed = !entry->descriptor()->unique() ||
                ignoreUniqueIndex(entry->descriptor());
            bool dropDups = entry->descriptor()->dropDups() || inDBRepair;

            BtreeBuilder<V> btBuilder(dupsAllowed, entry);

            BSONObj keyLast;
            scoped_ptr<BSONObjExternalSorter::Iterator> i( _phase1.sorter->iterator() );

            // verifies that pm and op refer to the same ProgressMeter
            ProgressMeter& pm = op->setMessage("Index Bulk Build: (2/3) btree bottom up",
                                               "Index: (2/3) BTree Bottom Up Progress",
                                               _phase1.nkeys,
                                               10);

            while( i->more() ) {
                RARELY killCurrentOp.checkForInterrupt( !mayInterrupt );
                ExternalSortDatum d = i->next();

                try {
                    if ( !dupsAllowed && dropDups ) {
                        LastError::Disabled led( lastError.get() );
                        btBuilder.addKey(d.first, d.second);
                    }
                    else {
                        btBuilder.addKey(d.first, d.second);
                    }
                }
                catch( AssertionException& e ) {
                    if ( dupsAllowed ) {
                        // unknown exception??
                        throw;
                    }

                    if( e.interrupted() ) {
                        killCurrentOp.checkForInterrupt();
                    }

                    if ( ! dropDups )
                        throw;

                    /* we could queue these on disk, but normally there are very few dups,
                     * so instead we keep in ram and have a limit.
                    */
                    if ( dupsToDrop ) {
                        dupsToDrop->insert(d.second);
                        uassert( 10092,
                                 "too may dups on index build with dropDups=true",
                                 dupsToDrop->size() < 1000000 );
                    }
                }
                pm.hit();
            }
            pm.finished();
            op->setMessage("Index Bulk Build: (3/3) btree-middle",
                           "Index: (3/3) BTree Middle Progress");
            LOG(timer.seconds() > 10 ? 0 : 1 ) << "\t done building bottom layer, going to commit";
            btBuilder.commit( mayInterrupt );
            if ( btBuilder.getn() != _phase1.nkeys && ! dropDups ) {
                warning() << "not all entries were added to the index, probably some "
                          << "keys were too large" << endl;
            }
        }
コード例 #11
0
ファイル: mythxmlclient.cpp プロジェクト: Olti/mythtv
UPnPResultCode MythXMLClient::GetConnectionInfo( const QString &sPin, DatabaseParams *pParams, QString &sMsg )
{
    if (pParams == NULL)
        return UPnPResult_InvalidArgs;

    int           nErrCode = 0;
    QString       sErrDesc;
    QStringMap    list;

    sMsg.clear();

    list.insert( "Pin", sPin );

    QDomDocument xmlResults = SendSOAPRequest(
        "GetConnectionInfo", list, nErrCode, sErrDesc, m_bInQtThread);

    // --------------------------------------------------------------
    // Is this a valid response?
    // --------------------------------------------------------------

    QDomNode oNode = xmlResults.namedItem( "GetConnectionInfoResult" );

    if (UPnPResult_Success == nErrCode && !oNode.isNull())
    {
        QDomNode dbNode = oNode.namedItem( "Database" );

        pParams->dbHostName   = GetNodeValue( dbNode, "Host"     , QString());
        pParams->dbPort       = GetNodeValue( dbNode, "Port"     , 0        );
        pParams->dbUserName   = GetNodeValue( dbNode, "UserName" , QString());
        pParams->dbPassword   = GetNodeValue( dbNode, "Password" , QString());
        pParams->dbName       = GetNodeValue( dbNode, "Name"     , QString());
        pParams->dbType       = GetNodeValue( dbNode, "Type"     , QString());

        QDomNode wolNode = oNode.namedItem( "WOL" );

        pParams->wolEnabled   = GetNodeValue( wolNode, "Enabled"  , false    );
        pParams->wolReconnect = GetNodeValue( wolNode, "Reconnect", 0        );
        pParams->wolRetry     = GetNodeValue( wolNode, "Retry"    , 0        );
        pParams->wolCommand   = GetNodeValue( wolNode, "Command"  , QString());

        QDomNode verNode = oNode.namedItem( "Version" );

        pParams->verVersion   = GetNodeValue( verNode, "Version"  , ""       );
        pParams->verBranch    = GetNodeValue( verNode, "Branch"   , ""       );
        pParams->verProtocol  = GetNodeValue( verNode, "Protocol" , ""       );
        pParams->verBinary    = GetNodeValue( verNode, "Binary"   , ""       );
        pParams->verSchema    = GetNodeValue( verNode, "Schema"   , ""       );

        if ((pParams->verProtocol != MYTH_PROTO_VERSION) ||
            (pParams->verSchema   != MYTH_DATABASE_VERSION))
            // incompatible version, we cannot use this backend
        {
            LOG(VB_GENERAL, LOG_ERR,
                QString("MythXMLClient::GetConnectionInfo Failed - "
                        "Version Mismatch (%1,%2) != (%3,%4)")
                .arg(pParams->verProtocol)
                .arg(pParams->verSchema)
                .arg(MYTH_PROTO_VERSION)
                .arg(MYTH_DATABASE_VERSION));
            sMsg = QObject::tr("Version Mismatch", "UPNP Errors");
            return UPnPResult_ActionFailed;
        }

        return UPnPResult_Success;
    }
    else
    {
        sMsg = sErrDesc;

        LOG(VB_GENERAL, LOG_ERR,
            QString("MythXMLClient::GetConnectionInfo Failed - (%1) %2")
                .arg(nErrCode) .arg(sErrDesc));
    }

    if (( nErrCode == UPnPResult_HumanInterventionRequired ) || 
        ( nErrCode == UPnPResult_ActionNotAuthorized       ) ||
        ( nErrCode == 501                                  ))
    {
        // Service calls no longer return UPnPResult codes, 
        // convert standard 501 to UPnPResult code for now.
        sMsg = QObject::tr("Not Authorized", "UPNP Errors");
        return UPnPResult_ActionNotAuthorized;
    }

    sMsg = QObject::tr("Unknown Error", "UPNP Errors");
    return UPnPResult_ActionFailed;
}
コード例 #12
0
ファイル: db.c プロジェクト: asyn/openvims
/**
 *  Get the NDS list from the database.
 * @param d - array of string to fill with the db contents
 * @returns 1 on success, 0 on error 
 */
int icscf_db_get_nds(str *d[])
{
	db_key_t   keys_ret[] = {"trusted_domain"};
	db_res_t   * res = 0 ;	
	str s;
	int i;

	if (!icscf_db_check_init(hdl_nds))
		goto error;

	DBG("DBG:"M_NAME":icscf_db_get_nds: fetching list of NDS for I-CSCF \n");

	if (dbf.query(hdl_nds, 0, 0, 0, keys_ret, 0, 1, NULL, & res) < 0) {
		LOG(L_ERR, "ERR:"M_NAME":icscf_db_get_nds: db_query failed\n");
		goto error;
	}

	if (res->n == 0) {
		DBG("DBG:"M_NAME":icscf_db_get_nds: I-CSCF has no NDS trusted domains in db\n");
		*d=shm_malloc(sizeof(str));
		if (*d==NULL){
			LOG(L_ERR, "ERR:"M_NAME":icscf_db_get_nds: failed shm_malloc for 0 domains\n");
			goto error;
		}	
		(*d)[0].s=0;
		(*d)[0].len=0;
	}
	else {
		*d=shm_malloc(sizeof(str)*(res->n+1));
		if (*d==NULL){
			LOG(L_ERR, "ERR:"M_NAME":icscf_db_get_nds: failed shm_malloc for %d domains\n",
				res->n);
			goto error;
		}	
		for(i=0;i<res->n;i++){
			s.s = (char*) res->rows[i].values[0].val.string_val;
			s.len = strlen(s.s);
			(*d)[i].s = shm_malloc(s.len);
			if ((*d)[i].s==NULL) {
				LOG(L_ERR, "ERR:"M_NAME":icscf_db_get_nds: failed shm_malloc for %d bytes\n",
					s.len);
				(*d)[i].len = 0;
			}else{
				(*d)[i].len = s.len;
				memcpy((*d)[i].s,s.s,s.len);
			}
		}
		(*d)[res->n].s=0;
		(*d)[res->n].len=0;
	}

	LOG(L_INFO, "INF:"M_NAME":icscf_db_get_nds: Loaded %d trusted domains\n",
		res->n);

	dbf.free_result( hdl_nds, res);
	return 1;
error:
	if (res)
		dbf.free_result( hdl_nds, res);
	*d=shm_malloc(sizeof(str));
	if (*d==NULL)
		LOG(L_ERR, "ERR:"M_NAME":icscf_db_get_nds: failed shm_malloc for 0 domains\n");
	else {
		(*d)[0].s=0;
		(*d)[0].len=0;
	}
	return 0;
}
コード例 #13
0
ファイル: db.cpp プロジェクト: Machyne/mongo
void repairDatabasesAndCheckVersion(OperationContext* txn) {
    LOG(1) << "enter repairDatabases (to check pdfile version #)";

    ScopedTransaction transaction(txn, MODE_X);
    Lock::GlobalWrite lk(txn->lockState());

    vector<string> dbNames;

    StorageEngine* storageEngine = txn->getServiceContext()->getGlobalStorageEngine();
    storageEngine->listDatabases(&dbNames);

    // Repair all databases first, so that we do not try to open them if they are in bad shape
    if (storageGlobalParams.repair) {
        invariant(!storageGlobalParams.readOnly);
        for (vector<string>::const_iterator i = dbNames.begin(); i != dbNames.end(); ++i) {
            const string dbName = *i;
            LOG(1) << "    Repairing database: " << dbName;

            fassert(18506, repairDatabase(txn, storageEngine, dbName));
        }
    }

    const repl::ReplSettings& replSettings = repl::getGlobalReplicationCoordinator()->getSettings();

    // On replica set members we only clear temp collections on DBs other than "local" during
    // promotion to primary. On pure slaves, they are only cleared when the oplog tells them
    // to. The local DB is special because it is not replicated.  See SERVER-10927 for more
    // details.
    const bool shouldClearNonLocalTmpCollections =
        !(checkIfReplMissingFromCommandLine(txn) || replSettings.usingReplSets() ||
          replSettings.isSlave());

    const bool shouldDoCleanupForSERVER23299 = isSubjectToSERVER23299(txn);

    for (vector<string>::const_iterator i = dbNames.begin(); i != dbNames.end(); ++i) {
        const string dbName = *i;
        LOG(1) << "    Recovering database: " << dbName;

        Database* db = dbHolder().openDb(txn, dbName);
        invariant(db);

        // First thing after opening the database is to check for file compatibility,
        // otherwise we might crash if this is a deprecated format.
        auto status = db->getDatabaseCatalogEntry()->currentFilesCompatible(txn);
        if (!status.isOK()) {
            if (status.code() == ErrorCodes::CanRepairToDowngrade) {
                // Convert CanRepairToDowngrade statuses to MustUpgrade statuses to avoid logging a
                // potentially confusing and inaccurate message.
                //
                // TODO SERVER-24097: Log a message informing the user that they can start the
                // current version of mongod with --repair and then proceed with normal startup.
                status = {ErrorCodes::MustUpgrade, status.reason()};
            }
            severe() << "Unable to start mongod due to an incompatibility with the data files and"
                        " this version of mongod: "
                     << redact(status);
            severe() << "Please consult our documentation when trying to downgrade to a previous"
                        " major release";
            quickExit(EXIT_NEED_UPGRADE);
            return;
        }

        // Check if admin.system.version contains an invalid featureCompatibilityVersion.
        // If a valid featureCompatibilityVersion is present, cache it as a server parameter.
        if (dbName == "admin") {
            if (Collection* versionColl =
                    db->getCollection(FeatureCompatibilityVersion::kCollection)) {
                BSONObj featureCompatibilityVersion;
                if (Helpers::findOne(txn,
                                     versionColl,
                                     BSON("_id" << FeatureCompatibilityVersion::kParameterName),
                                     featureCompatibilityVersion)) {
                    auto version = FeatureCompatibilityVersion::parse(featureCompatibilityVersion);
                    if (!version.isOK()) {
                        severe() << version.getStatus();
                        fassertFailedNoTrace(40283);
                    }
                    serverGlobalParams.featureCompatibility.version.store(version.getValue());
                }
            }
        }

        // Major versions match, check indexes
        const string systemIndexes = db->name() + ".system.indexes";

        Collection* coll = db->getCollection(systemIndexes);
        unique_ptr<PlanExecutor> exec(
            InternalPlanner::collectionScan(txn, systemIndexes, coll, PlanExecutor::YIELD_MANUAL));

        BSONObj index;
        PlanExecutor::ExecState state;
        while (PlanExecutor::ADVANCED == (state = exec->getNext(&index, NULL))) {
            const BSONObj key = index.getObjectField("key");
            const string plugin = IndexNames::findPluginName(key);

            if (db->getDatabaseCatalogEntry()->isOlderThan24(txn)) {
                if (IndexNames::existedBefore24(plugin)) {
                    continue;
                }

                log() << "Index " << index << " claims to be of type '" << plugin << "', "
                      << "which is either invalid or did not exist before v2.4. "
                      << "See the upgrade section: "
                      << "http://dochub.mongodb.org/core/upgrade-2.4" << startupWarningsLog;
            }

            if (index["v"].isNumber() && index["v"].numberInt() == 0) {
                log() << "WARNING: The index: " << index << " was created with the deprecated"
                      << " v:0 format.  This format will not be supported in a future release."
                      << startupWarningsLog;
                log() << "\t To fix this, you need to rebuild this index."
                      << " For instructions, see http://dochub.mongodb.org/core/rebuild-v0-indexes"
                      << startupWarningsLog;
            }
        }

        // Non-yielding collection scans from InternalPlanner will never error.
        invariant(PlanExecutor::IS_EOF == state);

        if (replSettings.usingReplSets()) {
            // We only care about the _id index if we are in a replset
            checkForIdIndexes(txn, db);
            // Ensure oplog is capped (mmap does not guarantee order of inserts on noncapped
            // collections)
            if (db->name() == "local") {
                checkForCappedOplog(txn, db);
            }
        }

        if (shouldDoCleanupForSERVER23299) {
            handleSERVER23299ForDb(txn, db);
        }

        if (!storageGlobalParams.readOnly &&
            (shouldClearNonLocalTmpCollections || dbName == "local")) {
            db->clearTmpCollections(txn);
        }
    }

    LOG(1) << "done repairDatabases";
}
コード例 #14
0
ファイル: afp_mdns.c プロジェクト: kevinxucs/netatalk-debian
/*
 * This function tries to register the AFP DNS
 * SRV service type.
 */
static void register_stuff(const AFPObj *obj) {
    uint                                        port;
    const struct vol                *volume;
    DSI                                         *dsi;
    char                                        name[MAXINSTANCENAMELEN+1];
    DNSServiceErrorType         error;
    TXTRecordRef                        txt_adisk;
    TXTRecordRef                        txt_devinfo;
    char                                        tmpname[256];

    // If we had already registered, then we will unregister and re-register
    if(svc_refs) unregister_stuff();

    /* Register our service, prepare the TXT record */
    TXTRecordCreate(&txt_adisk, 0, NULL);
    if( 0 > TXTRecordPrintf(&txt_adisk, "sys", "waMa=0,adVF=0x100") ) {
        LOG ( log_error, logtype_afpd, "Could not create Zeroconf TXTRecord for sys");
        goto fail;
    }

    /* Build AFP volumes list */
    int i = 0;

    for (volume = getvolumes(); volume; volume = volume->v_next) {

        if (convert_string(CH_UCS2, CH_UTF8_MAC, volume->v_u8mname, -1, tmpname, 255) <= 0) {
            LOG ( log_error, logtype_afpd, "Could not set Zeroconf volume name for TimeMachine");
            goto fail;
        }

        if (volume->v_flags & AFPVOL_TM) {
            if (volume->v_uuid) {
                LOG(log_info, logtype_afpd, "Registering volume '%s' with UUID: '%s' for TimeMachine",
                    volume->v_localname, volume->v_uuid);
                if( 0 > TXTRecordKeyPrintf(&txt_adisk, "dk%u", i++, "adVN=%s,adVF=0xa1,adVU=%s",
                                   tmpname, volume->v_uuid) ) {
                    LOG ( log_error, logtype_afpd, "Could not set Zeroconf TXTRecord for dk%u", i);
                    goto fail;
                }
            } else {
                LOG(log_warning, logtype_afpd, "Registering volume '%s' for TimeMachine. But UUID is invalid.",
                    volume->v_localname);
                if( 0 > TXTRecordKeyPrintf(&txt_adisk, "dk%u", i++, "adVN=%s,adVF=0xa1", tmpname) ) {
                    LOG ( log_error, logtype_afpd, "Could not set Zeroconf TXTRecord for dk%u", i);
                    goto fail;
                }
            }
        }
    }

    /* AFP_DNS_SERVICE_TYPE */
    svc_ref_count = 1;
    if (i) {
        /* ADISK_SERVICE_TYPE */
        svc_ref_count++;
    }
    if (obj->options.mimicmodel) {
        /* DEV_INFO_SERVICE_TYPE */
        svc_ref_count++;
    }

    // Allocate the memory to store our service refs
    svc_refs = calloc(svc_ref_count, sizeof(DNSServiceRef));
    assert(svc_refs);
    svc_ref_count = 0;

    port = atoi(obj->options.port);

    if (convert_string(obj->options.unixcharset,
                       CH_UTF8,
                       obj->options.hostname,
                       -1,
                       name,
                       MAXINSTANCENAMELEN) <= 0) {
        LOG(log_error, logtype_afpd, "Could not set Zeroconf instance name");
        goto fail;
    }
    LOG(log_info, logtype_afpd, "Registering server '%s' with Bonjour",
        dsi->bonjourname);

    error = DNSServiceRegister(&svc_refs[svc_ref_count++],
                               0,               // no flags
                               0,               // all network interfaces
                               name,
                               AFP_DNS_SERVICE_TYPE,
                               "",            // default domains
                               NULL,            // default host name
                               htons(port),
                               0,               // length of TXT
                               NULL,            // no TXT
                               RegisterReply,           // callback
                               NULL);       // no context
    if (error != kDNSServiceErr_NoError) {
        LOG(log_error, logtype_afpd, "Failed to add service: %s, error=%d",
            AFP_DNS_SERVICE_TYPE, error);
        goto fail;
    }

    if (i) {
        error = DNSServiceRegister(&svc_refs[svc_ref_count++],
                                   0,               // no flags
                                   0,               // all network interfaces
                                   name,
                                   ADISK_SERVICE_TYPE,
                                   "",            // default domains
                                   NULL,            // default host name
                                   htons(port),
                                   TXTRecordGetLength(&txt_adisk),
                                   TXTRecordGetBytesPtr(&txt_adisk),
                                   RegisterReply,           // callback
                                   NULL);       // no context
        if (error != kDNSServiceErr_NoError) {
            LOG(log_error, logtype_afpd, "Failed to add service: %s, error=%d",
                ADISK_SERVICE_TYPE, error);
            goto fail;
        }
    }

    if (obj->options.mimicmodel) {
        LOG(log_info, logtype_afpd, "Registering server '%s' with model '%s'",
            dsi->bonjourname, obj->options.mimicmodel);
        TXTRecordCreate(&txt_devinfo, 0, NULL);
        if ( 0 > TXTRecordPrintf(&txt_devinfo, "model", obj->options.mimicmodel) ) {
            LOG ( log_error, logtype_afpd, "Could not create Zeroconf TXTRecord for model");
            goto fail;
        }

        error = DNSServiceRegister(&svc_refs[svc_ref_count++],
                                   0,               // no flags
                                   0,               // all network interfaces
                                   name,
                                   DEV_INFO_SERVICE_TYPE,
                                   "",            // default domains
                                   NULL,            // default host name
                                   /*
                                    * We would probably use port 0 zero, but we can't, from man DNSServiceRegister:
                                    *   "A value of 0 for a port is passed to register placeholder services.
                                    *    Place holder services are not found  when browsing, but other
                                    *    clients cannot register with the same name as the placeholder service."
                                    * We therefor use port 9 which is used by the adisk service type.
                                    */
                                   htons(9),
                                   TXTRecordGetLength(&txt_devinfo),
                                   TXTRecordGetBytesPtr(&txt_devinfo),
                                   RegisterReply,           // callback
                                   NULL);       // no context
        TXTRecordDeallocate(&txt_devinfo);
        if (error != kDNSServiceErr_NoError) {
            LOG(log_error, logtype_afpd, "Failed to add service: %s, error=%d",
                DEV_INFO_SERVICE_TYPE, error);
            goto fail;
        }
    } /* if (config->obj.options.mimicmodel) */

    /*
     * Now we can create the thread that will poll for the results
     * and handle the calling of the callbacks
     */
    if(pthread_create(&poller, NULL, polling_thread, NULL) != 0) {
        LOG(log_error, logtype_afpd, "Unable to start mDNS polling thread");
        goto fail;
    }

fail:
    TXTRecordDeallocate(&txt_adisk);
    return;
}
コード例 #15
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
int Script::Execute() {
  LOG(TRACE) << "Entering Script::Execute";

  CComVariant result = L"";
  CComBSTR error_description = L"";

  if (this->script_engine_host_ == NULL) {
    LOG(WARN) << "Script engine host is NULL";
    return ENOSUCHDOCUMENT;
  }
  CComVariant temp_function;
  if (!this->CreateAnonymousFunction(&temp_function)) {
    LOG(WARN) << "Cannot create anonymous function";
    return EUNEXPECTEDJSERROR;
  }

  if (temp_function.vt != VT_DISPATCH) {
    LOG(DEBUG) << "No return value that we care about";
    return WD_SUCCESS;
  }

  // Grab the "call" method out of the returned function
  DISPID call_member_id;
  OLECHAR FAR* call_member_name = L"call";
  HRESULT hr = temp_function.pdispVal->GetIDsOfNames(IID_NULL,
                                                     &call_member_name,
                                                     1,
                                                     LOCALE_USER_DEFAULT,
                                                     &call_member_id);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Cannot locate call method on anonymous function";
    return EUNEXPECTEDJSERROR;
  }

  CComPtr<IHTMLWindow2> win;
  hr = this->script_engine_host_->get_parentWindow(&win);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "Cannot get parent window, IHTMLDocument2::get_parentWindow failed";
    return EUNEXPECTEDJSERROR;
  }

  // IDispatch::Invoke() expects the arguments to be passed into it
  // in reverse order. To accomplish this, we create a new variant
  // array of size n + 1 where n is the number of arguments we have.
  // we copy each element of arguments_array_ into the new array in
  // reverse order, and add an extra argument, the window object,
  // to the end of the array to use as the "this" parameter for the
  // function invocation.
  size_t arg_count = this->argument_array_.size();
  std::vector<CComVariant> argument_array_copy(arg_count + 1);
  CComVariant window_variant(win);
  argument_array_copy[arg_count].Copy(&window_variant);

  for (size_t index = 0; index < arg_count; ++index) {
    argument_array_copy[arg_count - 1 - index].Copy(&this->argument_array_[index]);
  }

  DISPPARAMS call_parameters = { 0 };
  memset(&call_parameters, 0, sizeof call_parameters);
  call_parameters.cArgs = static_cast<unsigned int>(argument_array_copy.size());
  call_parameters.rgvarg = &argument_array_copy[0];

  int return_code = WD_SUCCESS;
  EXCEPINFO exception;
  memset(&exception, 0, sizeof exception);
  hr = temp_function.pdispVal->Invoke(call_member_id,
                                      IID_NULL,
                                      LOCALE_USER_DEFAULT,
                                      DISPATCH_METHOD,
                                      &call_parameters, 
                                      &result,
                                      &exception,
                                      0);

  if (FAILED(hr)) {
    if (DISP_E_EXCEPTION == hr) {
      error_description = exception.bstrDescription ? exception.bstrDescription : L"EUNEXPECTEDJSERROR";
      CComBSTR error_source(exception.bstrSource ? exception.bstrSource : L"EUNEXPECTEDJSERROR");
      LOG(INFO) << "Exception message was: '" << error_description << "'";
      LOG(INFO) << "Exception source was: '" << error_source << "'";
    } else {
      LOGHR(DEBUG, hr) << "Failed to execute anonymous function, no exception information retrieved";
    }

    result.Clear();
    result.vt = VT_BSTR;
    result.bstrVal = error_description;
    return_code = EUNEXPECTEDJSERROR;
  }

  this->result_.Copy(&result);

  return return_code;
}
コード例 #16
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
bool Script::ResultIsInteger() {
  LOG(TRACE) << "Entering Script::ResultIsInteger";
  return VariantUtilities::VariantIsInteger(this->result_);
}
コード例 #17
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
int Script::ExecuteAsync(int timeout_in_milliseconds) {
  LOG(TRACE) << "Entering Script::ExecuteAsync";
  int return_code = WD_SUCCESS;

  CComVariant result = L"";
  CComBSTR error_description = L"";

  AsyncScriptExecutorThreadContext thread_context;
  thread_context.script_source = this->source_code_.c_str();
  thread_context.script_argument_count = this->argument_count_;

  // We need exclusive access to this event. If it's already created,
  // OpenEvent returns non-NULL, so we need to wait a bit and retry
  // until OpenEvent returns NULL.
  int retry_counter = 50;
  HANDLE event_handle = ::OpenEvent(SYNCHRONIZE, FALSE, ASYNC_SCRIPT_EVENT_NAME);
  while (event_handle != NULL && --retry_counter > 0) {
    ::CloseHandle(event_handle);
    ::Sleep(50);
    event_handle = ::OpenEvent(SYNCHRONIZE, FALSE, ASYNC_SCRIPT_EVENT_NAME);
  }

  // Failure condition here.
  if (event_handle != NULL) {
    ::CloseHandle(event_handle);
    LOG(WARN) << "OpenEvent() returned non-NULL, event already exists.";
    result.Clear();
    result.vt = VT_BSTR;
    error_description = L"Couldn't create an event for synchronizing the creation of the thread. This generally means that you were trying to click on an option in two different instances.";
    result.bstrVal = error_description;
    this->result_.Copy(&result);
    return EUNEXPECTEDJSERROR;
  }

  LOG(DEBUG) << "Creating synchronization event for new thread";
  event_handle = ::CreateEvent(NULL, TRUE, FALSE, ASYNC_SCRIPT_EVENT_NAME);
  if (event_handle == NULL || ::GetLastError() == ERROR_ALREADY_EXISTS) {
    if (event_handle == NULL) {
      LOG(WARN) << "CreateEvent() failed.";
      error_description = L"Couldn't create an event for synchronizing the creation of the thread. This is an internal failure at the Windows OS level, and is generally not due to an error in the IE driver.";
    } else {
      ::CloseHandle(event_handle);
      LOG(WARN) << "Synchronization event is already created in another instance.";
      error_description = L"Couldn't create an event for synchronizing the creation of the thread. This generally means that you were trying to click on an option in multiple different instances.";
    }
    result.Clear();
    result.vt = VT_BSTR;
    result.bstrVal = error_description;
    this->result_.Copy(&result);
    return EUNEXPECTEDJSERROR;
  }

  // Start the thread and wait up to 1 second to be signaled that it is ready
  // to receive messages, then close the event handle.
  LOG(DEBUG) << "Starting new thread";
  unsigned int thread_id = 0;
  HANDLE thread_handle = reinterpret_cast<HANDLE>(_beginthreadex(NULL,
                                                  0,
                                                  AsyncScriptExecutor::ThreadProc,
                                                  reinterpret_cast<void*>(&thread_context),
                                                  0,
                                                  &thread_id));

  LOG(DEBUG) << "Waiting for new thread to be ready for messages";
  DWORD event_wait_result = ::WaitForSingleObject(event_handle, 5000);
  if (event_wait_result != WAIT_OBJECT_0) {
    LOG(WARN) << "Waiting for event to be signaled returned unexpected value: " << event_wait_result;
  }
  ::CloseHandle(event_handle);

  if (thread_handle == NULL) {
    LOG(WARN) << "_beginthreadex() failed.";
    result.Clear();
    result.vt = VT_BSTR;
    error_description = L"Couldn't create the thread for executing JavaScript asynchronously.";
    result.bstrVal = error_description;
    this->result_.Copy(&result);
    return EUNEXPECTEDJSERROR;
  }

  HWND executor_handle = thread_context.hwnd;

  // Marshal the document and the element to click to streams for use in another thread.
  LOG(DEBUG) << "Marshaling document to stream to send to new thread";
  LPSTREAM document_stream;
  HRESULT hr = ::CoMarshalInterThreadInterfaceInStream(IID_IHTMLDocument2, this->script_engine_host_, &document_stream);
  if (FAILED(hr)) {
    LOGHR(WARN, hr) << "CoMarshalInterfaceThreadInStream() for document failed";
    result.Clear();
    result.vt = VT_BSTR;
    error_description = L"Couldn't marshal the IHTMLDocument2 interface to a stream. This is an internal COM error.";
    result.bstrVal = error_description;
    this->result_.Copy(&result);
    return EUNEXPECTEDJSERROR;
  }

  ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_SET_DOCUMENT, NULL, reinterpret_cast<LPARAM>(document_stream));
  for (size_t index = 0; index < this->argument_array_.size(); ++index) {
    CComVariant arg = this->argument_array_[index];
    WPARAM wparam = static_cast<WPARAM>(arg.vt);
    LPARAM lparam = NULL;
    switch (arg.vt) {
      case VT_DISPATCH: {
        LPSTREAM dispatch_stream;
        hr = ::CoMarshalInterThreadInterfaceInStream(IID_IDispatch, arg.pdispVal, &dispatch_stream);
        if (FAILED(hr)) {
          LOGHR(WARN, hr) << "CoMarshalInterfaceThreadInStream() for IDispatch argument failed";
          result.Clear();
          result.vt = VT_BSTR;
          error_description = L"Couldn't marshal the IDispatch interface to a stream. This is an internal COM error.";
          result.bstrVal = error_description;
          this->result_.Copy(&result);
          return EUNEXPECTEDJSERROR;
        }
        lparam = reinterpret_cast<LPARAM>(dispatch_stream);
        break;
      }
      default: {
        // TODO: Marshal arguments of types other than VT_DISPATCH. At present,
        // the asynchronous execution of JavaScript is only used for Automation
        // Atoms on an element which take a single argument, an IHTMLElement
        // object, which is represented as an IDispatch. This case statement
        // will get much more complex should the need arise to execute
        // arbitrary scripts in an asynchronous manner.
      }
    }
    ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_SET_ARGUMENT, wparam, lparam);
  }
  ::PostMessage(executor_handle, WD_ASYNC_SCRIPT_EXECUTE, NULL, NULL);
  // We will wait a short bit and poll for the execution of the script to be
  // complete. This will allow us to say synchronous for short-running scripts
  // like clearing an input element, yet still be able to continue processing
  // when the script is blocked, as when an alert() window is present.
  LOG(TRACE) << "Waiting for async script execution to be complete";
  retry_counter = static_cast<int>(timeout_in_milliseconds / 10);
  bool is_execution_finished = ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_IS_EXECUTION_COMPLETE, NULL, NULL) != 0;
  while(!is_execution_finished && --retry_counter > 0) {
    ::Sleep(10);
    is_execution_finished = ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_IS_EXECUTION_COMPLETE, NULL, NULL) != 0;
  }

  if (is_execution_finished) {
    // TODO: Marshal the actual result from the AsyncScriptExecutor window
    // thread to this one. At present, the asynchronous execution of JavaScript
    // is only used for Automation Atoms on an element which could cause an
    // alert to appear (e.g., clear, click, or submit), and do not return any
    // return values back to the caller. In this case, the return code of the
    // execution method is sufficent. Marshaling the return will require two
    // more messages, one for determining the variant type of the return value,
    // and another for actually retrieving that value from the worker window's
    // thread.
    LOG(TRACE) << "Async script execution completed, getting result";
    int status_code = static_cast<int>(::SendMessage(executor_handle, WD_ASYNC_SCRIPT_GET_RESULT, NULL, NULL));
    return status_code;
  } else {
    LOG(TRACE) << "Async script execution not completed after timeout, detaching listener";
    ::SendMessage(executor_handle, WD_ASYNC_SCRIPT_DETACH_LISTENTER, NULL, NULL);
  }
  return WD_SUCCESS;
}
コード例 #18
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
bool Script::ResultIsDouble() {
  LOG(TRACE) << "Entering Script::ResultIsDouble";
  return VariantUtilities::VariantIsDouble(this->result_);
}
コード例 #19
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
void Script::AddArgument(const std::wstring& argument) {
  LOG(TRACE) << "Entering Script::AddArgument(std::wstring)";
  CComVariant dest_argument(argument.c_str());
  this->AddArgument(dest_argument);
}
コード例 #20
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
bool Script::ResultIsBoolean() {
  LOG(TRACE) << "Entering Script::ResultIsBoolean";
  return VariantUtilities::VariantIsBoolean(this->result_);
}
コード例 #21
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
void Script::AddArgument(const bool argument) {
  LOG(TRACE) << "Entering Script::AddArgument(bool)";
  CComVariant dest_argument(argument);
  this->AddArgument(dest_argument);
}
コード例 #22
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
bool Script::ResultIsIDispatch() {
  LOG(TRACE) << "Entering Script::ResultIsIDispatch";
  return VariantUtilities::VariantIsIDispatch(this->result_);
}
コード例 #23
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
void Script::AddArgument(IHTMLElement* argument) {
  LOG(TRACE) << "Entering Script::AddArgument(IHTMLElement*)";
  CComVariant dest_argument(argument);
  this->AddArgument(dest_argument);
}
コード例 #24
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
bool Script::ResultIsElementCollection() {
  LOG(TRACE) << "Entering Script::ResultIsElementCollection";
  return VariantUtilities::VariantIsElementCollection(this->result_);
}
コード例 #25
0
// Called before quitting
bool j1Input::CleanUp()
{
	LOG("Quitting SDL event subsystem");
	SDL_QuitSubSystem(SDL_INIT_EVENTS);
	return true;
}
コード例 #26
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
bool Script::ResultIsArray() {
  LOG(TRACE) << "Entering Script::ResultIsArray";
  return VariantUtilities::VariantIsArray(this->result_);
}
コード例 #27
0
ファイル: hid.c プロジェクト: adamruul/arduino-project
/* This function returns a newly allocated wide string containing the USB
   device string numbered by the index. The returned string must be freed
   by using free(). */
static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
{
	char buf[512];
	int len;
	wchar_t *str = NULL;
	wchar_t wbuf[256];

	/* iconv variables */
	iconv_t ic;
	size_t inbytes;
	size_t outbytes;
	size_t res;
	const char *inptr;
	char *outptr;

	/* Determine which language to use. */
	uint16_t lang;
	lang = get_usb_code_for_current_locale();
	if (!is_language_supported(dev, lang))
		lang = get_first_language(dev);

	/* Get the string from libusb. */
	len = libusb_get_string_descriptor(dev,
			idx,
			lang,
			(unsigned char*)buf,
			sizeof(buf));
	if (len < 0)
		return NULL;

	/* buf does not need to be explicitly NULL-terminated because
	   it is only passed into iconv() which does not need it. */

	/* Initialize iconv. */
	ic = iconv_open("WCHAR_T", "UTF-16LE");
	if (ic == (iconv_t)-1) {
		LOG("iconv_open() failed\n");
		return NULL;
	}

	/* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
	   Skip the first character (2-bytes). */
	inptr = buf+2;
	inbytes = len-2;
	outptr = (char*) wbuf;
	outbytes = sizeof(wbuf);
	res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
	if (res == (size_t)-1) {
		LOG("iconv() failed\n");
		goto err;
	}

	/* Write the terminating NULL. */
	wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
	if (outbytes >= sizeof(wbuf[0]))
		*((wchar_t*)outptr) = 0x00000000;

	/* Allocate and copy the string. */
	str = wcsdup(wbuf);

err:
	iconv_close(ic);

	return str;
}
コード例 #28
0
ファイル: Script.cpp プロジェクト: AlfZombie/selenium
bool Script::ResultIsObject() {
  LOG(TRACE) << "Entering Script::ResultIsObject";
  return VariantUtilities::VariantIsObject(this->result_);
}
コード例 #29
0
ファイル: hid.c プロジェクト: adamruul/arduino-project
static void read_callback(struct libusb_transfer *transfer)
{
	hid_device *dev = transfer->user_data;
	int res;

	if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {

		struct input_report *rpt = malloc(sizeof(*rpt));
		rpt->data = malloc(transfer->actual_length);
		memcpy(rpt->data, transfer->buffer, transfer->actual_length);
		rpt->len = transfer->actual_length;
		rpt->next = NULL;

		pthread_mutex_lock(&dev->mutex);

		/* Attach the new report object to the end of the list. */
		if (dev->input_reports == NULL) {
			/* The list is empty. Put it at the root. */
			dev->input_reports = rpt;
			pthread_cond_signal(&dev->condition);
		}
		else {
			/* Find the end of the list and attach. */
			struct input_report *cur = dev->input_reports;
			int num_queued = 0;
			while (cur->next != NULL) {
				cur = cur->next;
				num_queued++;
			}
			cur->next = rpt;

			/* Pop one off if we've reached 30 in the queue. This
			   way we don't grow forever if the user never reads
			   anything from the device. */
			if (num_queued > 30) {
				return_data(dev, NULL, 0);
			}
		}
		pthread_mutex_unlock(&dev->mutex);
	}
	else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
		dev->shutdown_thread = 1;
		return;
	}
	else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
		dev->shutdown_thread = 1;
		return;
	}
	else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
		//LOG("Timeout (normal)\n");
	}
	else {
		LOG("Unknown transfer code: %d\n", transfer->status);
	}

	/* Re-submit the transfer object. */
	res = libusb_submit_transfer(transfer);
	if (res != 0) {
		LOG("Unable to submit URB. libusb error code: %d\n", res);
		dev->shutdown_thread = 1;
	}
}
コード例 #30
0
ファイル: upd7759.c プロジェクト: cdrr/MAME_hack
static int find_sample(int num, int sample_num,struct UPD7759sample *sample)
{
	int j;
	int nextoff = 0;
	unsigned char *memrom;
	unsigned char *header;   /* upd7759 has a 4 byte what we assume is an identifier (bytes 1-4)*/
	unsigned char *data;


	memrom = memory_region(upd7759_intf->region[num]);

	numsam = (unsigned int)memrom[0]; /* get number of samples from sound rom */
	header = &(memrom[1]);

	if (memcmp (header, "\x5A\xA5\x69\x55",4) == 0)
	{
		LOG(1,(errorlog,"uPD7759 header verified\n"));
	}
	else
	{
		LOG(1,(errorlog,"uPD7759 header verification failed\n"));
	}

	LOG(1,(errorlog,"Number of samples in UPD7759 rom = %d\n",numsam));

	/* move the header pointer to the start of the sample offsets */
	header = &(memrom[5]);


	if (sample_num > numsam) return 0;	/* sample out of range */


	nextoff = 2 * sample_num;
	sample->offset = ((((unsigned int)(header[nextoff]))<<8)+(header[nextoff+1]))*2;
	data = &memory_region(upd7759_intf->region[num])[sample->offset];
	/* guesswork, probably wrong */
	j = 0;
	if (!data[j]) j++;
	if ((data[j] & 0xf0) != 0x50) j++;

	// Added and Modified by Takahiro Nogi. 1999/10/28
#if 0	// original
	switch (data[j])
	{
		case 0x53: sample->freq = 8000; break;
		case 0x59: sample->freq = 6000; break;
		case 0x5f: sample->freq = 5000; break;
		default:
			sample->freq = 5000;
	}
#else	// modified by Takahiro Nogi. 1999/10/28
	switch (data[j] & 0x1f)
	{
		case 0x13: sample->freq = 8000; break;
		case 0x19: sample->freq = 6000; break;
		case 0x1f: sample->freq = 5000; break;
		default:				// ???
			sample->freq = 5000;
	}
#endif

	if (sample_num == numsam)
	{
		sample->length = 0x20000 - sample->offset;
	}
	else
		sample->length = ((((unsigned int)(header[nextoff+2]))<<8)+(header[nextoff+3]))*2 -
							((((unsigned int)(header[nextoff]))<<8)+(header[nextoff+1]))*2;

if (errorlog)
{
	data = &memory_region(upd7759_intf->region[num])[sample->offset];
	fprintf( errorlog,"play sample %3d, offset $%06x, length %5d, freq = %4d [data $%02x $%02x $%02x]\n",
		sample_num,
		sample->offset,
		sample->length,
		sample->freq,
		data[0],data[1],data[2]);
}

	return 1;
}