示例#1
0
文件: main.c 项目: kojiba/RayLanguage
int main(int argc, const char *argv[]) {
    enablePool(RPool);
    ComplexTest();


    // [ ] ,  [ [ [ ] ] ],  [ [ ] [] [ ] ]
    const RString *source = RS(" ++++++++++ [ >+++++++>++++++++++>+++>+<<<<- ] >++\n"
                                  " .>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.\n"
                                  " ------.--------.>+.>.");

    RVirtualFunction *function = c(RVirtualFunction)(nil);
    function->name = RSC("Hello");
    function->masterRDataObject = makeRDataAllocated(5);
    function->masterRDataObject->data[0] = r_addition;
    function->masterRDataObject->data[1] = 0x01;

    function->masterRDataObject->data[2] = r_addition;
    function->masterRDataObject->data[3] = 0x23;

    function->masterRDataObject->data[4] = r_end;

    // brainfuck hard(with [, ]) hello world on RVM
//    RVirtualFunction *function = $(RVC, m(createFunctionFromBrainFuckSourceCode, RVirtualCompiler)), source );

    p(RVirtualFunction)(function);

    executeRay(function);

    deleter(function, RVirtualFunction);
    deleter(RVM, RVirtualMachine);
    deleter(RVC, RVirtualCompiler);

    endRay();
}
示例#2
0
bool clIndexerProtocol::SendReply(clNamedPipe* conn, clIndexerReply& reply)
{
    size_t buff_size(0);
    char *data = reply.toBinary(buff_size);
    CharDeleter deleter(data);

    // send the reply size
    size_t written(0);
    conn->write((void*)&buff_size, sizeof(buff_size), &written, -1);


    int bytes_left(buff_size);
    int bytes_to_write(0);
    int bytes_written(0);

    while (bytes_left > 0) {
        // we write in chunks of 3000 bytes
        if (bytes_left < 3000) {
            bytes_to_write = bytes_left;
        } else {
            bytes_to_write = 3000;
        }

        size_t actual_written(0);
        if ( !conn->write(data+bytes_written, bytes_to_write, &actual_written, -1) ) {
            return false;
        }

        bytes_left -= actual_written;
        bytes_written += actual_written;
    }

    // the above problem does not exist under Windows' NamedPipes
    return true;
}
	void Run(SMInvoker &invoker, bigtime_t targetUnblock,
			 bigtime_t targetReply, status_t result, bool deliverySuccess,
			 bool replySuccess, bigtime_t duration)
	{
//printf("SMTester::Run(%lld, %lld, %lx, %d, %d, %lld)\n", targetUnblock,
//targetReply, result, deliverySuccess, replySuccess, duration);
		enum { JITTER = 10000 };
		enum { SETUP_LATENCY = 100000 };
		enum { DELIVERY_LATENCY = 10000 };
		enum { TARGET_HEAD_START = 1000 };
		if (targetUnblock == 0)
			targetUnblock = -TARGET_HEAD_START;
		// create the target
		SMTarget *target = NULL;
		switch (fTargetKind) {
			case TARGET_UNINITIALIZED:
				target = new SMTarget;
				break;
			case TARGET_LOCAL_PREFERRED:
				target = new LocalSMTarget(true);
				break;
			case TARGET_LOCAL_SPECIFIC:
				target = new LocalSMTarget(false);
				break;
			case TARGET_REMOTE_PREFERRED:
				target = new RemoteSMTarget(true);
				break;
			case TARGET_REMOTE_SPECIFIC:
				target = new RemoteSMTarget(false);
				break;
		}
		AutoDeleter<SMTarget> deleter(target);
		// create the reply target
		SMReplyTarget replyTarget;
		// init the target and send the message
		BHandler *replyHandler = replyTarget.Handler();
		BMessenger replyMessenger = replyTarget.Messenger();
		bigtime_t startTime = system_time() + SETUP_LATENCY;
		target->Init(startTime + targetUnblock, targetReply);
		BMessenger targetMessenger = target->Messenger();
		snooze_until(startTime, B_SYSTEM_TIMEBASE);
		status_t actualResult = invoker.Invoke(targetMessenger, replyHandler,
											   replyMessenger);
		bigtime_t actualDuration = system_time() - startTime;
//printf("duration: %lld vs %lld\n", actualDuration, duration);
		// We need to wait for the reply, if reply mode is asynchronous.
		snooze_until(startTime + targetUnblock + targetReply
					 + 2 * DELIVERY_LATENCY, B_SYSTEM_TIMEBASE);
		bool actualReplySuccess = invoker.ReplySuccess();
		if (!invoker.DirectReply())
			actualReplySuccess = replyTarget.ReplySuccess();
		// check the results
if (actualResult != result)
printf("result: %lx vs %lx\n", actualResult, result);
		CHK(actualResult == result);
		CHK(target->DeliverySuccess() == deliverySuccess);
		CHK(actualReplySuccess == replySuccess);
		CHK(actualDuration > duration - JITTER
			&& actualDuration < duration + JITTER);
	}
std::string resultDateInJson(const UDate& date)
{
    UErrorCode status = U_ZERO_ERROR;
    Calendar* cal = Calendar::createInstance(status);
    if (!cal) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::resultInJson: failed to create Calendar instance: %d",
                status);
        return errorInJson(UNKNOWN_ERROR, "Failed to create Calendar instance!");
    }
    std::auto_ptr<Calendar> deleter(cal);

    cal->setTime(date, status);
    if (status != U_ZERO_ERROR && status != U_ERROR_WARNING_START) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::resultInJson: failed to setTime: %d",
                status);
        return errorInJson(UNKNOWN_ERROR, "Failed to set Calendar time!");
    }

    Json::Value result;
    result["year"] = cal->get(UCAL_YEAR, status);
    result["month"] = cal->get(UCAL_MONTH, status);
    result["day"] = cal->get(UCAL_DAY_OF_MONTH, status);
    result["hour"] = cal->get(UCAL_HOUR, status);
    result["minute"] = cal->get(UCAL_MINUTE, status);
    result["second"] = cal->get(UCAL_SECOND, status);
    result["millisecond"] = cal->get(UCAL_MILLISECOND, status);

    Json::Value root;
    root["result"] = result;

    Json::FastWriter writer;
    return writer.write(root);
}
示例#5
0
RegionSnapshot dense_region(
  RegionType region_type,
  void *start_addr, void* permanent_addr, size_t size)
{
  simgrid::mc::RegionSnapshot::flat_data_ptr data;
  if (!_sg_mc_ksm)
    data = simgrid::mc::RegionSnapshot::flat_data_ptr((char*) malloc(size));
  else {
    char* ptr = (char*) mmap(nullptr, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE, -1, 0);
    if (ptr == MAP_FAILED)
      throw std::bad_alloc();
    simgrid::mc::data_deleter deleter(
      simgrid::mc::data_deleter::Munmap, size);
    data = simgrid::mc::RegionSnapshot::flat_data_ptr(ptr, deleter);
  }
  mc_model_checker->process().read_bytes(data.get(), size,
    remote(permanent_addr),
    simgrid::mc::ProcessIndexDisabled);
  if (_sg_mc_ksm)
    // Mark the region as mergeable *after* we have written into it.
    // There no point to let KSM do the hard work before that.
    madvise(data.get(), size, MADV_MERGEABLE);

  simgrid::mc::RegionSnapshot region(
    region_type, start_addr, permanent_addr, size);
  region.flat_data(std::move(data));

  XBT_DEBUG("New region : type : %s, data : %p (real addr %p), size : %zu",
            to_cstr(region_type), region.flat_data(), permanent_addr, size);
  return std::move(region);
}
int main()
{
    {
        boost::shared_array<X> p;

        BOOST_TEST(boost::get_deleter<void>(p) == 0);
        BOOST_TEST(boost::get_deleter<void const>(p) == 0);
        BOOST_TEST(boost::get_deleter<int>(p) == 0);
        BOOST_TEST(boost::get_deleter<int const>(p) == 0);
        BOOST_TEST(boost::get_deleter<X>(p) == 0);
        BOOST_TEST(boost::get_deleter<X const>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter const>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter2>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter2 const>(p) == 0);
    }

    {
        boost::shared_array<X> p(new X[1]);

        BOOST_TEST(boost::get_deleter<void>(p) == 0);
        BOOST_TEST(boost::get_deleter<void const>(p) == 0);
        BOOST_TEST(boost::get_deleter<int>(p) == 0);
        BOOST_TEST(boost::get_deleter<int const>(p) == 0);
        BOOST_TEST(boost::get_deleter<X>(p) == 0);
        BOOST_TEST(boost::get_deleter<X const>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter const>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter2>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter2 const>(p) == 0);
    }

    {
        X x[1];
        boost::shared_array<X> p(x, deleter());

        BOOST_TEST(boost::get_deleter<void>(p) == 0);
        BOOST_TEST(boost::get_deleter<void const>(p) == 0);
        BOOST_TEST(boost::get_deleter<int>(p) == 0);
        BOOST_TEST(boost::get_deleter<int const>(p) == 0);
        BOOST_TEST(boost::get_deleter<X>(p) == 0);
        BOOST_TEST(boost::get_deleter<X const>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter2>(p) == 0);
        BOOST_TEST(boost::get_deleter<deleter2 const>(p) == 0);

        deleter * q = boost::get_deleter<deleter>(p);

        BOOST_TEST(q != 0);
        BOOST_TEST(q->data == 0);

        q->data = 17041;

        deleter const * r = boost::get_deleter<deleter const>(p);

        BOOST_TEST(r == q);
        BOOST_TEST(r->data == 17041);
    }

    return boost::report_errors();
}
示例#7
0
 inline result_type make_pointer(value_type* ptr, boost::non_type<
     factory_alloc_propagation,factory_alloc_for_pointee_and_deleter>)
 const
 {
     return result_type(ptr,deleter(this->get_allocator()),
         this->get_allocator());
 }
status_t
BPhotoContactField::Unflatten(type_code code,
	const void* buffer,	ssize_t size)
{
	BMemoryIO data(buffer, size);
	status_t ret = BContactField::Unflatten(code, &data);
	if (ret != B_OK)
		return ret;

	BMessage msg;
	ssize_t destSize;
	data.Read(&destSize, sizeof(destSize));

	if (destSize < 1) {
		fBitmap = NULL;
		return B_OK;
	}

	void* buf = malloc(destSize);
	MemoryDeleter deleter(buf);
	data.Read(buf, destSize);

	BMemoryIO dest(buf, destSize);
	msg.Unflatten(&dest);

	fBitmap = new BBitmap(&msg);

	return fBitmap->InitCheck();
}
示例#9
0
    void AudioOutputDeviceManager::removeDeviceEventProc(
        int                                                 _card
        , std::multimap< int, const AudioOutputDevice * > & _devices
    )
    {
        auto    iterators = _devices.equal_range( _card );

        if( iterators.first == _devices.end() ) {
            return;
        }

        DevicesDeleter  deleter(
            _devices
            , iterators
        );

        std::for_each(
            iterators.first
            , iterators.second
            , [
                this
            ]
            (
                std::pair< const int, const AudioOutputDevice * > & _pair
            )
            {
                const auto  DEVICE = _pair.second;

                this->callDisconnectEventHandler(
                    *DEVICE
                );
            }
        );
    }
示例#10
0
文件: RBuffer.c 项目: tml/RayLanguage
RBuffer* makeRBufferOptions(size_t startSize, size_t objectCount) {
    RBuffer *object = allocator(RBuffer);
    if(object != nil) {
        // allocation of buffer
        master(object, RData) = makeRDataBytes(arrayAllocator(byte, startSize), startSize);
        if(master(object, RData) != nil) {

            // allocation of sizes array
            object->sizesArray = arrayAllocator(RRange, objectCount);

            if(object->sizesArray  != nil) {
                object->classId     = registerClassOnce(toString(RBuffer));
                object->freePlaces  = objectCount;
                object->count       = 0;
                object->totalPlaced = 0;
#ifdef RAY_BUFFER_THREAD_SAFE
                mutexWithType(&object->mutex, RMutexRecursive);
#endif
            } else {
                RError("RBuffer. Allocation of sizes array failed.", object);
                deleter(master(object, RData), RData);
            }
        } else {
            RError("RBuffer. Allocation of master RData failed.", object);
            deallocator(object);
            object = nil;
        }
    }
    return object;
}
示例#11
0
Session::Session(S_Connection conn, sr_datastore_t datastore, const sr_sess_options_t opts, \
                 const char *user_name)
{
    int ret;
    _opts = opts;
    _datastore = datastore;
    _conn = nullptr;
    _sess = nullptr;
    S_Deleter deleter(new Deleter(_sess));

    if (user_name == nullptr) {
        /* start session */
        ret = sr_session_start(conn->_conn, _datastore, _opts, &_sess);
        if (SR_ERR_OK != ret) {
            goto cleanup;
        }
    } else {
        /* start session */
        ret = sr_session_start_user(conn->_conn, user_name, _datastore, _opts, &_sess);
        if (SR_ERR_OK != ret) {
            goto cleanup;
        }
    }

    _deleter = deleter;
    _conn = conn;
    return;

cleanup:
    throw_exception(ret);
}
示例#12
0
std::shared_ptr<T> makeShared(Args&&... args) {
    return std::shared_ptr<T>(new T(std::forward<Args>(args)...),
                              [](T* instance) {
                                  auto&& deleter = internal::getDeleter<T>();
                                  deleter(instance);
                              });
}
示例#13
0
void
TBarWindow::AddItem(BMessage* message)
{
	DeskbarShelf shelf = B_DESKBAR_TRAY;
	entry_ref ref;
	int32 id = 999;
	BMessage reply;
	status_t err = B_ERROR;

	BMessage* archivedView = new BMessage();
	ObjectDeleter<BMessage> deleter(archivedView);
	if (message->FindMessage("view", archivedView) == B_OK) {
#if SHELF_AWARE
		message->FindInt32("shelf", &shelf);
#endif
		err = fBarView->AddItem(archivedView, shelf, &id);
		if (err == B_OK) {
			// Detach the deleter since AddReplicant is taking ownership
			// on success. This should be changed on server side.
			deleter.Detach();
		}
	} else if (message->FindRef("addon", &ref) == B_OK) {
		BEntry entry(&ref);
		err = entry.InitCheck();
		if (err == B_OK)
			err = fBarView->AddItem(&entry, shelf, &id);
	}

	if (err == B_OK)
		reply.AddInt32("id", id);
	else
		reply.AddInt32("error", err);

	message->SendReply(&reply);
}
 ~untyped_heap_storage()
 {
     if (pointer)
     {
         deleter();
     }
 }
示例#15
0
int main()
{
    boost::shared_ptr<X> p( new X, deleter() );

    test_get_deleter( p );

    return boost::report_errors();
}
示例#16
0
文件: ahci_port.cpp 项目: DonCN/haiku
void
AHCIPort::ScsiUnmap(scsi_ccb* request, scsi_unmap_parameter_list* unmapBlocks)
{
	// Determine how many ranges we'll need
	// We assume that the SCSI unmap ranges cannot be merged together
	uint32 scsiRangeCount = B_BENDIAN_TO_HOST_INT16(
		unmapBlocks->block_data_length) / sizeof(scsi_unmap_block_descriptor);
	uint32 lbaRangeCount = 0;
	for (uint32 i = 0; i < scsiRangeCount; i++) {
		lbaRangeCount += ((uint32)B_BENDIAN_TO_HOST_INT32(
			unmapBlocks->blocks[i].block_count) + 65534) / 65535;
	}

	uint32 lbaRangesSize = lbaRangeCount * sizeof(uint64);
	uint64* lbaRanges = (uint64*)malloc(lbaRangesSize);
	if (lbaRanges == NULL) {
		TRACE("out of memory when allocating %" B_PRIu32 " unmap ranges\n",
			lbaRangeCount);
		request->subsys_status = SCSI_REQ_ABORTED;
		gSCSI->finished(request, 1);
		return;
	}

	MemoryDeleter deleter(lbaRanges);

	for (uint32 i = 0, scsiIndex = 0; scsiIndex < scsiRangeCount; scsiIndex++) {
		uint64 lba = (uint64)B_BENDIAN_TO_HOST_INT64(
			unmapBlocks->blocks[scsiIndex].lba);
		uint64 blocksLeft = (uint32)B_BENDIAN_TO_HOST_INT32(
			unmapBlocks->blocks[scsiIndex].block_count);
		while (blocksLeft > 0) {
			uint16 blocks = blocksLeft > 65535 ? 65535 : (uint16)blocksLeft;
			lbaRanges[i++] = B_HOST_TO_LENDIAN_INT64(
				((uint64)blocks << 48) | lba);
			lba += blocks;
			blocksLeft -= blocks;
		}
	}

	sata_request sreq;
	sreq.SetATA48Command(ATA_COMMAND_DATA_SET_MANAGEMENT, 0,
		(lbaRangesSize + 511) / 512);
	sreq.SetFeature(1);
	sreq.SetData(lbaRanges, lbaRangesSize);

	ExecuteSataRequest(&sreq);
	sreq.WaitForCompletion();

	if ((sreq.CompletionStatus() & ATA_ERR) != 0) {
		TRACE("trim failed (%" B_PRIu32 " ranges)!\n", lbaRangeCount);
		request->subsys_status = SCSI_REQ_CMP_ERR;
	} else
		request->subsys_status = SCSI_REQ_CMP;

	request->data_resid = 0;
	request->device_status = SCSI_STATUS_GOOD;
	gSCSI->finished(request, 1);
}
示例#17
0
RCString* stringFromFile(const char *filename) {
    RByteArray *content = contentOfFile(filename);
    RCString   *result = RSC((const char *)content->array);
    deleter(content, RByteArray);
    ifError(result == nil,
            RError1("stringFromFile. Can't create string from \"%s\".", result, filename)
    );
    return result;
}
示例#18
0
 void reset()
 {
     if(!_empty)
     {
         deleter(_val);
         _val = {};
         _empty = true;
     }
 }
std::string GlobalizationNDK::stringToDate(const std::string& args)
{
    if (args.empty())
        return errorInJson(PARSING_ERROR, "No dateString provided!");

    Json::Reader reader;
    Json::Value root;
    bool parse = reader.parse(args, root);

    if (!parse) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::stringToDate: invalid json data: %s",
                args.c_str());
        return errorInJson(PARSING_ERROR, "Parameters not valid json format!");
    }

    Json::Value dateString = root["dateString"];
    if (!dateString.isString()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::stringToDate: invalid dateString type: %d",
                dateString.type());
        return errorInJson(PARSING_ERROR, "dateString not a string!");
    }

    std::string dateValue = dateString.asString();
    if (dateValue.empty()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::stringToDate: empty dateString.");
        return errorInJson(PARSING_ERROR, "dateString is empty!");
    }

    Json::Value options = root["options"];

    DateFormat::EStyle dstyle, tstyle;
    std::string error;
    if (!handleDateOptions(options, dstyle, tstyle, error))
        return errorInJson(PARSING_ERROR, error);

    const Locale& loc = Locale::getDefault();
    DateFormat* df = DateFormat::createDateTimeInstance(dstyle, tstyle, loc);

    if (!df) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::stringToDate: unable to create DateFormat instance!");
        return errorInJson(UNKNOWN_ERROR, "Unable to create DateFormat instance!");
    }
    std::auto_ptr<DateFormat> deleter(df);

    UnicodeString uDate = UnicodeString::fromUTF8(dateValue);
    UErrorCode status = U_ZERO_ERROR;
    UDate date = df->parse(uDate, status);

    // Note: not sure why U_ERROR_WARNING_START is returned when parse succeeded.
    if (status != U_ZERO_ERROR && status != U_ERROR_WARNING_START) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::stringToDate: DataFormat::parse error: %d: %s",
                status, dateValue.c_str());
        return errorInJson(PARSING_ERROR, "Failed to parse dateString!");
    }

    return resultDateInJson(date);
}
示例#20
0
	void OpenglObjectManager::deleteObject(GLuint &id)
	{
		if(--refCounts[id] == 0)
		{
			if(deleter) deleter(1, &id);
			else deleter2(id);
			refCounts.erase(id);
		}
	}
std::string GlobalizationNDK::getDatePattern(const std::string& args)
{
    DateFormat::EStyle dstyle = DateFormat::kShort, tstyle = DateFormat::kShort;

    if (!args.empty()) {
        Json::Reader reader;
        Json::Value root;
        bool parse = reader.parse(args, root);

        if (!parse) {
            slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDatePattern: invalid json data: %s",
                    args.c_str());
            return errorInJson(PARSING_ERROR, "Parameters not valid json format!");
        }

        Json::Value options = root["options"];

        std::string error;
        if (!handleDateOptions(options, dstyle, tstyle, error))
            return errorInJson(PARSING_ERROR, error);
    }

    UErrorCode status = U_ZERO_ERROR;
    const Locale& loc = Locale::getDefault();
    DateFormat* df = DateFormat::createDateTimeInstance(dstyle, tstyle, loc);

    if (!df) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDatePattern: unable to create DateFormat instance!");
        return errorInJson(UNKNOWN_ERROR, "Unable to create DateFormat instance!");
    }
    std::auto_ptr<DateFormat> deleter(df);

    if (df->getDynamicClassID() != SimpleDateFormat::getStaticClassID()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::getDatePattern: DateFormat instance not SimpleDateFormat!");
        return errorInJson(UNKNOWN_ERROR, "DateFormat instance not SimpleDateFormat!");
    }

    SimpleDateFormat* sdf = (SimpleDateFormat*) df;

    UnicodeString pt;
    sdf->toPattern(pt);
    std::string ptUtf8;
    pt.toUTF8String(ptUtf8);

    const TimeZone& tz = sdf->getTimeZone();

    UnicodeString tzName;
    tz.getDisplayName(tzName);
    std::string tzUtf8;
    tzName.toUTF8String(tzUtf8);

    int utc_offset = tz.getRawOffset() / 1000; // UTC_OFFSET in seconds.
    int dst_offset = tz.getDSTSavings() / 1000; // DST_OFFSET in seconds;

    return resultInJson(ptUtf8, tzUtf8, utc_offset, dst_offset);
}
示例#22
0
bool delete_recursive(const std::string &path)
{
    struct stat sb;
    if (stat(path.c_str(), &sb) < 0 && errno == ENOENT) {
        // Don't fail if directory does not exist
        return true;
    }

    RecursiveDeleter deleter(path);
    return deleter.run();
}
示例#23
0
status_t
BBufferConsumer::SetOutputBuffersFor(const media_source &source,
	const media_destination &destination, BBufferGroup *group, void *user_data,
	int32 *change_tag, bool will_reclaim, void *_reserved_)
{
	CALLED();

	if (IS_INVALID_SOURCE(source))
		return B_MEDIA_BAD_SOURCE;
	if (IS_INVALID_DESTINATION(destination))
		return B_MEDIA_BAD_DESTINATION;

	int32 buffer_count = 0;

	if (group > 0) {
		if (group->CountBuffers(&buffer_count) != B_OK)
			return B_ERROR;
	}

	size_t size = sizeof(producer_set_buffer_group_command)
		+ buffer_count * sizeof(media_buffer_id);

	producer_set_buffer_group_command *command
		= static_cast<producer_set_buffer_group_command *>(malloc(size));
	MemoryDeleter deleter(command);

	command->source = source;
	command->destination = destination;
	command->user_data = user_data;
	command->change_tag = NewChangeTag();

	BBuffer *buffers[buffer_count];
	if (buffer_count != 0) {
		if (group->GetBufferList(buffer_count, buffers) != B_OK)
			return B_ERROR;
		for (int32 i = 0; i < buffer_count; i++)
			command->buffers[i] = buffers[i]->ID();
	}

	command->buffer_count = buffer_count;

	if (change_tag != NULL)
		*change_tag = command->change_tag;

	status_t status = SendToPort(source.port, PRODUCER_SET_BUFFER_GROUP,
		command, size);

	if (status == B_OK) {
		// XXX will leak memory if port write failed
		delete fDeleteBufferGroup;
		fDeleteBufferGroup = will_reclaim ? NULL : group;
	}
	return status;
}
示例#24
0
status_t
BNetworkRoster::GetNextInterface(uint32* cookie,
                                 BNetworkInterface& interface) const
{
    // TODO: think about caching the interfaces!

    if (cookie == NULL)
        return B_BAD_VALUE;

    // get a list of all interfaces

    int socket = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (socket < 0)
        return errno;

    FileDescriptorCloser closer(socket);

    ifconf config;
    config.ifc_len = sizeof(config.ifc_value);
    if (ioctl(socket, SIOCGIFCOUNT, &config, sizeof(struct ifconf)) < 0)
        return errno;

    size_t count = (size_t)config.ifc_value;
    if (count == 0)
        return B_BAD_VALUE;

    char* buffer = (char*)malloc(count * sizeof(struct ifreq));
    if (buffer == NULL)
        return B_NO_MEMORY;

    MemoryDeleter deleter(buffer);

    config.ifc_len = count * sizeof(struct ifreq);
    config.ifc_buf = buffer;
    if (ioctl(socket, SIOCGIFCONF, &config, sizeof(struct ifconf)) < 0)
        return errno;

    ifreq* interfaces = (ifreq*)buffer;
    ifreq* end = (ifreq*)(buffer + config.ifc_len);

    for (uint32 i = 0; interfaces < end; i++) {
        interface.SetTo(interfaces[0].ifr_name);
        if (i == *cookie) {
            (*cookie)++;
            return B_OK;
        }

        interfaces = (ifreq*)((uint8*)interfaces
                              + _SIZEOF_ADDR_IFREQ(interfaces[0]));
    }

    return B_BAD_VALUE;
}
示例#25
0
 void reset(element_type val)
 {
     if(!_empty)
     {
         deleter(_val);
     }
     else
     {
         _empty = false;
     }
     _val = val;
 }
std::string GlobalizationNDK::dateToString(const std::string& args)
{
    if (args.empty())
        return errorInJson(PARSING_ERROR, "No date provided!");

    Json::Reader reader;
    Json::Value root;
    bool parse = reader.parse(args, root);

    if (!parse) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::dateToString: invalid json data: %s",
                args.c_str());
        return errorInJson(PARSING_ERROR, "Parameters not valid json format!");
    }

    Json::Value date = root["date"];
    if (date.isNull()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::dateToString: no date provided.");
        return errorInJson(PARSING_ERROR, "No date provided!");
    }

    if (!date.isNumeric()) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::dateToString: date is not a numeric: %d.",
                date.type());
        return errorInJson(PARSING_ERROR, "Date in wrong format!");
    }

    Json::Value options = root["options"];

    DateFormat::EStyle dstyle, tstyle;
    std::string error;

    if (!handleDateOptions(options, dstyle, tstyle, error))
        return errorInJson(PARSING_ERROR, error);

    UErrorCode status = U_ZERO_ERROR;
    const Locale& loc = Locale::getDefault();
    DateFormat* df = DateFormat::createDateTimeInstance(dstyle, tstyle, loc);

    if (!df) {
        slog2f(0, ID_G11N, SLOG2_ERROR, "GlobalizationNDK::dateToString: unable to create DateFormat!");
        return errorInJson(UNKNOWN_ERROR, "Unable to create DateFormat instance!");
    }
    std::auto_ptr<DateFormat> deleter(df);

    UnicodeString result;
    df->format(date.asDouble(), result);

    std::string utf8;
    result.toUTF8String(utf8);
    return resultInJson(utf8);
}
示例#27
0
static void _deleteContentsWithChildren(BinaryTreeNode* node, void (*deleter)(void* item))
{
    if (node->left != NULL)
    {
        _deleteContentsWithChildren(node->left, deleter);
    }
    if (node->right != NULL)
    {
        _deleteContentsWithChildren(node->right, deleter);
    }
    deleter(node->item);
    free(node);
}
示例#28
0
 void destroy() // nothrow
 {
    //Self destruction, so get a copy of the allocator
    //(in the future we could move it)
    this_allocator a_copy(*this);
    BOOST_ASSERT(a_copy == *this);
    this_pointer this_ptr (this);
    //Do it now!
    scoped_ptr< this_type, scoped_ptr_dealloc_functor<this_allocator> >
       deleter(this_ptr, a_copy);
    typedef typename this_allocator::value_type value_type;
    ipcdetail::to_raw_pointer(this_ptr)->~value_type();
 }
示例#29
0
void DebuggerServer::accept() {
  int port = RuntimeOption::DebuggerServerPort;
  int backlog = 128;

  Util::HostEnt result;
  if (!Util::safe_gethostbyname("0.0.0.0", result)) {
    return;
  }
  struct sockaddr_in la;
  memcpy((char*)&la.sin_addr, result.hostbuf.h_addr,
         result.hostbuf.h_length);
  la.sin_family = result.hostbuf.h_addrtype;
  la.sin_port = htons((unsigned short)port);

  Socket *sock = new Socket(socket(PF_INET, SOCK_STREAM, 0), PF_INET,
                            "0.0.0.0", port);
  Object deleter(sock);
  if (!sock->valid()) {
    Logger::Error("unable to create debugger server socket");
    return;
  }
  if (bind(sock->fd(), (struct sockaddr *)&la, sizeof(la)) < 0) {
    Logger::Error("unable to bind to port %d for debugger server", port);
    return;
  }
  if (listen(sock->fd(), backlog) < 0) {
    Logger::Error("unable to listen on port %d for debugger server", port);
    return;
  }

  // server loop
  while (!m_stopped) {
    struct pollfd fds[1];
    fds[0].fd = sock->fd();
    fds[0].events = POLLIN|POLLERR|POLLHUP;
    if (poll(fds, 1, POLLING_SECONDS * 1000) == 1 &&
        (fds[0].revents & POLLIN)) {
      struct sockaddr sa;
      socklen_t salen = sizeof(sa);
      Socket *new_sock = new Socket(::accept(sock->fd(), &sa, &salen),
                                    sock->getType());
      SmartPtr<Socket> ret(new_sock);
      if (!new_sock->valid()) {
        Logger::Error("unable to accept incoming debugger request");
        break;
      }
      Debugger::RegisterProxy(ret, false);
    } // else timed out, then we have a chance to check m_stopped bit
  }
}
示例#30
0
void
agg_configuration::add_to_set(vm::tuple *tpl, const ref_count many)
{
   assert(many != 0);
   assert(many > 0 || (many < 0 && !vals.empty()));

   changed = true; // this is important
   
   if(many > 0) {
      
      if(!vals.insert_tuple(tpl, many)) {
         // repeated tuple
         delete tpl;
      }
   } else {
      // to delete
      trie::delete_info deleter(vals.delete_tuple(tpl, -many)); // note the minus sign
      if(deleter.to_delete()) {
         deleter();
      }
      
      delete tpl;
   }
}