//---------------------------------------------------------
void managed_shm()
{
	{
		boost::interprocess::managed_shared_memory shm(boost::interprocess::open_or_create, "base_shm_00", boost::interprocess::read_write); 

		int* p_00=shm.construct<int>("obj_00")(99); 
		assert(*p_00==99);

		std::pair<int*, std::size_t> p_01=shm.find<int>("obj_00");
		assert(*p_01.first==99);

		assert(shm.find<int>("unknown").first==0);
		assert(shm.find<int>("unknown").second==0);

		int *i = shm.construct<int>("obj_01")[10](99); //array of 10 elts
		//all 10 elts are initialized with the value 99.
		//It is not possible to initialize individual elements with different values.
		assert(*i==99);
		std::pair<int*, std::size_t> p=shm.find<int>("obj_01"); 
		assert(*p.first==99);
		assert(p.second==10);

		assert(boost::interprocess::shared_memory_object::remove("base_shm_00"));
	}
}
Example #2
0
File: main.c Project: diegohdorta/C
int main(void) 
{
	unsigned int count;     
	pid_t pid = ONE;
	pid_t pids[NO_OF_CHILDREN];
	
	init();
	shm();

	for(count = 0; count < NO_OF_CHILDREN; count++) {
	
		if (pid) {
		
			if ((pid = fork()) < 0) {
				fprintf(stderr, "The fork() function has failed: %s", strerror(errno));
				return EXIT_FAILURE;
			}
			
			pids[count] = pid;
								
			if (pid)
				fprintf(stderr, "%d # Created pid process: %d\n", getpid(), (pids[count]));
		}
		
		else
			break;
	}

	if (!pid) {
	
		fprintf(stderr, "Child %i started...\n", count);

		if (count <= 4) {
		
			fprintf(stderr, "+1 producer!\n");
			producer(count, g_letters_and_numbers);
			exit(EXIT_SUCCESS);
		}
		else {
			fprintf(stderr, "+1 consumer!\n");
			consumer(count, g_letters_and_numbers);
			exit(EXIT_SUCCESS);
		}
	}
	else {
		usleep(WAIT_CHILDREN);
		printf(NEW_LINE);
		
		for (count = 0; count < NO_OF_CHILDREN; count++) {
		
			kill(pids[count], SIGKILL);
			fprintf(stderr, "%d # Killing pid process: %d\n", getpid(), pids[count]);
		
		}
		
		end();
	}
	
	exit(EXIT_SUCCESS);
}
Example #3
0
void init_config()
{
	// read gw2dps directory from shared memory
	shared_memory_object shm(boost::interprocess::open_only, "config_path", boost::interprocess::read_only);
	mapped_region region(shm, boost::interprocess::read_only);
	wchar_t* cur_path = (wchar_t*) region.get_address();
	
	abs_file_name = wstring(cur_path) + L"\\" + CONFIG_FILE_NAME;
	
	in_config_file.open(abs_file_name.c_str(), fstream::in);
	if (!in_config_file.is_open())
	{
		out_config_file.open(abs_file_name.c_str(), fstream::out);
		out_config_file << DEFAULT_CONFIG_FILE;
		out_config_file.flush();
		out_config_file.close();
	}
	// TODO: rewind is better than reopen
	in_config_file.close();
	in_config_file.open(abs_file_name.c_str(), fstream::in);
	read_ini(in_config_file, config_pt);
	in_config_file.close();

	stringstream ss;
	ss << DEFAULT_CONFIG_FILE;
	read_ini(ss, def_config_pt);
}
Example #4
0
int BRMShmImpl::grow(unsigned newKey, off_t newSize)
{
	idbassert(newKey != fKey);
	idbassert(newSize >= fSize);

	string oldName = fShmobj.get_name();

	string keyName = ShmKeys::keyToName(newKey);
#if BOOST_VERSION < 104500
	bi::shared_memory_object shm(bi::create_only, keyName.c_str(), bi::read_write);
#ifdef __linux__
	{
		string pname = "/dev/shm/" + keyName;
		chmod(pname.c_str(), 0666);
	}
#endif
#else
	bi::permissions perms;
	perms.set_unrestricted();
	bi::shared_memory_object shm(bi::create_only, keyName.c_str(), bi::read_write, perms);
#endif
	shm.truncate(newSize);

	bi::mapped_region region(shm, bi::read_write);

	//Copy old data into new region
	memcpy(region.get_address(), fMapreg.get_address(), fSize);
	//clear new region
	//make some versions of gcc happier...
	memset(reinterpret_cast<void*>(reinterpret_cast<ptrdiff_t>(region.get_address()) + fSize), 0, newSize - fSize);

	fShmobj.swap(shm);
	fMapreg.swap(region);

	if (!oldName.empty()) bi::shared_memory_object::remove(oldName.c_str());

	fKey = newKey;
	fSize = newSize;

	if (fReadOnly)
	{
		bi::mapped_region ro_region(fShmobj, bi::read_only);
		fMapreg.swap(ro_region);
	}

	return 0;
}
//---------------------------------------------------------
void shm()
{
	{
		//create /dev/shm/base_shm_00 of size 0
		//TODO boost::interprocess::open_only
		boost::interprocess::shared_memory_object shm(boost::interprocess::open_or_create, "base_shm_00", boost::interprocess::read_write); 

		//resize shm
		shm.truncate(1024); // throws boost::interprocess::interprocess_exception

		assert(shm.get_name()==std::string("base_shm_00"));

		boost::interprocess::offset_t size; 
		shm.get_size(size);
		assert(size=1024);

		boost::interprocess::mapped_region region_00(shm, boost::interprocess::read_write); 
		boost::interprocess::mapped_region region_01(shm, boost::interprocess::read_only); 
		assert(region_00.get_address()!=region_01.get_address());
		assert(region_00.get_size()==1024);
		assert(region_01.get_size()==1024);

		int* p_00=static_cast<int*>(region_00.get_address()); 
		int* p_01=static_cast<int*>(region_01.get_address()); 
		*p_00=99; 
		assert(p_01!=p_00); 
		assert(*p_01==*p_00); 

		//If remove() is not being called on UNIX, the shared memory continues to exist even if the application is terminated (until reboot)
		//On windows/OSX, it will never be removed even after reboot
		assert(boost::interprocess::shared_memory_object::remove("base_shm_00"));  //remove from /dev/shm/
	}
	{
		boost::interprocess::shared_memory_object shm(boost::interprocess::open_or_create, "base_shm_00", boost::interprocess::read_write); 
		shm.truncate(1024);
		boost::interprocess::mapped_region region(shm, boost::interprocess::read_write); 
		base_00 b(9);

		base_00* p=static_cast<base_00*>(region.get_address()); 
		*p=b;
		

		assert(boost::interprocess::shared_memory_object::remove("base_shm_00"));
	}
}
Example #6
0
statmap *statmap::getRegistry(const char *id, unsigned timeslots)
{
    if(!count || used >= count)
        return NULL;

    statmap *node = shm(used++);
    snprintf(node->id, sizeof(node->id), "%s", id);
    node->type = REGISTRY;
    node->timeslots = timeslots;
    return node;
}
Example #7
0
statmap *statmap::create(unsigned total)
{
    count = ++total;

    shm.init();

    statmap *node = shm(used++);
    node->type = SYSTEM;
    node->timeslots = Driver::getCount();
    Board::allocate();  // assign board stats if there are boards...
    return node;
}
 static bool RegionExists(const boost::interprocess::xsi_key &key)
 {
     bool result = true;
     try
     {
         boost::interprocess::xsi_shared_memory shm(boost::interprocess::open_only, key);
     }
     catch (...)
     {
         result = false;
     }
     return result;
 }
Example #9
0
statmap *statmap::getSpan(unsigned id)
{
    Span *span = Driver::getSpan(id);
    if(!count || used >= count)
        return NULL;

    statmap *node = shm(used++);
    snprintf(node->id, sizeof(node->id), "%d", id);
    node->type = SPAN;
    if(span)
        node->timeslots = span->getCount();
    return node;
}
Example #10
0
MasterSegmentTableImpl::MasterSegmentTableImpl(int key, int size)
{
	string keyName = ShmKeys::keyToName(key);
	try
	{
#if BOOST_VERSION < 104500
		bi::shared_memory_object shm(bi::create_only, keyName.c_str(), bi::read_write);
#ifdef __linux__
		{
			string pname = "/dev/shm/" + keyName;
			chmod(pname.c_str(), 0666);
		}
#endif
#else
		bi::permissions perms;
		perms.set_unrestricted();
		bi::shared_memory_object shm(bi::create_only, keyName.c_str(), bi::read_write, perms);
#endif
		shm.truncate(size);
		fShmobj.swap(shm);
	}
	catch (bi::interprocess_exception& biex)
	{
		bi::shared_memory_object shm(bi::open_only, keyName.c_str(), bi::read_write);
#ifdef __linux__
		{
			string pname = "/dev/shm/" + keyName;
			chmod(pname.c_str(), 0666);
		}
#endif
		fShmobj.swap(shm);
	}
	catch (...)
	{
		throw;
	}
	bi::mapped_region region(fShmobj, bi::read_write);
	fMapreg.swap(region);
}
Example #11
0
/** 辞書ロード */
bool ImeServer::loadDictionary()
{
    MonAPI::scoped_ptr<MonAPI::SharedMemory> shm(monapi_file_read_all(BASICDIC_NAME));
    if (shm.get() != NULL) {
        basicDicSize = shm->size();
        if (basicDicSize > 0) {
            basicDic = (char *)malloc(basicDicSize);
            memcpy(basicDic, shm->data(), basicDicSize);
        }
        return true;
    } else {
        return false;
    }
}
Example #12
0
statmap *statmap::getBoard(unsigned id)
{
    Board *board = Driver::getBoard(id);

    if(!count || used >= count)
        return NULL;

    statmap *node = shm(used++);
    snprintf(node->id, sizeof(node->id), "%d", id);
    node->type = BOARD;
    if(board)
        node->timeslots = board->getCount();
    return node;
}
 static bool RegionExists(const char *key)
 {
     bool result = true;
     try
     {
         boost::interprocess::shared_memory_object shm(boost::interprocess::open_only, key,
                                                       boost::interprocess::read_write);
     }
     catch (...)
     {
         result = false;
     }
     return result;
 }
Example #14
0
void statmap::period(FILE *fp)
{
    unsigned pos = 0;
    char text[80];
    size_t len;
    time_t last;

    while(pos < count) {
        statmap *node = shm(pos++);
        if(node->type == UNUSED)
            continue;

        if(fp) {
            if(node->type == statmap::BOARD)
                snprintf(text, sizeof(text), " board/%-6s", node->id);
            else if(node->type == statmap::SPAN)
                snprintf(text, sizeof(text), " span/%-7s", node->id);
            else if(node->type == statmap::REGISTRY)
                snprintf(text, sizeof(text), " net/%-8s", node->id);
            else
                snprintf(text, sizeof(text), " system      ");
            len = strlen(text);
        }
        else
            len = 0;

        Mutex::protect(node);
        for(unsigned entry = 0; entry < 2; ++entry) {
            if(fp) {
                snprintf(text + len, sizeof(text) - len, " %09lu %05hu %05hu",
                node->stats[entry].period, node->stats[entry].min, node->stats[entry].max);
                len = strlen(text);
            }
            node->stats[entry].pperiod = node->stats[entry].period;
            node->stats[entry].pmax = node->stats[entry].max;
            node->stats[entry].pmin = node->stats[entry].min;
            node->stats[entry].max = node->stats[entry].min = node->stats[entry].current;
            node->stats[entry].period = 0;
        }
        last = node->lastcall;
        Mutex::release(node);
        if(fp)
            fprintf(fp, "%s %ld\n", text, (long)last);
    }
}
Example #15
0
    static bool RegionExists(const boost::interprocess::xsi_key &key)
    {
        bool result = true;
        try
        {
            boost::interprocess::xsi_shared_memory shm(boost::interprocess::open_only, key);
        }
        catch (const boost::interprocess::interprocess_exception &e)
        {
            if (e.get_error_code() != boost::interprocess::not_found_error)
            {
                throw;
            }
            result = false;
        }

        return result;
    }
Example #16
0
void MessagerShm::sendMessage(Pid pid, const QString &message)
{
    const HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
                                        FALSE, pid);
    if (hProcess) {
        wchar_t buffer[1024];
        memset(buffer, 0, sizeof(buffer));
        DWORD sz = GetModuleBaseNameW(hProcess, 0, buffer, 1024u);
        CloseHandle(hProcess);
        QString procName = QString::fromWCharArray(buffer, sz);
        if (procName.length() > 0) {
            QSharedMemory shm(procName);
            if (shm.attach(QSharedMemory::ReadWrite)) {
                shm.lock();
                QByteArray utf8 = message.toUtf8();
                memset(shm.data(), 0, shm.size());
                memcpy(shm.data(), utf8.constData(), utf8.size());
                shm.unlock();
            }
        }
    }
}
Example #17
0
int entry_main(int argc, _TCHAR* argv[])
{
	DWORD		pid;
	HANDLE		l;
	Injector	&i = Injector::GetInstance();
	SharedMemoryServer	shm("lllol");
	
	HMODULE dll = LoadLibrary(L"ClientDll.dll");
	if (dll == NULL) {
		printf("The DLL could not be found.n");
		getchar();
		return -1;
	}
	typedef void(*fnPtr)(void);

	fnPtr addr = (fnPtr)GetProcAddress(dll, "LoadHook");
	if (addr == NULL) {
		printf("The function was not found.n");
		getchar();
		return -1;
	}
	addr();
	while (1)
	{
		Data test = shm.pop();
		if (test.t != NONE)
		{
			std::cout << "[" << test.pid << "] ";
			if (test.t == MOUSELOG)
				std::cout << "Click at " << test.data.mouse.x << ";" << test.data.mouse.y << std::endl;
			else
				std::cout << "Keypress " << test.data.key.keyCode << std::endl;
		}
		Sleep(100);
	}
	return (0);
}
//---------------------------------------------------------
int main()
{
	shm();
	//managed_shm();
	return 0;
}
Example #19
0
void shippingInformation::sFillList()
{
//  Clear any old data
  _item->clear();

  QString shs( "SELECT shiphead_notes, shiphead_shipvia,"
               "       shiphead_shipchrg_id, shiphead_shipform_id,"
               "       shiphead_freight, shiphead_freight_curr_id,"
               "       shiphead_shipdate,"
               "       CASE WHEN (shiphead_shipdate IS NULL) THEN FALSE"
               "            ELSE TRUE"
               "       END AS validdata "
               "FROM shiphead "
               "WHERE ((NOT shiphead_shipped)"
	       "  AND  (shiphead_order_type=<? value(\"ordertype\") ?>)"
               "  AND  (shiphead_order_id=<? value(\"orderid\") ?>) );" ) ;
  ParameterList shp;
  if (_salesOrder->isValid())
  {
    shp.append("ordertype", "SO");
    shp.append("orderid",   _salesOrder->id());
  }
  else if (_to->isValid())
  {
    shp.append("ordertype", "TO");
    shp.append("orderid",   _to->id());
  }
  else
  {
    _salesOrder->setId(-1);
    _orderDate->setNull();
    _poNumber->clear();
    _custName->clear();
    _custPhone->clear();
    _shipDate->setNull();
    _shipVia->setNull();

    _freight->reset();
    _totalNetWeight->clear();
    _totalTareWeight->clear();
    _totalGrossWeight->clear();
    return;
  }

  MetaSQLQuery shm(shs);
  q = shm.toQuery(shp);
  bool fetchFromHead = TRUE;

  if (q.first())
  {
    if (q.value("validdata").toBool())
    {
      fetchFromHead = FALSE;

      _shipDate->setDate(q.value("shiphead_shipdate").toDate());
      _shipVia->setText(q.value("shiphead_shipvia").toString());
      _shippingCharges->setId(q.value("shiphead_shipchrg_id").toInt());
      _shippingForm->setId(q.value("shiphead_shipform_id").toInt());
      _freight->setId(q.value("shiphead_freight_curr_id").toInt());
      _freight->setLocalValue(q.value("shiphead_freight").toDouble());
      _notes->setText(q.value("shiphead_notes").toString());
    }
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if (_salesOrder->isValid())
  {
    q.prepare( "SELECT cohead_orderdate AS orderdate,"
	       "       cohead_holdtype AS holdtype,"
	       "       cohead_custponumber AS ponumber,"
               "       cust_name AS name, cust_phone AS phone,"
               "       cohead_shipcomments AS shipcomments,"
	       "       cohead_shipvia AS shipvia,"
               "       cohead_shipchrg_id AS shipchrg_id,"
	       "       cohead_shipform_id AS shipform_id "
               "FROM cohead, cust "
               "WHERE ((cohead_cust_id=cust_id)"
               " AND (cohead_id=:cohead_id));" );
    q.bindValue(":cohead_id", _salesOrder->id());
  }
  else if (_to->isValid())
  {
    q.prepare( "SELECT tohead_orderdate AS orderdate,"
	       "       'N' AS holdtype,"
	       "       :to AS ponumber,"
	       "       tohead_destname AS name, tohead_destphone AS phone,"
	       "       tohead_shipcomments AS shipcomments,"
	       "       tohead_shipvia AS shipvia,"
	       "       tohead_shipchrg_id AS shipchrg_id,"
	       "       tohead_shipform_id AS shipform_id "
	       "FROM tohead "
	       "WHERE (tohead_id=:tohead_id);" );
    q.bindValue(":tohead_id", _to->id());
  }
  q.exec();
  if (q.first())
  {
    _orderDate->setDate(q.value("orderdate").toDate());
    _poNumber->setText(q.value("custponumber").toString());
    _custName->setText(q.value("name").toString());
    _custPhone->setText(q.value("phone").toString());

    QString msg;
    if (q.value("head_holdtype").toString() == "C")
      msg = storedProcErrorLookup("issuetoshipping", -12);
    else if (q.value("head_holdtype").toString() == "P")
      msg = storedProcErrorLookup("issuetoshipping", -13);
    else if (q.value("head_holdtype").toString() == "R")
      msg = storedProcErrorLookup("issuetoshipping", -14);

    if (! msg.isEmpty())
    {
      QMessageBox::warning(this, tr("Order on Hold"), msg);
      _salesOrder->setId(-1);
      _salesOrder->setFocus();
      _to->setId(-1);
      return;
    }

    if (fetchFromHead)
    {
      _shipDate->setDate(omfgThis->dbDate());

      _shippingCharges->setId(q.value("shipchrg_id").toInt());
      _shippingForm->setId(q.value("shipform_id").toInt());
      _notes->setText(q.value("shipcomments").toString());
      _shipVia->setText(q.value("shipvia").toString());
    }
  }
  else if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  if (_salesOrder->isValid())
  {
    q.prepare( "SELECT coitem_id AS itemid, coitem_cohead_id AS headid,"
	       "       coitem_linenumber AS linenumber, item_number,"
               "      (item_prodweight * itemuomtouom(item_id, coitem_price_uom_id, NULL, qtyAtShipping('SO', coitem_id))) AS netweight,"
               "      (item_packweight * itemuomtouom(item_id, coitem_price_uom_id, NULL, qtyAtShipping('SO', coitem_id))) AS tareweight,"
               "      qtyAtShipping('SO', coitem_id) AS qtyatshipping,"
               "      formatQty(qtyAtShipping('SO', coitem_id)) AS f_qtyatshipping "
               "FROM coitem, itemsite, item "
               "WHERE ((coitem_itemsite_id=itemsite_id)"
               "  AND  (itemsite_item_id=item_id)"
               "  AND  (coitem_cohead_id=:cohead_id) ) "
               "ORDER BY coitem_linenumber;" );
    q.bindValue(":cohead_id", _salesOrder->id());
  }
  else if (_to->isValid())
  {
    q.prepare( "SELECT toitem_id AS itemid, toitem_tohead_id AS headid,"
	       "       toitem_linenumber AS linenumber, item_number,"
               "      (item_prodweight * qtyAtShipping('TO', toitem_id))) AS netweight,"
               "      (item_packweight * qtyAtShipping('TO', toitem_id))) AS tareweight,"
               "      qtyAtShipping('TO', toitem_id) AS qtyatshipping,"
               "      formatQty(qtyAtShipping('TO', toitem_id)) AS f_qtyatshipping "
               "FROM toitem, item "
               "WHERE ((toitem_item_id=item_id)"
               "  AND  (toitem_tohead_id=:tohead_id) ) "
               "ORDER BY toitem_linenumber;" ) ;
    q.bindValue(":tohead_id", _to->id());
  } 
  q.exec();

  double        totalNetWeight   = 0;
  double        totalTareWeight  = 0;

  XTreeWidgetItem* last = 0;

  while (q.next())
  {
    totalNetWeight   += q.value("netweight").toDouble();
    totalTareWeight  += q.value("tareweight").toDouble();

    last = new XTreeWidgetItem( _item, last, q.value("itemid").toInt(),
		       q.value("headid").toInt(),
		       q.value("linenumber"), q.value("item_number"),
		       q.value("f_qtyatshipping"),
		       formatWeight(q.value("netweight").toDouble()),
		       formatWeight(q.value("tareweight").toDouble()),
		       formatWeight((q.value("netweight").toDouble() +
				     q.value("tareweight").toDouble())) );
  }
  if (q.lastError().type() != QSqlError::None)
  {
    systemError(this, q.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  _totalNetWeight->setText(formatWeight(totalNetWeight));
  _totalTareWeight->setText(formatWeight(totalTareWeight));
  _totalGrossWeight->setText(formatWeight(totalNetWeight + totalTareWeight));
}
Example #20
0
BRMShmImpl::BRMShmImpl(unsigned key, off_t size, bool readOnly) :
	fKey(key), fSize(size), fReadOnly(readOnly)
{
	string keyName = ShmKeys::keyToName(fKey);
	if (fSize == 0)
	{
		unsigned tries = 0;
again:
		try
		{
			bi::shared_memory_object shm(bi::open_only, keyName.c_str(), bi::read_write);
			off_t curSize = 0;
#ifdef _MSC_VER
			bi::offset_t tmp = 0;
			shm.get_size(tmp);
			curSize = static_cast<off_t>(tmp);
#else
			shm.get_size(curSize);
#endif
			if (curSize == 0) throw
#if BOOST_VERSION < 104500
				bi::interprocess_exception();
#else
				bi::interprocess_exception("shm size is zero");
#endif
		}
		catch (bi::interprocess_exception&)
		{
			if (++tries > 10) {
				log("BRMShmImpl::BRMShmImpl(): retrying on size==0");
				throw;
			}
			cerr << "BRMShmImpl::BRMShmImpl(): retrying on size==0" << endl;
			usleep(500 * 1000);
			goto again;
		}
	}
	try
	{
#if BOOST_VERSION < 104500
		bi::shared_memory_object shm(bi::create_only, keyName.c_str(), bi::read_write);
#ifdef __linux__
		{
			string pname = "/dev/shm/" + keyName;
			chmod(pname.c_str(), 0666);
		}
#endif
#else
		bi::permissions perms;
		perms.set_unrestricted();
		bi::shared_memory_object shm(bi::create_only, keyName.c_str(), bi::read_write, perms);
#endif
		idbassert(fSize > 0);
		shm.truncate(fSize);
		fShmobj.swap(shm);
	}
	catch (bi::interprocess_exception&)
	{
		bi::shared_memory_object shm(bi::open_only, keyName.c_str(), bi::read_write);
		off_t curSize = 0;
#ifdef _MSC_VER
		bi::offset_t tmp = 0;
		shm.get_size(tmp);
		curSize = static_cast<off_t>(tmp);
#else
		shm.get_size(curSize);
#endif
		idbassert(curSize > 0);
		idbassert(curSize >= fSize);
		fShmobj.swap(shm);
		fSize = curSize;
	}
	catch (...)
	{
		throw;
	}

	if (fReadOnly)
	{
		bi::mapped_region ro_region(fShmobj, bi::read_only);
		fMapreg.swap(ro_region);
	}
	else
	{
		bi::mapped_region region(fShmobj, bi::read_write);
		fMapreg.swap(region);
	}
}
extern "C" JNIEXPORT int
JVM_handle_linux_signal(int sig,
                        siginfo_t* info,
                        void* ucVoid,
                        int abort_if_unrecognized) {
  // in fact this isn't ucontext_t* at all, but struct sigcontext*
  // but Linux porting layer uses ucontext_t, so to minimize code change
  // we cast as needed
  ucontext_t* ucFake = (ucontext_t*) ucVoid;
  sigcontext* uc = (sigcontext*)ucVoid;

  Thread* t = ThreadLocalStorage::get_thread_slow();

  SignalHandlerMark shm(t);

  // Note: it's not uncommon that JNI code uses signal/sigset to install
  // then restore certain signal handler (e.g. to temporarily block SIGPIPE,
  // or have a SIGILL handler when detecting CPU type). When that happens,
  // JVM_handle_linux_signal() might be invoked with junk info/ucVoid. To
  // avoid unnecessary crash when libjsig is not preloaded, try handle signals
  // that do not require siginfo/ucontext first.

  if (sig == SIGPIPE || sig == SIGXFSZ) {
    // allow chained handler to go first
    if (os::Linux::chained_handler(sig, info, ucVoid)) {
      return true;
    } else {
      if (PrintMiscellaneous && (WizardMode || Verbose)) {
        char buf[64];
        warning("Ignoring %s - see bugs 4229104 or 646499219",
                os::exception_name(sig, buf, sizeof(buf)));
      }
      return true;
    }
  }

  JavaThread* thread = NULL;
  VMThread* vmthread = NULL;
  if (os::Linux::signal_handlers_are_installed) {
    if (t != NULL ){
      if(t->is_Java_thread()) {
        thread = (JavaThread*)t;
      }
      else if(t->is_VM_thread()){
        vmthread = (VMThread *)t;
      }
    }
  }

  // decide if this trap can be handled by a stub
  address stub = NULL;
  address pc = NULL;
  address npc = NULL;

  //%note os_trap_1
  if (info != NULL && uc != NULL && thread != NULL) {
    pc = address(SIG_PC(uc));
    npc = address(SIG_NPC(uc));

    // Check to see if we caught the safepoint code in the
    // process of write protecting the memory serialization page.
    // It write enables the page immediately after protecting it
    // so we can just return to retry the write.
    if ((sig == SIGSEGV) && checkSerializePage(thread, (address)info->si_addr)) {
      // Block current thread until the memory serialize page permission restored.
      os::block_on_serialize_page_trap();
      return 1;
    }

    if (checkPrefetch(uc, pc)) {
      return 1;
    }

    // Handle ALL stack overflow variations here
    if (sig == SIGSEGV) {
      if (checkOverflow(uc, pc, (address)info->si_addr, thread, &stub)) {
        return 1;
      }
    }

    if (sig == SIGBUS &&
        thread->thread_state() == _thread_in_vm &&
        thread->doing_unsafe_access()) {
      stub = StubRoutines::handler_for_unsafe_access();
    }

    if (thread->thread_state() == _thread_in_Java) {
      do {
        // Java thread running in Java code => find exception handler if any
        // a fault inside compiled code, the interpreter, or a stub

        if ((sig == SIGSEGV) && checkPollingPage(pc, (address)info->si_addr, &stub)) {
          break;
        }

        if ((sig == SIGBUS) && checkByteBuffer(pc, &stub)) {
          break;
        }

        if ((sig == SIGSEGV || sig == SIGBUS) &&
            checkVerifyOops(pc, (address)info->si_addr, &stub)) {
          break;
        }

        if ((sig == SIGSEGV) && checkZombie(uc, &pc, &stub)) {
          break;
        }

        if ((sig == SIGILL) && checkICMiss(uc, &pc, &stub)) {
          break;
        }

        if ((sig == SIGFPE) && checkFPFault(pc, info->si_code, thread, &stub)) {
          break;
        }

        if ((sig == SIGSEGV) &&
            checkNullPointer(pc, (intptr_t)info->si_addr, thread, &stub)) {
          break;
        }
      } while (0);

      // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in
      // and the heap gets shrunk before the field access.
      if ((sig == SIGSEGV) || (sig == SIGBUS)) {
        checkFastJNIAccess(pc, &stub);
      }
    }

    if (stub != NULL) {
      // save all thread context in case we need to restore it
      thread->set_saved_exception_pc(pc);
      thread->set_saved_exception_npc(npc);
      set_cont_address(uc, stub);
      return true;
    }
  }

  // signal-chaining
  if (os::Linux::chained_handler(sig, info, ucVoid)) {
    return true;
  }

  if (!abort_if_unrecognized) {
    // caller wants another chance, so give it to him
    return false;
  }

  if (pc == NULL && uc != NULL) {
    pc = os::Linux::ucontext_get_pc((ucontext_t*)uc);
  }

  // unmask current signal
  sigset_t newset;
  sigemptyset(&newset);
  sigaddset(&newset, sig);
  sigprocmask(SIG_UNBLOCK, &newset, NULL);

  VMError err(t, sig, pc, info, ucVoid);
  err.report_and_die();

  ShouldNotReachHere();
}
int main()
{
   //Remove any other old shared memory from the system
   bip::shared_memory_object::remove(bip::test::get_process_id_name());
   try {
      bip::managed_shared_memory shm(bip::create_only, bip::test::get_process_id_name(), 65536);

      //Elements to be inserted in unordered containers
      const int elements[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
      const int elements_size = sizeof(elements)/sizeof(elements[0]);

      MyUnorderedSet *myset  =
         shm.construct<MyUnorderedSet>(bip::anonymous_instance)
            ( elements_size
            , MyUnorderedSet::hasher()
            , MyUnorderedSet::key_equal()
            , shm.get_allocator<int>());
      MyUnorderedMultiSet *mymset =
         shm.construct<MyUnorderedMultiSet>(bip::anonymous_instance)
            ( elements_size
            , MyUnorderedSet::hasher()
            , MyUnorderedSet::key_equal()
            , shm.get_allocator<int>());

      //Insert elements and check sizes
      myset->insert((&elements[0]), (&elements[elements_size]));
      myset->insert((&elements[0]), (&elements[elements_size]));
      mymset->insert((&elements[0]), (&elements[elements_size]));
      mymset->insert((&elements[0]), (&elements[elements_size]));

      if(myset->size() != (unsigned int)elements_size)
         return 1;
      if(mymset->size() != (unsigned int)elements_size*2)
         return 1;

      //Destroy elements and check sizes
      myset->clear();
      mymset->clear();

      if(!myset->empty())
         return 1;
      if(!mymset->empty())
         return 1;

      //Destroy elements and check if memory has been deallocated
      shm.destroy_ptr(myset);
      shm.destroy_ptr(mymset);

      shm.shrink_to_fit_indexes();
      if(!shm.all_memory_deallocated())
         return 1;

   }
   catch(...){
      //Remove shared memory from the system
      bip::shared_memory_object::remove(bip::test::get_process_id_name());
      throw;
   }
   //Remove shared memory from the system
   bip::shared_memory_object::remove(bip::test::get_process_id_name());
   return 0;
}
Example #23
0
File: writer.c Project: ombt/ombt
// main entry into test case
int
main(int argc, char **argv)
{
	pid_t pid = -1;
	key_t shmkey = -1;
	key_t rdkey = -1;
	key_t wrkey = -1;
	int shmid = -1;
	int asize = 0;

	// check number of arguments
	if (argc != 5)
	{
		cout << "usage: writer shmkey readkey writekey arraysize" << endl;
		return(2);
	}

	// try/catch block for everything
	try {
		// get keys
		shmkey = atoi(argv[1]);
		rdkey = atoi(argv[2]);
		wrkey = atoi(argv[3]);
		asize = atoi(argv[4]);

		// number of readers and writers
		int rd_no = 0;
		int wr_no = 1;

		// attach to shared memory
		SharedMemory<Dummy> shm(shmkey, asize);
		shmid = shm.getShmId();

		// check if we own the shared memory
		MustBeTrue(shm.isOwner())

		// get semaphore
		Semaphore writer(wrkey, 0666, wr_no);
		Semaphore reader(rdkey, 0666, rd_no);

		// fork/exec the reader process
		MustBeTrue((pid = fork()) != (pid_t)NOTOK);
		if (pid == 0)
		{
			// execute the child process
			try {
			MustBeTrue(execl("reader", "reader", argv[1], 
				argv[2], argv[3], argv[4], NULL) != NOTOK);
			}
			catch (const char *pe)
			{
				ERROR(pe, errno);
			}
			return(2);
		}

		// gain ownership
		MustBeTrue(writer.P(-1) == OK);

		// get length of initial msg
		int ilen = strlen(shm[0].buf);
		ilen--;

		// let reader proceed
		MustBeTrue(reader.V() == OK);

		for (char c = 'a'; c <= 'z'; c++)
		{
			// gain ownership
			MustBeTrue(writer.P(-1) == OK);

			// write to shared memory
			for (int ia = 0; ia < asize; ia++)
			{
				shm[ia].buf[ilen] = c;
				shm[ia].buf[ilen+1] = '\0';
				cout << "WRITER: writing into buffer [";
				cout << ia << "] ... " << shm[ia].buf << endl;
			}
			ilen++;

			// release ownership
			MustBeTrue(reader.V() == OK);
		}

		// get permission to write 
		MustBeTrue(writer.P(-1) == OK);

		// write to shared memory
		strcpy(shm->buf, "all done");
		cout << "WRITER: writing ... " << shm->buf << endl;

		// let reader proceed
		MustBeTrue(reader.V() == OK);

		// gain ownership one last time
		MustBeTrue(writer.P(-1) == OK);
	}
	catch (const char *pe)
	{
		ERROR(pe, errno);
		return(2);
	}

	// wait for child to finish
	int status;
	MustBeTrue(wait(&status) == pid);

	// delete resources
	SharedMemory<Dummy>::removeSharedMemory(shmid);

	// all done
	return(0);
}
Example #24
0
extern "C" JNIEXPORT int
JVM_handle_linux_signal(int sig,
                        siginfo_t* info,
                        void* ucVoid,
                        int abort_if_unrecognized) {
  ucontext_t* uc = (ucontext_t*) ucVoid;

  Thread* t = ThreadLocalStorage::get_thread_slow();

  SignalHandlerMark shm(t);

  // Note: it's not uncommon that JNI code uses signal/sigset to
  // install then restore certain signal handler (e.g. to temporarily
  // block SIGPIPE, or have a SIGILL handler when detecting CPU
  // type). When that happens, JVM_handle_linux_signal() might be
  // invoked with junk info/ucVoid. To avoid unnecessary crash when
  // libjsig is not preloaded, try handle signals that do not require
  // siginfo/ucontext first.

  if (sig == SIGPIPE || sig == SIGXFSZ) {
    // allow chained handler to go first
    if (os::Linux::chained_handler(sig, info, ucVoid)) {
      return true;
    } else {
      if (PrintMiscellaneous && (WizardMode || Verbose)) {
        char buf[64];
        warning("Ignoring %s - see bugs 4229104 or 646499219",
                os::exception_name(sig, buf, sizeof(buf)));
      }
      return true;
    }
  }

  JavaThread* thread = NULL;
  VMThread* vmthread = NULL;
  if (os::Linux::signal_handlers_are_installed) {
    if (t != NULL ){
      if(t->is_Java_thread()) {
        thread = (JavaThread*)t;
      }
      else if(t->is_VM_thread()){
        vmthread = (VMThread *)t;
      }
    }
  }

  if (info != NULL && thread != NULL) {
    // Handle ALL stack overflow variations here
    if (sig == SIGSEGV) {
      address addr = (address) info->si_addr;

      // check if fault address is within thread stack
      if (addr < thread->stack_base() &&
          addr >= thread->stack_base() - thread->stack_size()) {
        // stack overflow
        if (thread->in_stack_yellow_zone(addr)) {
          thread->disable_stack_yellow_zone();
          ShouldNotCallThis();
        }
        else if (thread->in_stack_red_zone(addr)) {
          thread->disable_stack_red_zone();
          ShouldNotCallThis();
        }
        else {
          // Accessing stack address below sp may cause SEGV if
          // current thread has MAP_GROWSDOWN stack. This should
          // only happen when current thread was created by user
          // code with MAP_GROWSDOWN flag and then attached to VM.
          // See notes in os_linux.cpp.
          if (thread->osthread()->expanding_stack() == 0) {
            thread->osthread()->set_expanding_stack();
            if (os::Linux::manually_expand_stack(thread, addr)) {
              thread->osthread()->clear_expanding_stack();
              return true;
            }
            thread->osthread()->clear_expanding_stack();
          }
          else {
            fatal("recursive segv. expanding stack.");
          }
        }
      }
    }

    /*if (thread->thread_state() == _thread_in_Java) {
      ShouldNotCallThis();
    }
    else*/ if (thread->thread_state() == _thread_in_vm &&
               sig == SIGBUS && thread->doing_unsafe_access()) {
      ShouldNotCallThis();
    }

    // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC
    // kicks in and the heap gets shrunk before the field access.
    /*if (sig == SIGSEGV || sig == SIGBUS) {
      address addr = JNI_FastGetField::find_slowcase_pc(pc);
      if (addr != (address)-1) {
        stub = addr;
      }
    }*/

    // Check to see if we caught the safepoint code in the process
    // of write protecting the memory serialization page.  It write
    // enables the page immediately after protecting it so we can
    // just return to retry the write.
    if (sig == SIGSEGV &&
        os::is_memory_serialize_page(thread, (address) info->si_addr)) {
      // Block current thread until permission is restored.
      os::block_on_serialize_page_trap();
      return true;
    }
  }

  // signal-chaining
  if (os::Linux::chained_handler(sig, info, ucVoid)) {
     return true;
  }

  if (!abort_if_unrecognized) {
    // caller wants another chance, so give it to him
    return false;
  }

#ifndef PRODUCT
  if (sig == SIGSEGV) {
    fatal("\n#"
          "\n#    /--------------------\\"
          "\n#    | segmentation fault |"
          "\n#    \\---\\ /--------------/"
          "\n#        /"
          "\n#    [-]        |\\_/|    "
          "\n#    (+)=C      |o o|__  "
          "\n#    | |        =-*-=__\\ "
          "\n#    OOO        c_c_(___)");
  }
#endif // !PRODUCT

  const char *fmt = "caught unhandled signal %d";
  char buf[64];

  sprintf(buf, fmt, sig);
  fatal(buf);
}
extern "C" JNIEXPORT int
JVM_handle_linux_signal(int sig,
                        siginfo_t* info,
                        void* ucVoid,
                        int abort_if_unrecognized) {
  ucontext_t* uc = (ucontext_t*) ucVoid;

  Thread* t = ThreadLocalStorage::get_thread_slow();

  // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away
  // (no destructors can be run)
  os::WatcherThreadCrashProtection::check_crash_protection(sig, t);

  SignalHandlerMark shm(t);

  // Note: it's not uncommon that JNI code uses signal/sigset to install
  // then restore certain signal handler (e.g. to temporarily block SIGPIPE,
  // or have a SIGILL handler when detecting CPU type). When that happens,
  // JVM_handle_linux_signal() might be invoked with junk info/ucVoid. To
  // avoid unnecessary crash when libjsig is not preloaded, try handle signals
  // that do not require siginfo/ucontext first.

  if (sig == SIGPIPE || sig == SIGXFSZ) {
    // allow chained handler to go first
    if (os::Linux::chained_handler(sig, info, ucVoid)) {
      return true;
    } else {
      if (PrintMiscellaneous && (WizardMode || Verbose)) {
        char buf[64];
        warning("Ignoring %s - see bugs 4229104 or 646499219",
                os::exception_name(sig, buf, sizeof(buf)));
      }
      return true;
    }
  }

  JavaThread* thread = NULL;
  VMThread* vmthread = NULL;
  if (os::Linux::signal_handlers_are_installed) {
    if (t != NULL ){
      if(t->is_Java_thread()) {
        thread = (JavaThread*)t;
      }
      else if(t->is_VM_thread()){
        vmthread = (VMThread *)t;
      }
    }
  }
/*
  NOTE: does not seem to work on linux.
  if (info == NULL || info->si_code <= 0 || info->si_code == SI_NOINFO) {
    // can't decode this kind of signal
    info = NULL;
  } else {
    assert(sig == info->si_signo, "bad siginfo");
  }
*/
  // decide if this trap can be handled by a stub
  address stub = NULL;

  address pc          = NULL;

  //%note os_trap_1
  if (info != NULL && uc != NULL && thread != NULL) {
    pc = (address) os::Linux::ucontext_get_pc(uc);

#ifdef BUILTIN_SIM
    if (pc == (address) Fetch32PFI) {
       uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ;
       return 1 ;
    }
    if (pc == (address) FetchNPFI) {
       uc->uc_mcontext.gregs[REG_PC] = intptr_t (FetchNResume) ;
       return 1 ;
    }
#else
    if (StubRoutines::is_safefetch_fault(pc)) {
      uc->uc_mcontext.pc = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc));
      return 1;
    }
#endif

#ifndef AMD64
    // Halt if SI_KERNEL before more crashes get misdiagnosed as Java bugs
    // This can happen in any running code (currently more frequently in
    // interpreter code but has been seen in compiled code)
    if (sig == SIGSEGV && info->si_addr == 0 && info->si_code == SI_KERNEL) {
      fatal("An irrecoverable SI_KERNEL SIGSEGV has occurred due "
            "to unstable signal handling in this distribution.");
    }
#endif // AMD64

    // Handle ALL stack overflow variations here
    if (sig == SIGSEGV) {
      address addr = (address) info->si_addr;

      // check if fault address is within thread stack
      if (addr < thread->stack_base() &&
          addr >= thread->stack_base() - thread->stack_size()) {
        // stack overflow
        if (thread->in_stack_yellow_zone(addr)) {
          thread->disable_stack_yellow_zone();
          if (thread->thread_state() == _thread_in_Java) {
            // Throw a stack overflow exception.  Guard pages will be reenabled
            // while unwinding the stack.
            stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW);
          } else {
            // Thread was in the vm or native code.  Return and try to finish.
            return 1;
          }
        } else if (thread->in_stack_red_zone(addr)) {
          // Fatal red zone violation.  Disable the guard pages and fall through
          // to handle_unexpected_exception way down below.
          thread->disable_stack_red_zone();
          tty->print_raw_cr("An irrecoverable stack overflow has occurred.");

          // This is a likely cause, but hard to verify. Let's just print
          // it as a hint.
          tty->print_raw_cr("Please check if any of your loaded .so files has "
                            "enabled executable stack (see man page execstack(8))");
        } else {
          // Accessing stack address below sp may cause SEGV if current
          // thread has MAP_GROWSDOWN stack. This should only happen when
          // current thread was created by user code with MAP_GROWSDOWN flag
          // and then attached to VM. See notes in os_linux.cpp.
          if (thread->osthread()->expanding_stack() == 0) {
             thread->osthread()->set_expanding_stack();
             if (os::Linux::manually_expand_stack(thread, addr)) {
               thread->osthread()->clear_expanding_stack();
               return 1;
             }
             thread->osthread()->clear_expanding_stack();
          } else {
             fatal("recursive segv. expanding stack.");
          }
        }
      }
    }

    if (thread->thread_state() == _thread_in_Java) {
      // Java thread running in Java code => find exception handler if any
      // a fault inside compiled code, the interpreter, or a stub

      // Handle signal from NativeJump::patch_verified_entry().
      if ((sig == SIGILL || sig == SIGTRAP)
          && nativeInstruction_at(pc)->is_sigill_zombie_not_entrant()) {
        if (TraceTraps) {
          tty->print_cr("trap: zombie_not_entrant (%s)", (sig == SIGTRAP) ? "SIGTRAP" : "SIGILL");
        }
        stub = SharedRuntime::get_handle_wrong_method_stub();
      } else if (sig == SIGSEGV && os::is_poll_address((address)info->si_addr)) {
        stub = SharedRuntime::get_poll_stub(pc);
      } else if (sig == SIGBUS /* && info->si_code == BUS_OBJERR */) {
        // BugId 4454115: A read from a MappedByteBuffer can fault
        // here if the underlying file has been truncated.
        // Do not crash the VM in such a case.
        CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
        nmethod* nm = (cb != NULL && cb->is_nmethod()) ? (nmethod*)cb : NULL;
        if (nm != NULL && nm->has_unsafe_access()) {
          stub = handle_unsafe_access(thread, pc);
        }
      }
      else

      if (sig == SIGFPE  &&
          (info->si_code == FPE_INTDIV || info->si_code == FPE_FLTDIV)) {
        stub =
          SharedRuntime::
          continuation_for_implicit_exception(thread,
                                              pc,
                                              SharedRuntime::
                                              IMPLICIT_DIVIDE_BY_ZERO);
      } else if (sig == SIGSEGV &&
               !MacroAssembler::needs_explicit_null_check((intptr_t)info->si_addr)) {
          // Determination of interpreter/vtable stub/compiled code null exception
          stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
      }
    } else if (thread->thread_state() == _thread_in_vm &&
               sig == SIGBUS && /* info->si_code == BUS_OBJERR && */
               thread->doing_unsafe_access()) {
        stub = handle_unsafe_access(thread, pc);
    }

    // jni_fast_Get<Primitive>Field can trap at certain pc's if a GC kicks in
    // and the heap gets shrunk before the field access.
    if ((sig == SIGSEGV) || (sig == SIGBUS)) {
      address addr = JNI_FastGetField::find_slowcase_pc(pc);
      if (addr != (address)-1) {
        stub = addr;
      }
    }

    // Check to see if we caught the safepoint code in the
    // process of write protecting the memory serialization page.
    // It write enables the page immediately after protecting it
    // so we can just return to retry the write.
    if ((sig == SIGSEGV) &&
        os::is_memory_serialize_page(thread, (address) info->si_addr)) {
      // Block current thread until the memory serialize page permission restored.
      os::block_on_serialize_page_trap();
      return true;
    }
  }

  if (stub != NULL) {
    // save all thread context in case we need to restore it
    if (thread != NULL) thread->set_saved_exception_pc(pc);

#ifdef BUILTIN_SIM
    uc->uc_mcontext.gregs[REG_PC] = (greg_t)stub;
#else
    uc->uc_mcontext.pc = (__u64)stub;
#endif
    return true;
  }

  // signal-chaining
  if (os::Linux::chained_handler(sig, info, ucVoid)) {
     return true;
  }

  if (!abort_if_unrecognized) {
    // caller wants another chance, so give it to him
    return false;
  }

  if (pc == NULL && uc != NULL) {
    pc = os::Linux::ucontext_get_pc(uc);
  }

  // unmask current signal
  sigset_t newset;
  sigemptyset(&newset);
  sigaddset(&newset, sig);
  sigprocmask(SIG_UNBLOCK, &newset, NULL);

  VMError err(t, sig, pc, info, ucVoid);
  err.report_and_die();

  ShouldNotReachHere();
}