Example #1
0
///////////////////////////////
// YieldingFlexibleGangWorker
///////////////////////////////
void YieldingFlexibleGangWorker::loop() {
  int previous_sequence_number = 0;
  Monitor* gang_monitor = gang()->monitor();
  MutexLockerEx ml(gang_monitor, Mutex::_no_safepoint_check_flag);
  WorkData data;
  int id;
  while (true) {
    // Check if there is work to do or if we have been asked
    // to terminate
    gang()->internal_worker_poll(&data);
    if (data.terminate()) {
      // We have been asked to terminate.
      assert(gang()->task() == NULL, "No task binding");
      // set_status(TERMINATED);
      return;
    } else if (data.task() != NULL &&
               data.sequence_number() != previous_sequence_number) {
      // There is work to be done.
      // First check if we need to become active or if there
      // are already the requisite number of workers
      if (gang()->started_workers() == yf_gang()->active_workers()) {
        // There are already enough workers, we do not need to
        // to run; fall through and wait on monitor.
      } else {
        // We need to pitch in and do the work.
        assert(gang()->started_workers() < yf_gang()->active_workers(),
               "Unexpected state");
        id = gang()->started_workers();
        gang()->internal_note_start();
        // Now, release the gang mutex and do the work.
        {
          MutexUnlockerEx mul(gang_monitor, Mutex::_no_safepoint_check_flag);
          data.task()->work(id);   // This might include yielding
        }
        // Reacquire monitor and note completion of this worker
        gang()->internal_note_finish();
        // Update status of task based on whether all workers have
        // finished or some have yielded
        assert(data.task() == gang()->task(), "Confused task binding");
        if (gang()->finished_workers() == yf_gang()->active_workers()) {
          switch (data.yf_task()->status()) {
            case ABORTING: {
              data.yf_task()->set_status(ABORTED);
              break;
            }
            case ACTIVE:
            case COMPLETING: {
              data.yf_task()->set_status(COMPLETED);
              break;
            }
            default:
              ShouldNotReachHere();
          }
          gang_monitor->notify_all();  // Notify overseer
        } else { // at least one worker is still working or yielded
          assert(gang()->finished_workers() < yf_gang()->active_workers(),
                 "Counts inconsistent");
          switch (data.yf_task()->status()) {
            case ACTIVE: {
              // first, but not only thread to complete
              data.yf_task()->set_status(COMPLETING);
              break;
            }
            case YIELDING: {
              if (gang()->finished_workers() + yf_gang()->yielded_workers()
                  == yf_gang()->active_workers()) {
                data.yf_task()->set_status(YIELDED);
                gang_monitor->notify_all();  // notify overseer
              }
              break;
            }
            case ABORTING:
            case COMPLETING: {
              break; // nothing to do
            }
            default: // everything else: INACTIVE, YIELDED, ABORTED, COMPLETED
              ShouldNotReachHere();
          }
        }
      }
    }
    // Remember the sequence number
    previous_sequence_number = data.sequence_number();
    // Wait for more work
    gang_monitor->wait(Mutex::_no_safepoint_check_flag);
  }
}
/*! Returns the sort ordering that will be used sort the results of this request
*/
QList<QContactSortOrder> QContactFetchRequest::sorting() const
{
    Q_D(const QContactFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    return d->m_sorting;
}
/*! Returns the list of contacts retrieved by this request
*/
QList<QContact> QContactFetchRequest::contacts() const
{
    Q_D(const QContactFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    return d->m_contacts;
}
/*!
  Sets the contact filter used to determine which contacts will be retrieved to \a filter.
*/
void QContactFetchRequest::setFilter(const QContactFilter& filter)
{
    Q_D(QContactFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    d->m_filter = filter;
}
/*!
  Sets the fetch hint which may be used by the backend to optimize contact retrieval
  to \a fetchHint.  A client should not make changes to a contact which has been retrieved
  using a fetch hint other than the default fetch hint.  Doing so will result in information
  loss when saving the contact back to the manager (as the "new" restricted contact will
  replace the previously saved contact in the backend).
  \sa QContactFetchHint
 */
void QContactFetchRequest::setFetchHint(const QContactFetchHint &fetchHint)
{
    Q_D(QContactFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    d->m_fetchHint = fetchHint;
}
void Debug::clearHasNewError() {
  QMutexLocker ml(&_lock);
  _hasNewError = false;
}
Example #7
0
boolean Graphic31::intersects_gs (BoxObj& userb, Graphic31* gs) { 
    Coord* convx, *convy;
    Coord ll, bb, rr, tt;
    getbounds_gs(ll, bb, rr, tt, gs);
    BoxObj b(ll, bb, rr, tt);;
    boolean result = false;

    if (!_curved && !_fill) {
        if (b.Intersects(userb)) {
            convx = new Coord[_ctrlpts+1];
            convy = new Coord[_ctrlpts+1];
            Xform_gs(_x, _y, _ctrlpts, convx, convy, gs);
            if (_closed) {
                convx[_ctrlpts] = *convx;
                convy[_ctrlpts] = *convy;
                MultiLineObj ml(convx, convy, _ctrlpts+1);
                result = ml.Intersects(userb);
            } else {
                MultiLineObj ml(convx, convy, _ctrlpts);
                result = ml.Intersects(userb);
            }
            delete convx;
            delete convy;
        }
        return result;

    } else if (!_curved && _fill) {
        if (b.Intersects(userb)) {
            convx = new Coord[_ctrlpts];
            convy = new Coord[_ctrlpts];
            Xform_gs(_x, _y, _ctrlpts, convx, convy, gs);
            FillPolygonObj fp (convx, convy, _ctrlpts);
            result = fp.Intersects(userb);
            delete convx;
            delete convy;
        }
        return result;    

    } else if (_curved && !_fill) {
        if (b.Intersects(userb)) {
            convx = new Coord[_ctrlpts];
            convy = new Coord[_ctrlpts];
            Xform_gs(_x, _y, _ctrlpts, convx, convy, gs);
            MultiLineObj ml;
            if (_closed) {
                ml.ClosedSplineToPolygon(convx, convy, _ctrlpts);
            } else {
                ml.SplineToMultiLine(convx, convy, _ctrlpts);
            }
            result = ml.Intersects(userb);
            delete convx;
            delete convy;
        }
        return result;

    } else {
        if (b.Intersects(userb)) {
            convx = new Coord[_ctrlpts];
            convy = new Coord[_ctrlpts];
            Xform_gs(_x, _y, _ctrlpts, convx, convy, gs);
            FillPolygonObj fp;
            fp.ClosedSplineToPolygon(convx, convy, _ctrlpts);
            result = fp.Intersects(userb);
            delete convx;
            delete convy;
        }
        return result;
    }
}
/*! Sets the filter which will be used to select the organizer items whose ids will be returned to \a filter
    \since 1.1
*/
void QOrganizerItemIdFetchRequest::setFilter(const QOrganizerItemFilter& filter)
{
    Q_D(QOrganizerItemIdFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    d->m_filter = filter;
}
/*! Sets the future sort ordering of the result of the request to \a sorting.  This function only has
    effect on the result if called prior to calling \c start()
    \since 1.1
*/
void QOrganizerItemIdFetchRequest::setSorting(const QList<QOrganizerItemSortOrder>& sorting)
{
    Q_D(QOrganizerItemIdFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    d->m_sorting = sorting;
}
/*!
   Returns the date-time which is the upper bound for the range for items whose ids will be returned.
   An invalid (default-constructed) date-time signifies that no upper bound is given (matches everything
   after the start date).
   Note that an item matches if either it or any of its occurrences occur within the defined range.
   \since 1.1
 */
QDateTime QOrganizerItemIdFetchRequest::endDate() const
{
    Q_D(const QOrganizerItemIdFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    return d->m_endDate;
}
/*! Returns the list of ids of organizer items which matched the request
    \since 1.1
*/
QList<QOrganizerItemId> QOrganizerItemIdFetchRequest::itemIds() const
{
    Q_D(const QOrganizerItemIdFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    return d->m_ids;
}
/*! Returns the sort ordering which will be used to sort the result
    \since 1.1
*/
QList<QOrganizerItemSortOrder> QOrganizerItemIdFetchRequest::sorting() const
{
    Q_D(const QOrganizerItemIdFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    return d->m_sorting;
}
/*! Returns the filter which will be used to select the organizer items whose ids will be returned
    \since 1.1
*/
QOrganizerItemFilter QOrganizerItemIdFetchRequest::filter() const
{
    Q_D(const QOrganizerItemIdFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    return d->m_filter;
}
/*!
   Sets the date-time which is the upper bound for the range for items whose ids will be returned to \a date.
   An invalid (default-constructed) date-time signifies that no upper bound is given (matches everything
   after the start date).
   Note that an item matches if either it or any of its occurrences occur within the defined range.
   \since 1.1
 */
void QOrganizerItemIdFetchRequest::setEndDate(const QDateTime &date)
{
    Q_D(QOrganizerItemIdFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    d->m_endDate = date;
}
Example #15
0
const QString& Debug::kstRevision() const {
  QMutexLocker ml(&_lock);
  return _kstRevision;
}
Example #16
0
//------------------------------------------------------------------------------
// Main entry point to this program
//------------------------------------------------------------------------------
int main(int argc, char** argv)
{
	int c;
	bool clearLockOnly = false;
	bool rollbackOnly  = false;
	uint32_t tableOID  = 0;

	while ((c = getopt(argc, argv, "hlr:")) != EOF)
	{
		switch (c)
		{
			case 'l':
				clearLockOnly = true;
				break;
//Only allow '-r' option for development/debugging
#if 1
			case 'r': // hidden option to rollback specified table w/o a lock
				rollbackOnly  = true;
				tableOID      = ::strtoull(optarg, 0, 10);
				break;
#endif
			case 'h':
			case '?':
			default:
				usage();
				return (c == 'h' ? 0 : 1);
				break;
		}
	}

	if ((argc - optind) != 1 )
	{
		usage();
		return 1;
	}

	// Get the table lock ID specified by the user
	uint64_t lockID = ::strtoull(argv[optind], 0, 10);

	// If user specified both clearlock and rollback then we need to do both
	if (clearLockOnly && rollbackOnly)
	{
		clearLockOnly = false;
		rollbackOnly  = false;
	}

	//--------------------------------------------------------------------------
	// Verify that BRM is up and in a read/write state
	//--------------------------------------------------------------------------
	BRM::DBRM brm;
	int brmRc = brm.isReadWrite();
	if (brmRc != BRM::ERR_OK)
	{
		std::string brmErrMsg;
		BRM::errString(brmRc, brmErrMsg);
		std::cout << "BRM error: " << brmErrMsg << std::endl;
		std::cout << "Table lock " << lockID << " is not cleared." << std::endl;
		return 1;
	}

	if (brm.getSystemReady() < 1)
	{
		std::cout << "System is not ready.  Verify that EryDB "
			"is up and ready before running this program" << std::endl;
		return 1;
	}

	//--------------------------------------------------------------------------
	//@Bug 3711 Check whether the table is locked; does the table lock exist.
	//--------------------------------------------------------------------------
	execplan::erydbSystemCatalog::TableName tblName;
	BRM::TableLockInfo tInfo;
	std::string task;
	std::vector<uint32_t> pmList;
	int rc;
	const std::string taskSysCat("getting system catalog information");
	try {
		if (rollbackOnly)
		{
			tInfo.id             = lockID;
			tInfo.tableOID       = tableOID;
			tInfo.ownerPID       = 0;
			tInfo.ownerSessionID = 1;
			tInfo.state          = BRM::LOADING;

			// Construct PM list using all PMs, since we don't have a table
			// lock with the list of applicable DBRoots.
			task = "constructing total PM list";
			rc = constructPMList( pmList );
			if (rc != 0)
			{
				return 1;
			}
		}
		else
		{
			task = "getting table lock";
   			bool lockExists = brm.getTableLockInfo( lockID, &tInfo );
   			if (!lockExists)
			{
				std::cout << "Table lock " << lockID << " does not exist." <<
					std::endl;
				return 1;
			}

			// Construct PM list based on list of affected DBRoots
			task = "mapping DBRoots to PMs";
			rc = constructPMList( tInfo.dbrootList, pmList );
			if (rc != 0)
			{
				return 1;
			}
		}

		uint32_t sessionID = 1;
		task = taskSysCat;
		boost::shared_ptr<execplan::erydbSystemCatalog> systemCatalogPtr =
			execplan::erydbSystemCatalog::makeerydbSystemCatalog(
				sessionID );
		systemCatalogPtr->identity(execplan::erydbSystemCatalog::EC);
		tblName = systemCatalogPtr->tableName( tInfo.tableOID );
	}
	catch (std::exception& ex)
	{
		std::cout << "Error " << task << ".  " << ex.what() << std::endl;
		if (clearLockOnly && (task == taskSysCat))
		{
			tblName.schema= "[unknown name]";
			tblName.table.clear();
			std::cout << "Will still try to clear table lock." << std::endl;
		}
		else
		{
			std::cout << "Table lock " << lockID << " is not cleared." <<
				std::endl;
			return 1;
		}
	}
	catch (...)
	{
		std::cout << "Error " << task << ".  " << std::endl;
		if (clearLockOnly && (task == taskSysCat))
		{
			tblName.schema= "[unknown name]";
			tblName.table.clear();
			std::cout << "Will still try to clear table lock." << std::endl;
		}
		else
		{
			std::cout << "Table lock " << lockID << " is not cleared." <<
				std::endl;
			return 1;
		}
	}

	logInitStatus( tblName.toString(), lockID );
	if (rollbackOnly)
	{
		std::cout << "Rolling back table " << tblName.toString() <<
			std::endl << std::endl;
	}
	else if (clearLockOnly)
	{
		std::cout << "Clearing table lock " << lockID <<
			" for table " << tblName.toString() << std::endl << std::endl;
	}
	else
	{
		std::cout << "Rolling back and clearing table lock for table " <<
			tblName.toString() << "; table lock " << lockID <<
			std::endl << std::endl;
	}

	//--------------------------------------------------------------------------
	// Perform bulk rollback
	//--------------------------------------------------------------------------
	std::string errMsg;
	if (!clearLockOnly)
	{
		std::vector<boost::shared_ptr<messageqcpp::MessageQueueClient> >
			msgQueClts;
		rc = createMsgQueClts(pmList, msgQueClts, errMsg);
		if (rc != 0)
		{
			logFinalStatus( tblName.toString(), lockID, errMsg );
			std::cout << errMsg << std::endl;
			std::cout << "Table lock " << lockID << " for table " <<
				tblName.toString() << " is not cleared." << std::endl;
			return rc;
		}

		rc = execBulkRollbackReq( msgQueClts, pmList,
			&brm, tInfo, tblName.toString(), rollbackOnly, errMsg );
		if (rc != 0)
		{
			logFinalStatus( tblName.toString(), lockID, errMsg );
			std::cout << "Rollback error: " << errMsg << std::endl;
			std::cout << "Table lock " << lockID << " for table " <<
				tblName.toString() << " is not cleared." << std::endl;
			return rc;
		}

		//----------------------------------------------------------------------
		// Change the state of the table lock to cleanup state.
		// We ignore the return stateChange flag.
		//----------------------------------------------------------------------
		if (!rollbackOnly)
		{
			try {
				brm.changeState( tInfo.id, BRM::CLEANUP );
			}
			catch (std::exception& ex)
			{
				std::ostringstream oss;
				oss << "Error changing state.  " << ex.what();
				logFinalStatus( tblName.toString(), lockID, oss.str() );
				std::cout << oss.str() << std::endl;
				std::cout << "Table lock " << lockID << " is not cleared." <<
					std::endl;
				return 1;
			}
			catch (...)
			{
				std::ostringstream oss;
				oss << "Error changing state.  " << std::endl;
				logFinalStatus( tblName.toString(), lockID, oss.str() );
				std::cout << oss.str() << std::endl;
				std::cout << "Table lock " << lockID << " is not cleared." <<
					std::endl;
				return 1;
			}
		}

		//----------------------------------------------------------------------
		// Delete the meta data files
		//----------------------------------------------------------------------
		rc = execFileCleanupReq( msgQueClts, pmList,
			&brm, tInfo, tblName.toString(), errMsg );
		if (rc != 0)
		{
			//@Bug 4517. Release tablelock if remove meta files failed
			const std::string APPLNAME("cleartablelock command");
			const int SUBSYSTEM_ID = 19; // writeengine?
			const int COMP_MSG_NUM = logging::M0089;
			logging::Message::Args msgArgs;
			logging::Message logMsg( COMP_MSG_NUM );
			msgArgs.add( APPLNAME );
			msgArgs.add( tblName.toString() );
			msgArgs.add( lockID );
			msgArgs.add( errMsg );
			logMsg.format( msgArgs );
			logging::LoggingID  lid( SUBSYSTEM_ID );
			logging::MessageLog ml( lid );
			ml.logWarningMessage( logMsg );
			
			std::cout << "File cleanup error: " << errMsg << std::endl;
		}
	} // end of: if (!clearLockOnly)

	//--------------------------------------------------------------------------
	// Finally, release the actual table lock
	//--------------------------------------------------------------------------
	std::cout << std::endl;
	if (rollbackOnly)
	{
		logFinalStatus( tblName.toString(), lockID, std::string() );
		std::cout << "Bulk Rollback Only for table " << tblName.toString() <<
			" completed successfully." << std::endl;
	}
	else
	{
		try {
			brm.releaseTableLock( lockID ); // ignore boolean return value
		}
		catch (std::exception& ex)
		{
			logFinalStatus( tblName.toString(), lockID, ex.what() );
			std::cout << "Error releasing table lock " << lockID <<
				" for table " << tblName.toString() << std::endl;
			std::cout << ex.what() << std::endl;
			return 1;
		}
		catch (...)
		{
			std::string unknownErr("Unknown exception");
			logFinalStatus( tblName.toString(), lockID, unknownErr );
			std::cout << "Error releasing table lock " << lockID <<
				" for table " << tblName.toString() << std::endl;
			std::cout << unknownErr << std::endl;
			return 1;
		}

		logFinalStatus( tblName.toString(), lockID, std::string() );
		std::cout << "Table lock " << lockID << " for table " <<
			tblName.toString() << " is cleared." << std::endl;
	}
	
	return 0;
}
Example #17
0
bool Debug::hasNewError() const {
  QMutexLocker ml(&_lock);
  return _hasNewError;
}
Example #18
0
// ------------------------------------------------------------------
// ciEnv::get_klass_by_name_impl
ciKlass* ciEnv::get_klass_by_name_impl(ciKlass* accessing_klass,
                                       constantPoolHandle cpool,
                                       ciSymbol* name,
                                       bool require_local) {
  ASSERT_IN_VM;
  EXCEPTION_CONTEXT;

  // Now we need to check the SystemDictionary
  Symbol* sym = name->get_symbol();
  if (sym->byte_at(0) == 'L' &&
    sym->byte_at(sym->utf8_length()-1) == ';') {
    // This is a name from a signature.  Strip off the trimmings.
    // Call recursive to keep scope of strippedsym.
    TempNewSymbol strippedsym = SymbolTable::new_symbol(sym->as_utf8()+1,
                    sym->utf8_length()-2,
                    KILL_COMPILE_ON_FATAL_(_unloaded_ciinstance_klass));
    ciSymbol* strippedname = get_symbol(strippedsym);
    return get_klass_by_name_impl(accessing_klass, cpool, strippedname, require_local);
  }

  // Check for prior unloaded klass.  The SystemDictionary's answers
  // can vary over time but the compiler needs consistency.
  ciKlass* unloaded_klass = check_get_unloaded_klass(accessing_klass, name);
  if (unloaded_klass != NULL) {
    if (require_local)  return NULL;
    return unloaded_klass;
  }

  Handle loader(THREAD, (oop)NULL);
  Handle domain(THREAD, (oop)NULL);
  if (accessing_klass != NULL) {
    loader = Handle(THREAD, accessing_klass->loader());
    domain = Handle(THREAD, accessing_klass->protection_domain());
  }

  // setup up the proper type to return on OOM
  ciKlass* fail_type;
  if (sym->byte_at(0) == '[') {
    fail_type = _unloaded_ciobjarrayklass;
  } else {
    fail_type = _unloaded_ciinstance_klass;
  }
  KlassHandle found_klass;
  {
    ttyUnlocker ttyul;  // release tty lock to avoid ordering problems
    MutexLocker ml(Compile_lock);
    Klass* kls;
    if (!require_local) {
      kls = SystemDictionary::find_constrained_instance_or_array_klass(sym, loader,
                                                                       KILL_COMPILE_ON_FATAL_(fail_type));
    } else {
      kls = SystemDictionary::find_instance_or_array_klass(sym, loader, domain,
                                                           KILL_COMPILE_ON_FATAL_(fail_type));
    }
    found_klass = KlassHandle(THREAD, kls);
  }

  // If we fail to find an array klass, look again for its element type.
  // The element type may be available either locally or via constraints.
  // In either case, if we can find the element type in the system dictionary,
  // we must build an array type around it.  The CI requires array klasses
  // to be loaded if their element klasses are loaded, except when memory
  // is exhausted.
  if (sym->byte_at(0) == '[' &&
      (sym->byte_at(1) == '[' || sym->byte_at(1) == 'L')) {
    // We have an unloaded array.
    // Build it on the fly if the element class exists.
    TempNewSymbol elem_sym = SymbolTable::new_symbol(sym->as_utf8()+1,
                                                 sym->utf8_length()-1,
                                                 KILL_COMPILE_ON_FATAL_(fail_type));

    // Get element ciKlass recursively.
    ciKlass* elem_klass =
      get_klass_by_name_impl(accessing_klass,
                             cpool,
                             get_symbol(elem_sym),
                             require_local);
    if (elem_klass != NULL && elem_klass->is_loaded()) {
      // Now make an array for it
      return ciObjArrayKlass::make_impl(elem_klass);
    }
  }

  if (found_klass() == NULL && !cpool.is_null() && cpool->has_preresolution()) {
    // Look inside the constant pool for pre-resolved class entries.
    for (int i = cpool->length() - 1; i >= 1; i--) {
      if (cpool->tag_at(i).is_klass()) {
        Klass* kls = cpool->resolved_klass_at(i);
        if (kls->name() == sym) {
          found_klass = KlassHandle(THREAD, kls);
          break;
        }
      }
    }
  }

  if (found_klass() != NULL) {
    // Found it.  Build a CI handle.
    return get_klass(found_klass());
  }

  if (require_local)  return NULL;

  // Not yet loaded into the VM, or not governed by loader constraints.
  // Make a CI representative for it.
  return get_unloaded_klass(accessing_klass, name);
}
Example #19
0
int Debug::limit() const {
  QMutexLocker ml(&_lock);
  return _limit;
}
Example #20
0
void* myNew(size_t size, const char* file, int line)
{
#ifdef USE_CPLUSPLUS_11_MUTEX
  std::lock_guard<std::mutex> lg(GetMutex());
#else
  Amju::MutexLocker ml(GetMutex());
#endif

  // We have to allow allocations of size 0.
  // To make sure this works OK with malloc, change size to 1 in this case.
  // TODO Also print warning ?
  if (size == 0)
  {
    size = 1;
  }

  void* p = malloc(size);

  assert(depth >= 0);

  ++depth;
  if (ready && depth == 1)
  {

    currentAlloc++;

    if (breakId == currentAlloc)
    {
      // Break - use assert by default, or TODO allow another function to be set
      std::cout << "Mem: debug break on ID: " << breakId << "\n";
      myBreaker.Break(); 
    }

    if (breakSize && breakSize == size)
    {
      // Break on allocation of this size
      // TODO Allow another function to be called now
      std::cout << "Mem: debug break on size: " << size << "\n";
      myBreaker.Break(); 
    }

    totalMemAllocated += size;
    if (totalMemAllocated > maxMemAllocated)
    {
      maxMemAllocated = totalMemAllocated;
    }

    // Check that total is under a limit if set
    if (limit && totalMemAllocated > limit)
    {
      // Break - TODO allow another function ?
      std::cout << "Mem: over limit! Limit: " << limit << " total now: " << totalMemAllocated << "\n";
      myBreaker.Break(); 
    }

    // Avoid [] so we don't need default ctor
    std::pair<void*, Allocation> kv = 
      std::make_pair(p, 
      Allocation(size, p, currentAlloc, file, line, 
      Amju::CallStack::Instance()->GetFunctionNames()));

    AllocMgr::Instance()->allocMap.insert(kv);

  }

  assert(depth >= 0);
  --depth;

  return p;
}
Example #21
0
HeapWord* PermGen::mem_allocate_in_gen(size_t size, Generation* gen) {
  GCCause::Cause next_cause = GCCause::_permanent_generation_full;
  GCCause::Cause prev_cause = GCCause::_no_gc;
  unsigned int gc_count_before, full_gc_count_before;
  HeapWord* obj;

  for (;;) {
    {
      MutexLocker ml(Heap_lock);
      if ((obj = gen->allocate(size, false)) != NULL) {
        return obj;
      }
      if (gen->capacity() < _capacity_expansion_limit ||
          prev_cause != GCCause::_no_gc) {
        obj = gen->expand_and_allocate(size, false);
      }
      if (obj != NULL || prev_cause == GCCause::_last_ditch_collection) {
        return obj;
      }
      if (GC_locker::is_active_and_needs_gc()) {
        // If this thread is not in a jni critical section, we stall
        // the requestor until the critical section has cleared and
        // GC allowed. When the critical section clears, a GC is
        // initiated by the last thread exiting the critical section; so
        // we retry the allocation sequence from the beginning of the loop,
        // rather than causing more, now probably unnecessary, GC attempts.
        JavaThread* jthr = JavaThread::current();
        if (!jthr->in_critical()) {
          MutexUnlocker mul(Heap_lock);
          // Wait for JNI critical section to be exited
          GC_locker::stall_until_clear();
          continue;
        } else {
          if (CheckJNICalls) {
            fatal("Possible deadlock due to allocating while"
                  " in jni critical section");
          }
          return NULL;
        }
      }
      // Read the GC count while holding the Heap_lock
      gc_count_before      = SharedHeap::heap()->total_collections();
      full_gc_count_before = SharedHeap::heap()->total_full_collections();
    }

    // Give up heap lock above, VMThread::execute below gets it back
    VM_GenCollectForPermanentAllocation op(size, gc_count_before, full_gc_count_before,
                                           next_cause);
    VMThread::execute(&op);
    if (!op.prologue_succeeded() || op.gc_locked()) {
      assert(op.result() == NULL, "must be NULL if gc_locked() is true");
      continue;  // retry and/or stall as necessary
    }
    obj = op.result();
    assert(obj == NULL || SharedHeap::heap()->is_in_reserved(obj),
           "result not in heap");
    if (obj != NULL) {
      return obj;
    }
    prev_cause = next_cause;
    next_cause = GCCause::_last_ditch_collection;
  }
}
Example #22
0
bool MediaLibrary::Start()
{
    if ( m_ml != nullptr )
        return true;

    std::unique_ptr<medialibrary::IMediaLibrary> ml( NewMediaLibrary() );

    m_logger.reset( new Logger( VLC_OBJECT( m_vlc_ml ) ) );
    ml->setVerbosity( medialibrary::LogLevel::Info );
    ml->setLogger( m_logger.get() );

    auto userDir = vlc::wrap_cptr( config_GetUserDir( VLC_USERDATA_DIR ) );
    std::string mlDir = std::string{ userDir.get() } + "/ml/";
    auto thumbnailsDir = mlDir + "thumbnails/";

    auto initStatus = ml->initialize( mlDir + "ml.db", thumbnailsDir, this );
    switch ( initStatus )
    {
        case medialibrary::InitializeResult::AlreadyInitialized:
            msg_Info( m_vlc_ml, "MediaLibrary was already initialized" );
            return true;
        case medialibrary::InitializeResult::Failed:
            msg_Err( m_vlc_ml, "Medialibrary failed to initialize" );
            return false;
        case medialibrary::InitializeResult::DbReset:
            msg_Info( m_vlc_ml, "Database was reset" );
            break;
        case medialibrary::InitializeResult::Success:
            msg_Dbg( m_vlc_ml, "MediaLibrary successfully initialized" );
            break;
    }

    ml->addParserService( std::make_shared<MetadataExtractor>( VLC_OBJECT( m_vlc_ml ) ) );
    try
    {
        ml->addThumbnailer( std::make_shared<Thumbnailer>(
                                m_vlc_ml, std::move( thumbnailsDir ) ) );
    }
    catch ( const std::runtime_error& ex )
    {
        msg_Err( m_vlc_ml, "Failed to provide a thumbnailer module to the "
                 "medialib: %s", ex.what() );
        return false;
    }
    if ( ml->start() == false )
    {
        msg_Err( m_vlc_ml, "Failed to start the MediaLibrary" );
        return false;
    }

    // Reload entry points we already know about, and then add potential new ones.
    // Doing it the other way around would cause the initial scan to be performed
    // twice, as we start discovering the new folders, then reload them.
    ml->reload();

    auto folders = vlc::wrap_cptr( var_InheritString( m_vlc_ml, "ml-folders" ) );
    if ( folders != nullptr && strlen( folders.get() ) > 0 )
    {
        std::istringstream ss( folders.get() );
        std::string folder;
        while ( std::getline( ss, folder, ';' ) )
            ml->discover( folder );
    }
    else
    {
        std::string varValue;
        for( auto&& target : { VLC_VIDEOS_DIR, VLC_MUSIC_DIR } )
        {
            auto folder = vlc::wrap_cptr( config_GetUserDir( target ) );
            if( folder == nullptr )
                continue;
            auto folderMrl = vlc::wrap_cptr( vlc_path2uri( folder.get(), nullptr ) );
            ml->discover( folderMrl.get() );
            varValue += std::string{ ";" } + folderMrl.get();
        }
        if ( varValue.empty() == false )
            config_PutPsz( "ml-folders", varValue.c_str()+1 ); /* skip initial ';' */
    }
    m_ml = std::move( ml );
    return true;
}
Example #23
0
/*! Sets the sort order of the result to \a sorting.  Only has an effect if called prior to calling \c start()
*/
void QContactFetchRequest::setSorting(const QList<QContactSortOrder>& sorting)
{
    Q_D(QContactFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    d->m_sorting = sorting;
}
Example #24
0
void Debug::setLimit(bool applyLimit, int limit) {
  QMutexLocker ml(&_lock);
  _applyLimit = applyLimit;
  _limit = limit;
}
Example #25
0
/*! Returns the filter that will be used to select contacts to be returned
*/
QContactFilter QContactFetchRequest::filter() const
{
    Q_D(const QContactFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    return d->m_filter;
}
Example #26
0
QList<Debug::LogMessage> Debug::messages() const {
  QMutexLocker ml(&_lock);
  return _messages;
}
Example #27
0
/*!
  Returns the fetch hint which may be used by the backend to optimize contact retrieval.
  A client should not make changes to a contact which has been retrieved
  using a fetch hint other than the default fetch hint.  Doing so will result in information
  loss when saving the contact back to the manager (as the "new" restricted contact will
  replace the previously saved contact in the backend).
  \sa QContactFetchHint
 */
QContactFetchHint QContactFetchRequest::fetchHint() const
{
    Q_D(const QContactFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    return d->m_fetchHint;
}
Example #28
0
int Debug::logLength() const {
  QMutexLocker ml(&_lock);
  return _messages.size();
}
Example #29
0
/*!
  Sets the storage location from where the contacts will be retrieved.

  \a storageLocations is a flag so it is possible to define multiple locations in it.
  However, some backend implementations may accept only one flag to be set. In case multiple
  flags are set fetching is done from the default storage location.
  \sa QContactAbstractRequest::StorageLocation
  \sa QContactAbstractRequest::StorageLocations
 */
void QContactFetchRequest::setStorageLocations(QContactAbstractRequest::StorageLocations storageLocations)
{
    Q_D(QContactFetchRequest);
    QMutexLocker ml(&d->m_mutex);
    d->m_storageLocations = storageLocations;
}
Example #30
0
void FileScanner::Run(int thread_index)
{
	// Set the name of the thread.
	std::stringstream temp_ss;
	temp_ss << "FILESCAN_";
	temp_ss << thread_index;
	set_thread_name(temp_ss.str());

	if(m_manually_assign_cores)
	{
		// Spread the scanner threads across cores.  Linux at least doesn't seem to want to do that by default.
		AssignToNextCore();
	}

	// Create a reusable, resizable buffer for the File() reads.
	auto file_data_storage = std::make_shared<ResizableArray<char>>();

	// Pull new filenames off the input queue until it's closed.
	std::string next_string;
	while(m_in_queue.wait_pull(std::move(next_string)) != queue_op_status::closed)
	{
		MatchList ml(next_string);

		try
		{
			// Try to open and read the file.  This could throw.
			LOG(INFO) << "Attempting to scan file \'" << next_string << "\'";
			File f(next_string, file_data_storage);

			if(f.size() == 0)
			{
				LOG(INFO) << "WARNING: Filesize of \'" << next_string << "\' is 0, skipping.";
				continue;
			}

			const char *file_data = f.data();
			size_t file_size = f.size();

			// Scan the file data for occurrences of the regex, sending matches to the MatchList ml.
			ScanFile(file_data, file_size, ml);

			if(!ml.empty())
			{
				// Force move semantics here.
				m_output_queue.wait_push(std::move(ml));
			}
		}
		catch(const FileException &error)
		{
			// The File constructor threw an exception.
			ERROR() << error.what();
		}
		catch(const std::system_error& error)
		{
			// A system error.  Currently should only be errors from File.
			ERROR() << error.code() << " - " << error.code().message();
		}
		catch(...)
		{
			// Rethrow whatever it was.
			throw;
		}
	}
}