Beispiel #1
0
void slay_impl(proc_t **procs, int sig, pid_t pid, int include_children) {
	int i, hit = 0;

	for (i = 0; procs[i]; i++) {
		if (procs[i]->tgid == pid) {
			if (procs[i]->state == 'Z') {
				LOG_V("Not killing PID %d because it's already died (in state 'Z').", pid);
			}
			else {
				LOG_V("Kill PID %d (in state '%c') with signal %d", pid, procs[i]->state, sig);
				kill(pid, sig);
			}
			hit = 1;
		}
		if (include_children && (procs[i]->ppid == pid)) {
			if (procs[i]->state == 'Z') {
				LOG_V("Not killing PID %d because it's already died (in state 'Z').", procs[i]->tgid);
			}
			else
				slay_impl(procs, sig, procs[i]->tid, include_children);
		}
	}
	if (!hit) {
		LOG_V("PID %d was missing from the proc list (while sending signal %d)", pid, sig);
	}
}
Beispiel #2
0
void slay_impl(pid_t *pids, int n, int sig, pid_t pid, int include_children) {
	int i, hit = 0;

	DEBUG_V("slay %d with signal %d", pid, sig);
	kill(pid, sig);
	for (i = 0; i < n; i++) {
		struct proc_bsdinfo info;
		CHECK(proc_pidinfo(pids[i], PROC_PIDTBSDINFO, 0, &info, sizeof info));
		if (info.pbi_pid == pid) {
			if (info.pbi_status == SZOMB) {
				LOG_V("Not killing PID %d because it's already died (in state 'Z').", pid);
			}
			else {
				LOG_V("Kill PID %d (in state 0x%x) with signal %d", pid, info.pbi_status, sig);
				kill(pid, sig);
			}
			hit = 1;
		}
		if (include_children && (info.pbi_ppid == pid)) {
			if (info.pbi_status == SZOMB) {
				LOG_V("Not killing PID %d because it's already died (in state 'Z').", info.pbi_pid);
			}
			else
				slay_impl(pids, n, sig, info.pbi_pid, include_children);
		}
	}
	if (!hit) {
		LOG_V("PID %d was missing from the proc list (while sending signal %d)", pid, sig);
	}
}
//------------------------------------------------------------------------------
mcResult_t CMcKMod::mapWsm(
    uint32_t    len,
    uint32_t    *pHandle,
    addr_t      *pVirtAddr,
    addr_t      *pPhysAddr)
{
    int ret = 0;
    LOG_V(" mapWsm(): len=%d", len);

    if (!isOpen()) {
        LOG_E("no connection to kmod");
        return MC_DRV_ERR_KMOD_NOT_OPEN;
    }

    // mapping response data is in the buffer
struct mc_ioctl_map mapParams = {
    .len = len
};

    ret = ioctl(fdKMod, MC_IO_MAP_WSM, &mapParams);
    if (ret != 0) {
        LOG_ERRNO("ioctl MC_IO_MAP_WSM");
        return MAKE_MC_DRV_KMOD_WITH_ERRNO(errno);
    }

    addr_t virtAddr = ::mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED,
                             fdKMod, mapParams.phys_addr);
    if (virtAddr == MAP_FAILED) {
        LOG_ERRNO("mmap");
        return MAKE_MC_DRV_KMOD_WITH_ERRNO(errno);
    }


    LOG_V(" mapped to %p, handle=%d, phys=%p ", virtAddr,
          mapParams.handle, (addr_t) (mapParams.phys_addr));

    if (pVirtAddr != NULL) {
        *pVirtAddr = virtAddr;
    }

    if (pHandle != NULL) {
        *pHandle = mapParams.handle;
    }

    if (pPhysAddr != NULL) {
        *pPhysAddr = (addr_t) (mapParams.phys_addr);
    }

    return 0;
}
Beispiel #4
0
int main(int argc, const char* argv[])
{
    const char *description = "\n"
        "QtBinPatcher v2.3.0Beta. Tool for patching paths in Qt binaries.\n"
        "Yuri V. Krugloff, 2013-2015. http://www.tver-soft.org\n"
        "Frank Su, 2016. http://mogara.org\n"
        "This is free software released into the public domain.\n"
#ifdef QTCROSS
        "This binary is built for cross compiled Qt.\n"
#endif
        "\n"
    ;

    LOG(description);

    TCmdLineParser CmdLineParser(argc, argv);
    if (CmdLineParser.hasError()) {
        LOG("%s\n", CmdLineParser.errorString().c_str());
        howToUseMessage();
        return -1;
    }
    const TStringListMap& argsMap = CmdLineParser.argsMap();


    std::string ErrorString = TCmdLineChecker::check(argsMap);
    if (!ErrorString.empty()) {
        LOG("%s\n", ErrorString.c_str());
        howToUseMessage();
        return -1;
    }


    TLogger::setVerbose(argsMap.contains(OPT_VERBOSE));
    LOG_SET_FILENAME(argsMap.value(OPT_LOGFILE).c_str());
    LOG_V("%s\n", CmdLineParser.dump().c_str());
    LOG_V("Working directory: \"%s\".\n", Functions::currentDir().c_str());
    LOG_V("Binary file location: \"%s\".\n", argv[0]);

    if (argsMap.contains(OPT_HELP)) {
        howToUseMessage();
        return 0;
    }

    if (argsMap.contains(OPT_VERSION))
        return 0;

    return TQtBinPatcher::exec(argsMap) ? 0 : -1;
}
Beispiel #5
0
Error RoadPoint::SetImage(std::string imagepath){
    Error ret;

    if (imagepath.empty() || TempArchiveDirectory.empty()) {
        Image = ROADPOINT_NO_IMAGE;
    }
    else {
        std::string path(imagepath);
        std::string name(imagepath);

        ret = FileUtils::GetFileName(name);
        if (ret != ERROR_OK) {
            return ERROR_FAIL;
        }

        // Check if the picture is already in the temp archive directory, if not copy the image
        ret = FileUtils::GetFilePath(path);
        if (ret != ERROR_OK) {
            return ERROR_FAIL;
        }

        if (path.compare(TempArchiveDirectory) != 0) {
            LOG_V(TAG, "Copy point image %s into %s", imagepath.c_str(), (TempArchiveDirectory + FILEUTILS_PATH_DELIMITER + name).c_str());
            ret = FileUtils::CopyFile(imagepath, TempArchiveDirectory + FILEUTILS_PATH_DELIMITER + name);
            if (ret != ERROR_OK) {
                return ERROR_FAIL;
            }
        }

        // Set the image field
        Image = name;
    }

    return ret;
}
/**
* mix_videoconfigparamsenc_mpeg4_copy:
* @target: copy to target
* @src: copy from src
* @returns: boolean indicates if copy is successful.
* 
* Copy instance data from @src to @target.
*/
gboolean
mix_videoconfigparamsenc_mpeg4_copy (MixParams * target, const MixParams * src)
{
    MixVideoConfigParamsEncMPEG4 *this_target, *this_src;
    MixParamsClass *root_class;

    LOG_V( "Begin\n");	

    if (MIX_IS_VIDEOCONFIGPARAMSENC_MPEG4 (target)
      && MIX_IS_VIDEOCONFIGPARAMSENC_MPEG4 (src))
    {
      // Cast the base object to this child object
      this_target = MIX_VIDEOCONFIGPARAMSENC_MPEG4 (target);
      this_src = MIX_VIDEOCONFIGPARAMSENC_MPEG4 (src);

      //add properties
      this_target->profile_and_level_indication= this_src->profile_and_level_indication;
      this_target->fixed_vop_time_increment= this_src->fixed_vop_time_increment;      
      this_target->disable_deblocking_filter_idc = this_src->disable_deblocking_filter_idc;

      // Now chainup base class
      root_class = MIX_PARAMS_CLASS (parent_class);

      if (root_class->copy)
	{
	  return root_class->copy (MIX_PARAMS_CAST (target),
				   MIX_PARAMS_CAST (src));
	}
      else
	{
	  return TRUE;
	}
    }
  return FALSE;
}
//------------------------------------------------------------------------------
Connection::~Connection(void)
{
    LOG_V(" closing Connection...");
    if (socketDescriptor != -1)
        close(socketDescriptor);
    LOG_I(" Socket connection closed.");
}
//------------------------------------------------------------------------------
TrustletSession *MobiCoreDevice::registerTrustletConnection(
    Connection                    *connection,
    MC_DRV_CMD_NQ_CONNECT_struct *cmdNqConnect
)
{
    LOG_I(" Registering notification socket with Service session %d.",
          cmdNqConnect->sessionId);
    LOG_V("  Searching sessionId %d with sessionMagic %d",
          cmdNqConnect->sessionId,
          cmdNqConnect->sessionMagic);

    for (trustletSessionIterator_t iterator = trustletSessions.begin();
            iterator != trustletSessions.end();
            ++iterator) {
        TrustletSession *ts = *iterator;

        if (ts != (TrustletSession *) (cmdNqConnect->deviceSessionId)) {
            continue;
        }

        if ( (ts->sessionMagic != cmdNqConnect->sessionMagic)
                || (ts->sessionId != cmdNqConnect->sessionId)) {
            continue;
        }

        ts->notificationConnection = connection;

        LOG_I(" Found Service session, registered connection.");

        return ts;
    }

    LOG_I("registerTrustletConnection(): search failed");
    return NULL;
}
//------------------------------------------------------------------------------
void MobiCoreDriverDaemon::processNotify(Connection  *connection)
{
    // Read entire command data
    MC_DRV_CMD_NOTIFY_struct  cmd;
    //RECV_PAYLOAD_FROM_CLIENT(connection, &cmd);
    void *payload = (void *)((uintptr_t)&cmd + sizeof(mcDrvCommandHeader_t));
    uint32_t payload_len = sizeof(cmd) - sizeof(mcDrvCommandHeader_t);
    uint32_t rlen = connection->readData(payload, payload_len);
    if ((int) rlen < 0) {
        LOG_E("reading from Client failed");
        /* it is questionable, if writing to broken socket has any effect here. */
        // NOTE: notify fails silently
        //writeResult(connection, MC_DRV_RSP_SOCKET_ERROR);
        return;
    }
    if (rlen != payload_len) {
        LOG_E("wrong buffer length %i received from Client", rlen);
        // NOTE: notify fails silently
        //writeResult(connection, MC_DRV_RSP_PAYLOAD_LENGTH_ERROR);
        return;
    }

    // Device required
    MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData);
    if (NULL == device) {
        LOG_V("%s: no device associated with connection", __FUNCTION__);
        // NOTE: notify fails silently
        // writeResult(connection,MC_DRV_RSP_DEVICE_NOT_OPENED);
        return;
    }

    device->notify(connection, cmd.sessionId);
    // NOTE: for notifications there is no response at all
}
//------------------------------------------------------------------------------
void MobiCoreDriverDaemon::processGetMobiCoreVersion(
    Connection  *connection
)
{
    // there is no payload to read

    // Device required
    MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData);
    CHECK_DEVICE(device, connection);

    // Get <t-base version info from secure world.
    mcDrvRspGetMobiCoreVersion_t rspGetMobiCoreVersion;

    mcResult_t mcResult = device->getMobiCoreVersion(&rspGetMobiCoreVersion.payload);

    if (mcResult != MC_DRV_OK) {
        LOG_V("MC GET_MOBICORE_VERSION returned code %d", mcResult);
        writeResult(connection, mcResult);
        return;
    }

    rspGetMobiCoreVersion.header.responseId = MC_DRV_OK;
    connection->writeData(
        &rspGetMobiCoreVersion,
        sizeof(rspGetMobiCoreVersion));
}
Encode_Status VideoEncoderH263::renderSliceParams(EncodeTask *task) {

    VAStatus vaStatus = VA_STATUS_SUCCESS;
    uint32_t sliceHeight;
    uint32_t sliceHeightInMB;

    LOG_V("Begin\n\n");

    sliceHeight = mComParams.resolution.height;
    sliceHeight += 15;
    sliceHeight &= (~15);
    sliceHeightInMB = sliceHeight / 16;

    vaStatus = vaCreateBuffer(
            mVADisplay, mVAContext,
            VAEncSliceParameterBufferType,
            sizeof(VAEncSliceParameterBuffer),
            1, NULL, &mSliceParamBuf);
    CHECK_VA_STATUS_RETURN("vaCreateBuffer");

    VAEncSliceParameterBuffer *sliceParams;
    vaStatus = vaMapBuffer(mVADisplay, mSliceParamBuf, (void **)&sliceParams);
    CHECK_VA_STATUS_RETURN("vaMapBuffer");

    // starting MB row number for this slice
    sliceParams->start_row_number = 0;
    // slice height measured in MB
    sliceParams->slice_height = sliceHeightInMB;
    sliceParams->slice_flags.bits.is_intra = (task->type == FTYPE_I)?1:0;
    sliceParams->slice_flags.bits.disable_deblocking_filter_idc = 0;

    LOG_V("======h263 slice params======\n");
    LOG_I("start_row_number = %d\n", (int) sliceParams->start_row_number);
    LOG_I("slice_height_in_mb = %d\n", (int) sliceParams->slice_height);
    LOG_I("slice.is_intra = %d\n", (int) sliceParams->slice_flags.bits.is_intra);

    vaStatus = vaUnmapBuffer(mVADisplay, mSliceParamBuf);
    CHECK_VA_STATUS_RETURN("vaUnmapBuffer");

    vaStatus = vaRenderPicture(mVADisplay, mVAContext, &mSliceParamBuf, 1);
    CHECK_VA_STATUS_RETURN("vaRenderPicture");

    LOG_V("end\n");
    return ENCODE_SUCCESS;
}
Encode_Status VideoEncoderH263::renderPictureParams(EncodeTask *task) {

    VAStatus vaStatus = VA_STATUS_SUCCESS;
    VAEncPictureParameterBufferH263 h263PictureParams = {};

    LOG_V( "Begin\n\n");

    // set picture params for HW
    if(mAutoReference == false){
        h263PictureParams.reference_picture = task->ref_surface;
        h263PictureParams.reconstructed_picture = task->rec_surface;
    }else {
        h263PictureParams.reference_picture = mAutoRefSurfaces[0];
        h263PictureParams.reconstructed_picture = mAutoRefSurfaces[1];
    }

    h263PictureParams.coded_buf = task->coded_buffer;
    h263PictureParams.picture_width = mComParams.resolution.width;
    h263PictureParams.picture_height = mComParams.resolution.height;
    h263PictureParams.picture_type = (task->type == FTYPE_I) ? VAEncPictureTypeIntra : VAEncPictureTypePredictive;

    LOG_V("======h263 picture params======\n");
    LOG_I( "reference_picture = 0x%08x\n", h263PictureParams.reference_picture);
    LOG_I( "reconstructed_picture = 0x%08x\n", h263PictureParams.reconstructed_picture);
    LOG_I( "coded_buf = 0x%08x\n", h263PictureParams.coded_buf);
//    LOG_I( "coded_buf_index = %d\n", mCodedBufIndex);
    LOG_I( "picture_width = %d\n", h263PictureParams.picture_width);
    LOG_I( "picture_height = %d\n",h263PictureParams.picture_height);
    LOG_I( "picture_type = %d\n\n",h263PictureParams.picture_type);

    vaStatus = vaCreateBuffer(
            mVADisplay, mVAContext,
            VAEncPictureParameterBufferType,
            sizeof(h263PictureParams),
            1,&h263PictureParams,
            &mPicParamBuf);
    CHECK_VA_STATUS_RETURN("vaCreateBuffer");

    vaStatus = vaRenderPicture(mVADisplay, mVAContext, &mPicParamBuf , 1);
    CHECK_VA_STATUS_RETURN("vaRenderPicture");

    LOG_V( "end\n");
    return ENCODE_SUCCESS;
}
Encode_Status VideoEncoderH263::sendEncodeCommand(EncodeTask *task) {

    Encode_Status ret = ENCODE_SUCCESS;
    LOG_V( "Begin\n");

    if (mFrameNum == 0) {
        ret = renderSequenceParams(task);
        CHECK_ENCODE_STATUS_RETURN("renderSequenceParams");
    }

    ret = renderPictureParams(task);
    CHECK_ENCODE_STATUS_RETURN("renderPictureParams");

    ret = renderSliceParams(task);
    CHECK_ENCODE_STATUS_RETURN("renderSliceParams");

    LOG_V( "End\n");
    return ENCODE_SUCCESS;
}
//------------------------------------------------------------------------------
size_t MobiCoreDriverDaemon::writeResult(
    Connection  *connection,
    mcResult_t  code
)
{
    if (0 != code) {
        LOG_V(" sending error code %d", code);
    }
    return connection->writeData(&code, sizeof(mcResult_t));
}
Beispiel #15
0
//------------------------------------------------------------------------------
mcResult_t CMcKMod::mapMCI(
    uint32_t    len,
    uint32_t    *pHandle,
    addr_t      *pVirtAddr,
    addr_t      *pPhysAddr,
    bool        *pReuse)
{
    LOG_I("Mapping MCI: len=%d", len);
    // mapping response data is in the buffer
    struct mc_ioctl_map mapParams = {
        .len = len
    };

    if (!isOpen()) {
        LOG_E("no connection to kmod");
        return MC_DRV_ERR_KMOD_NOT_OPEN;
    }

    int ret = ioctl(fdKMod, MC_IO_MAP_MCI, &mapParams);
    if (ret != 0) {
        LOG_ERRNO("ioctl MC_IO_MAP_MCI");
        return MAKE_MC_DRV_KMOD_WITH_ERRNO(errno);
    }

    addr_t virtAddr = ::mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED,
                             fdKMod, 0);
    if (virtAddr == MAP_FAILED) {
        LOG_ERRNO("mmap");
        return MAKE_MC_DRV_KMOD_WITH_ERRNO(errno);
    }
    unsigned long addr = (unsigned long)virtAddr;
    *pReuse = mapParams.reused;

    LOG_V(" MCI mapped to %p, handle=%d, phys=%p, reused=%s",
          (void *)addr, mapParams.handle, (addr_t) (mapParams.phys_addr),
          mapParams.reused ? "true" : "false");

    if (pVirtAddr != NULL) {
        *pVirtAddr = (void *)addr;
    }

    if (pHandle != NULL) {
        *pHandle = mapParams.handle;
    }

    if (pPhysAddr != NULL) {
        *pPhysAddr = (addr_t) (mapParams.phys_addr);
    }

    // clean memory
    //memset(pMmapResp, 0, sizeof(*pMmapResp));

    return MC_DRV_OK;
}
Encode_Status VideoEncoderH263::renderSequenceParams(EncodeTask *task) {

    VAStatus vaStatus = VA_STATUS_SUCCESS;
    VAEncSequenceParameterBufferH263 h263SequenceParam = {};
    uint32_t frameRateNum = mComParams.frameRate.frameRateNum;
    uint32_t frameRateDenom = mComParams.frameRate.frameRateDenom;

    LOG_V( "Begin\n\n");

    //set up the sequence params for HW
    h263SequenceParam.bits_per_second= mComParams.rcParams.bitRate;
    h263SequenceParam.frame_rate = 
            (unsigned int) (frameRateNum + frameRateDenom /2) / frameRateDenom;   //hard-coded, driver need;
    h263SequenceParam.initial_qp = mComParams.rcParams.initQP;
    h263SequenceParam.min_qp = mComParams.rcParams.minQP;
    h263SequenceParam.intra_period = mComParams.intraPeriod;

    //h263_seq_param.fixed_vop_rate = 30;

    LOG_V("===h263 sequence params===\n");
    LOG_I( "bitrate = %d\n", h263SequenceParam.bits_per_second);
    LOG_I( "frame_rate = %d\n", h263SequenceParam.frame_rate);
    LOG_I( "initial_qp = %d\n", h263SequenceParam.initial_qp);
    LOG_I( "min_qp = %d\n", h263SequenceParam.min_qp);
    LOG_I( "intra_period = %d\n\n", h263SequenceParam.intra_period);

    vaStatus = vaCreateBuffer(
            mVADisplay, mVAContext,
            VAEncSequenceParameterBufferType,
            sizeof(h263SequenceParam),
            1, &h263SequenceParam,
            &mSeqParamBuf);
    CHECK_VA_STATUS_RETURN("vaCreateBuffer");

    vaStatus = vaRenderPicture(mVADisplay, mVAContext, &mSeqParamBuf, 1);
    CHECK_VA_STATUS_RETURN("vaRenderPicture");

    LOG_V( "end\n");
    return ENCODE_SUCCESS;
}
Beispiel #17
0
int accept_erlang_connection(ei_cnode *ec, int listen_sock, ErlConnect *onode) {
	int con, named;
	struct sockaddr_in addr;
	socklen_t len;

	/* Unfortunately we can't print out the address of the connection
	 * attempt if it doesn't succeed, because we don't have the socket
	 * at that stage: the accept() and more happen together inside ei_accept. */
	DEBUG("accepting connection on erlang socket");
	do {
		con = ei_accept(ec, listen_sock, onode);
	} while ((con == ERL_ERROR) && (erl_errno == EINTR));
	if (con == ERL_ERROR) {
		LOG_V("ei_accept failed (%d): %s", erl_errno, strerror(erl_errno));
		return -1;
	}
	len = sizeof addr;
	named = !getpeername(con, (struct sockaddr *)&addr, &len);
	LOG_V("connection from node %s:%d \"%s\""
	, (named ? inet_ntoa(addr.sin_addr) : "?"), (named ? ntohs(addr.sin_port) : -1), onode->nodename);
	return con;
}
Beispiel #18
0
int cleanup_child(int sig, const char *child_name, pid_t child_pid) {
	int rv, status, exit_code = 0;
	char *exit_status;

	if (child_pid == -1)
		return 0;
	/* If we're here because of a signal (arg != 0), pass it on to erld */
	if (sig) {
		LOG_V("passing signal %d to %s", sig, child_name);
		kill(child_pid, sig);
	}
	DEBUG_V("Waiting for %s (pid %d) to exit.", child_name, child_pid);
	while (((rv = waitpid(child_pid, &status, 0)) == -1) && (errno == EINTR))
		/* empty */;
	CHECK(rv);
	get_exit_status(status, &exit_status, &exit_code);
	DEBUG("Wait complete.");
	LOG_V("%s exited with status %d: %s.", child_name, exit_code, exit_status);
	syslog(LOG_INFO, "%s exited with status %d: %s.", child_name, exit_code, exit_status);
	free(exit_status);
	return exit_code;
}
Beispiel #19
0
void fatal_error(const char *file, int line, int e, const char *fmt, ...) {
	va_list ap;
	char *msg;

	va_start(ap, fmt);
	msg = create_fmt_errno_message(file, line, e, fmt, ap);
	va_end(ap);

	LOG_V("%s", msg);
	syslog(LOG_ERR, "%s", msg);
	free(msg);
	exit(1);
}
//------------------------------------------------------------------------------
mcResult_t CMcKMod::mapWsm(
    uint32_t    len,
    uint32_t    *pHandle,
    addr_t      *pVirtAddr)
{
    int ret = 0;
    LOG_V(" mapWsm(): len=%d", len);

    if (!isOpen()) {
        LOG_E("no connection to kmod");
        return MC_DRV_ERR_KMOD_NOT_OPEN;
    }

    // mapping response data is in the buffer
    struct mc_ioctl_map mapParams = { len : len };
//------------------------------------------------------------------------------
size_t Connection::readData(void *buffer, uint32_t len, int32_t timeout)
{
    size_t ret = 0;
    struct timeval tv;
    struct timeval *ptv = NULL;
    fd_set readfds;

    assert(NULL != buffer);
    assert(socketDescriptor != -1);

    if (timeout >= 0) {
        // Calculate timeout value
        tv.tv_sec = timeout / 1000;
        tv.tv_usec = (timeout - (tv.tv_sec * 1000)) * 1000;
        ptv = &tv;
    }

    FD_ZERO(&readfds);
    FD_SET(socketDescriptor, &readfds);
    ret = select(socketDescriptor + 1, &readfds, NULL, NULL, ptv);

    // check for read error
    if ((int)ret == -1) {
        LOG_ERRNO("select");
        return -1;
    }

    // Handle case of no descriptor ready
    if (ret == 0) {
        LOG_W(" Timeout during select() / No more notifications.");
        return -2;
    }

    // one or more descriptors are ready

    // finally check if fd has been selected -> must socketDescriptor
    if (!FD_ISSET(socketDescriptor, &readfds)) {
        LOG_ERRNO("no fd is set, select");
        return ret;
    }

    ret = recv(socketDescriptor, buffer, len, MSG_DONTWAIT);
    if (ret == 0) {
        LOG_V(" readData(): peer orderly closed connection.");
    }

    return ret;
}
/**
 * mix_videoconfigparamsenc_dup:
 * @obj: a #MixVideoConfigParamsEnc object
 * @returns: a newly allocated duplicate of the object.
 *
 * Copy duplicate of the object.
 */
MixParams *
mix_videoconfigparamsenc_dup(const MixParams * obj) {
    MixParams *ret = NULL;
    
    LOG_V( "Begin\n");	
    
    if (MIX_IS_VIDEOCONFIGPARAMSENC(obj)) {
        MixVideoConfigParamsEnc *duplicate = mix_videoconfigparamsenc_new();
        if (mix_videoconfigparamsenc_copy(MIX_PARAMS(duplicate), MIX_PARAMS(obj))) {

			ret = MIX_PARAMS(duplicate);
		} else {
			mix_videoconfigparamsenc_unref(duplicate);
		}
	}
	return ret;
}
Beispiel #23
0
static __inline__ void
fin_self(media_sinker *sinker)
{
	LOCK_DEL(sinker->lock);

	if (sinker->host)
	{
		session_unref(sinker->host);
	}

	if(sinker->medium)
	{
		media_unref(sinker->medium);
	}

	atomic_dec(&media_sinker_objs);
	LOG_V(
		"Media sinker objs count: %d.",
		atomic_get(&media_sinker_objs)
	);
}
Beispiel #24
0
//------------------------------------------------------------------------------
mcResult_t CMcKMod::free(uint32_t handle, addr_t buffer, uint32_t len)
{
    LOG_V("free(): handle=%d", handle);

    if (!isOpen()) {
        LOG_E("no connection to kmod");
        return MC_DRV_ERR_KMOD_NOT_OPEN;
    }

    // Even if unmap fails we still go on with our request
    if (::munmap(buffer, len)) {
        LOG_I("buffer = %p, len = %d", buffer, len);
        LOG_ERRNO("mmap failed");
    }

    int ret = ioctl(fdKMod, MC_IO_FREE, handle);
    if (ret != 0) {
        LOG_ERRNO("ioctl MC_IO_FREE");
        return MAKE_MC_DRV_KMOD_WITH_ERRNO(errno);
    }

    return MC_DRV_OK;
}
//------------------------------------------------------------------------------
void MobiCoreDriverDaemon::processUnmapBulkBuf(Connection *connection)
{
    MC_DRV_CMD_UNMAP_BULK_BUF_struct cmd;
    RECV_PAYLOAD_FROM_CLIENT(connection, &cmd)

    // Device required
    MobiCoreDevice *device = (MobiCoreDevice *) (connection->connectionData);
    CHECK_DEVICE(device, connection);

    // Unmap bulk memory from secure world
    uint32_t mcResult = device->unmapBulk(connection, cmd.sessionId, cmd.handle,
                                          cmd.secureVirtualAdr, cmd.lenBulkMem);

    if (mcResult != MC_DRV_OK) {
        LOG_V("MCP UNMAP returned code %d", mcResult);
        writeResult(connection, mcResult);
        return;
    }

    // TODO-2012-09-06-haenellu: Think about not ignoring the error case.
    device->unlockWsmL2(cmd.handle);

    writeResult(connection, MC_DRV_OK);
}
Beispiel #26
0
/* Return values:
 * - -1 error
 * - 0 nothing
 * - 1 detach */
int cnode_read(int fd, char **ret_str) {
	ei_x_buff x;
	erlang_msg msg;
	int result, index, o_index, arity, type, size, ver, rv = CNODE_IGNORE;
	const char *str;
	char *s;
	char atom[MAXATOMLEN];

	ei_x_new(&x);
	/* We don't use xreceive because we're not expecting any big
	   messages and we don't want a huge term to cause our memory
	   usage to blow out and crash us. */
	/* Use a timeout of 1 millisecond even though we know we'll
	   be able to read at least some bytes, just to be sure we
	   do not get blocked (for long). Really we want to specify
	   "no timeout but don't block" to ei_receive_msg but it
	   doesn't provide that functionality. */
	result = ei_receive_msg_tmo(fd, &msg, &x, 1);

	if (result < 0) {
		LOG_V("ei_receive_msg_tmo failed (%d): %s", erl_errno, strerror(erl_errno));
		switch (erl_errno) {
			case ETIMEDOUT:
				DEBUG("ei_receive_msg_tmo: timed out.");
				break;
			case EAGAIN:
				DEBUG("ei_receive_msg_tmo: try again");
				break;
			case EMSGSIZE:
				DEBUG("ei_receive_msg_tmo: message too big");
				rv = CNODE_ERROR;
				break;
			case EIO:
				LOG_V("ei_receive_msg_tmo: IO error (%d: %s)", errno, strerror(errno));
				if (errno != EAGAIN)
					rv = CNODE_ERROR;
				break;
		}
	}
	else {
		if (result == ERL_TICK) { /* nothing to do */
			DEBUG("node tick message");
		}
		else {
			switch (msg.msgtype) {
				case ERL_SEND: str = "SEND"; break;
				case ERL_REG_SEND: str = "REG_SEND"; break;
				case ERL_LINK: str = "LINK"; break;
				case ERL_UNLINK: str = "UNLINK"; break;
				default: str = "unknown";
			}
			if (msg.msgtype == ERL_REG_SEND) {
				index = 0;

				if (ei_decode_version(x.buff, &index, &ver) == 0) {
					// DEBUG_V("data ver %d", ver);
				}

				o_index = index;

				if (ei_decode_atom(x.buff, &index, atom) == 0) {
					// DEBUG_V("atom %s", atom);
					if (!strcmp(atom, "detach")) {
						DEBUG("got detach message");
						rv = CNODE_DETACH;
					}
					else if (!strcmp(atom, "thump")) {
						rv = CNODE_THUMP;
					}
					else {
						DEBUG("message is unknown");
					}
				}
				else if (ei_decode_tuple_header(x.buff, &index, &arity) == 0) {
					if ((arity == 2)
					&& !ei_decode_atom(x.buff, &index, atom) && !strcmp(atom, "stdout")
					&& !ei_get_type(x.buff, &index, &type, &size)
					&& (type == ERL_STRING_EXT)) {
						*ret_str = (char *)malloc(size + 1);
						if (ei_decode_string(x.buff, &index, *ret_str)) {
							LOG("Failed to decode string for stdout message.");
							free(*ret_str);
							rv = CNODE_ERROR;
						}
						else
							rv = CNODE_STR;
					}
					else {
						index = o_index; // Re-set index to beginning of term.
						s = 0;
						ei_s_print_term(&s, x.buff, &index);
						LOG_V("Unknown tuple (arity %d): %s", arity, s);
						free(s);
					}
				}
				else {
					s = 0;
					ei_s_print_term(&s, x.buff, &index);
					LOG_V("Unknown message: %s", s);
					free(s);
				}
			}
			else {
				DEBUG_V("received %s message", str);
			}
		}
	}
	ei_x_free(&x);
	return rv;
}
Beispiel #27
0
static bool parse_element(FILE *in, int state, element_t *out)
{
    tag_t tag;
    element_t item;
    int length;
    char vr[3] = "  ";
    char tmp_buff[128];
    bool extra_len = false;
    int i;

    if (remain_size(in) == 0) return false;
    tag.group = READ(uint16_t, in);
    tag.element  = READ(uint16_t, in);

    // The meta data is always in explicit form.
    if (tag.group == 0x0002) state &= ~STATE_IMPLICIT_VR;

    if (state & STATE_IMPLICIT_VR) {
        length = READ(uint32_t, in);
        // XXX: Handle this with a static table.
        if (tag.v == TAG_INSTANCE_NUMBER.v) sprintf(vr, "IS");
        if (tag.v == TAG_SLICE_LOCATION.v) sprintf(vr, "DS");
        if (tag.v == TAG_SAMPLES_PER_PIXEL.v) sprintf(vr, "US");
        if (tag.v == TAG_ROWS.v) sprintf(vr, "US");
        if (tag.v == TAG_COLUMNS.v) sprintf(vr, "US");
        if (tag.v == TAG_BITS_ALLOCATED.v) sprintf(vr, "US");
        if (tag.v == TAG_BITS_STORED.v) sprintf(vr, "US");
        if (tag.v == TAG_HIGH_BIT.v) sprintf(vr, "US");
        if (tag.v == TAG_PIXEL_DATA.v) sprintf(vr, "OB");
    } else {
        fread(vr, 2, 1, in);
        for (i = 0; i < ARRAY_SIZE(EXTRA_LEN_VRS); i++) {
            if (strncmp(vr, EXTRA_LEN_VRS[i], 2) == 0) {
                extra_len = true;
                break;
            }
        }
        if (extra_len) {
            READ(uint16_t, in);     // Reserved 2 bytes
            length = READ(uint32_t, in);
        } else {
            length = READ(uint16_t, in);
        }
    }

    LOG_V("(%.4x, %.4x) %s, length:%d", tag.group, tag.element, vr, length);

    // Read a sequence of undefined length.
    if (length == 0xffffffff && (streq(vr, "SQ") || streq(vr, "OW"))) {
        while (true) {
            parse_element(in, STATE_SEQUENCE_ITEM | STATE_IMPLICIT_VR, &item);
            if (item.tag.v == TAG_SEQ_DEL.v) {
                break;
            }
            if (item.tag.v != TAG_ITEM.v)
                LOG_E("Expected item tag");
        }
    }
    if (state & STATE_SEQUENCE_ITEM && length == 0xffffffff) {
        while (true) {
            parse_element(in, 0, &item);
            if (item.tag.v == TAG_ITEM_DEL.v) {
                break;
            }
        }
    }

    if (out) {
        out->tag = tag;
        out->length = length;
        memcpy(out->vr, vr, 2);
    }

    // For the moment we just skip the data.
    if (length != 0xffffffff) {
        CHECK(length >= 0);
        if (length > remain_size(in)) {
            CHECK(false);
        }
        if (out && length == 2 && strncmp(vr, "US", 2) == 0) {
            out->value.us = READ(uint16_t, in);
        }  else if (out && strncmp(vr, "IS", 2) == 0) {
            CHECK(length < sizeof(tmp_buff) - 1);
            fread(tmp_buff, length, 1, in);
            tmp_buff[length] = '\0';
            sscanf(tmp_buff, "%d", &out->value.is);
        }  else if (out && strncmp(vr, "DS", 2) == 0) {
            CHECK(length < sizeof(tmp_buff) - 1);
            fread(tmp_buff, length, 1, in);
            tmp_buff[length] = '\0';
            sscanf(tmp_buff, "%f", &out->value.ds);
        }  else if (out && strncmp(vr, "UI", 2) == 0) {
            CHECK(length < sizeof(out->value.ui) - 1);
            fread(out->value.ui, length, 1, in);
            out->value.ui[length] = '\0';
        } else if (out && tag.v == TAG_PIXEL_DATA.v && out->buffer) {
            CHECK(out->buffer_size >= length);
            fread(out->buffer, length, 1, in);
        } else {
            // Skip the data.
            fseek(in, length, SEEK_CUR);
        }
    }

    if (tag.group == 0) return false;
    return true;
}
/**
 * mix_videoconfigparamsenc_copy:
 * @target: copy to target
 * @src: copy from src
 * @returns: boolean indicates if copy is successful.
 *
 * Copy instance data from @src to @target.
 */
gboolean mix_videoconfigparamsenc_copy(MixParams * target, const MixParams * src) {

	MixVideoConfigParamsEnc *this_target, *this_src;
	MIX_RESULT mix_result = MIX_RESULT_FAIL;

    LOG_V( "Begin\n");	

	if (MIX_IS_VIDEOCONFIGPARAMSENC(target) && MIX_IS_VIDEOCONFIGPARAMSENC(src)) {

		/* Cast the base object to this child object */
		this_target = MIX_VIDEOCONFIGPARAMSENC(target);
		this_src = MIX_VIDEOCONFIGPARAMSENC(src);

		/* copy properties of primitive type */

		this_target->bitrate   = this_src->bitrate;
		this_target->frame_rate_num = this_src->frame_rate_num;
		this_target->frame_rate_denom = this_src->frame_rate_denom;		
		this_target->initial_qp = this_src->initial_qp;
		this_target->min_qp = this_src->min_qp;
		this_target->intra_period    = this_src->intra_period;
		this_target->picture_width    = this_src->picture_width;		
		this_target->picture_height   = this_src->picture_height;
		this_target->mixbuffer_pool_size = this_src->mixbuffer_pool_size;
		this_target->share_buf_mode = this_src->share_buf_mode;
		this_target->encode_format = this_src->encode_format;		
		this_target->ci_frame_num = this_src->ci_frame_num;		
		this_target->draw= this_src->draw;		
		this_target->need_display = this_src->need_display;
	       this_target->rate_control = this_src->rate_control;
	       this_target->raw_format = this_src->raw_format;
	       this_target->profile = this_src->profile;		
		
		/* copy properties of non-primitive */

		/* copy mime_type */

		if (this_src->mime_type) {
#ifdef MDEBUG
            if (this_src->mime_type->str) {
                
                LOG_I( "this_src->mime_type->str = %s  %x\n", 
                        this_src->mime_type->str, (unsigned int)this_src->mime_type->str);	
            }
#endif

            mix_result = mix_videoconfigparamsenc_set_mime_type(this_target,
                    this_src->mime_type->str);
        } else {
            
            LOG_I( "this_src->mime_type = NULL\n");
            
            mix_result = mix_videoconfigparamsenc_set_mime_type(this_target, NULL);
        }
        
        if (mix_result != MIX_RESULT_SUCCESS) {
            
            LOG_E( "Failed to mix_videoconfigparamsenc_set_mime_type\n");	
            return FALSE;
        }	
        
        mix_result = mix_videoconfigparamsenc_set_ci_frame_info (this_target, this_src->ci_frame_id,
                this_src->ci_frame_num);
        
        /* TODO: copy other properties if there's any */
        
		/* Now chainup base class */
		if (parent_class->copy) {
            return parent_class->copy(MIX_PARAMS_CAST(target), MIX_PARAMS_CAST(
                        src));
        } else {
            return TRUE;
        }
    }
    
    return FALSE;
}
Beispiel #29
0
void
HttpServer::Connection::QueueResponse(InternalResponse* aResponse)
{
  bool chunked = false;

  RefPtr<InternalHeaders> headers = new InternalHeaders(*aResponse->Headers());
  {
    ErrorResult res;
    headers->SetGuard(HeadersGuardEnum::None, res);
  }
  nsCOMPtr<nsIInputStream> body;
  int64_t bodySize;
  aResponse->GetBody(getter_AddRefs(body), &bodySize);

  if (body && bodySize >= 0) {
    nsCString sizeStr;
    sizeStr.AppendInt(bodySize);

    LOG_V("HttpServer::Connection::QueueResponse(%p) - "
          "Setting content-length to %s",
          this, sizeStr.get());

    ErrorResult res;
    headers->Set(NS_LITERAL_CSTRING("content-length"), sizeStr, res);
  } else if (body) {
    // Use chunked transfer encoding
    LOG_V("HttpServer::Connection::QueueResponse(%p) - Chunked transfer-encoding",
          this);

    ErrorResult res;
    headers->Set(NS_LITERAL_CSTRING("transfer-encoding"),
                 NS_LITERAL_CSTRING("chunked"),
                 res);
    headers->Delete(NS_LITERAL_CSTRING("content-length"), res);
    chunked = true;

  } else {
    LOG_V("HttpServer::Connection::QueueResponse(%p) - "
          "No body - setting content-length to 0", this);

    ErrorResult res;
    headers->Set(NS_LITERAL_CSTRING("content-length"),
                 NS_LITERAL_CSTRING("0"), res);
  }

  nsCString head(NS_LITERAL_CSTRING("HTTP/1.1 "));
  head.AppendInt(aResponse->GetStatus());
  // XXX is the statustext security checked?
  head.Append(NS_LITERAL_CSTRING(" ") +
              aResponse->GetStatusText() +
              NS_LITERAL_CSTRING("\r\n"));

  AutoTArray<InternalHeaders::Entry, 16> entries;
  headers->GetEntries(entries);

  for (auto header : entries) {
    head.Append(header.mName +
                NS_LITERAL_CSTRING(": ") +
                header.mValue +
                NS_LITERAL_CSTRING("\r\n"));
  }

  head.Append(NS_LITERAL_CSTRING("\r\n"));

  mOutputBuffers.AppendElement()->mString = head;
  if (body) {
    OutputBuffer* bodyBuffer = mOutputBuffers.AppendElement();
    bodyBuffer->mStream = body;
    bodyBuffer->mChunked = chunked;
  }

  OnOutputStreamReady(mOutput);
}
Beispiel #30
0
nsresult
HttpServer::Connection::ConsumeLine(const char* aBuffer,
                                    size_t aLength)
{
  MOZ_ASSERT(mState == eRequestLine ||
             mState == eHeaders);

  if (MOZ_LOG_TEST(gHttpServerLog, mozilla::LogLevel::Verbose)) {
    nsCString line(aBuffer, aLength);
    LOG_V("HttpServer::Connection::ConsumeLine(%p) - \"%s\"", this, line.get());
  }

  if (mState == eRequestLine) {
    LOG_V("HttpServer::Connection::ConsumeLine(%p) - Parsing request line", this);
    NS_ENSURE_FALSE(mCloseAfterRequest, NS_ERROR_UNEXPECTED);

    if (aLength == 0) {
      // Ignore empty lines before the request line
      return NS_OK;
    }
    MOZ_ASSERT(!mPendingReq);

    // Process request line
    nsCWhitespaceTokenizer tokens(Substring(aBuffer, aLength));

    NS_ENSURE_TRUE(tokens.hasMoreTokens(), NS_ERROR_UNEXPECTED);
    nsDependentCSubstring method = tokens.nextToken();
    NS_ENSURE_TRUE(NS_IsValidHTTPToken(method), NS_ERROR_UNEXPECTED);
    NS_ENSURE_TRUE(tokens.hasMoreTokens(), NS_ERROR_UNEXPECTED);
    nsDependentCSubstring url = tokens.nextToken();
    // Seems like it's also allowed to pass full urls with scheme+host+port.
    // May need to support that.
    NS_ENSURE_TRUE(url.First() == '/', NS_ERROR_UNEXPECTED);
    mPendingReq = new InternalRequest(url, /* aURLFragment */ EmptyCString());
    mPendingReq->SetMethod(method);
    NS_ENSURE_TRUE(tokens.hasMoreTokens(), NS_ERROR_UNEXPECTED);
    nsDependentCSubstring version = tokens.nextToken();
    NS_ENSURE_TRUE(StringBeginsWith(version, NS_LITERAL_CSTRING("HTTP/1.")),
                   NS_ERROR_UNEXPECTED);
    nsresult rv;
    // This integer parsing is likely not strict enough.
    nsCString reqVersion;
    reqVersion = Substring(version, MOZ_ARRAY_LENGTH("HTTP/1.") - 1);
    mPendingReqVersion = reqVersion.ToInteger(&rv);
    NS_ENSURE_SUCCESS(rv, NS_ERROR_UNEXPECTED);

    NS_ENSURE_FALSE(tokens.hasMoreTokens(), NS_ERROR_UNEXPECTED);

    LOG_V("HttpServer::Connection::ConsumeLine(%p) - Parsed request line", this);

    mState = eHeaders;

    return NS_OK;
  }

  if (aLength == 0) {
    LOG_V("HttpServer::Connection::ConsumeLine(%p) - Found end of headers", this);

    MaybeAddPendingHeader();

    ErrorResult res;
    mPendingReq->Headers()->SetGuard(HeadersGuardEnum::Immutable, res);

    // Check for WebSocket
    if (IsWebSocketRequest(mPendingReq, mPendingReqVersion)) {
      LOG_V("HttpServer::Connection::ConsumeLine(%p) - Fire OnWebSocket", this);

      mState = ePause;
      mPendingWebSocketRequest = mPendingReq.forget();
      mPendingReqVersion = 0;

      RefPtr<HttpServerListener> listener = mServer->mListener;
      RefPtr<InternalRequest> request = mPendingWebSocketRequest;
      nsCOMPtr<nsIRunnable> event = NS_NewRunnableFunction(
        "dom::HttpServer::Connection::ConsumeLine",
        [listener, request]() { listener->OnWebSocket(request); });
      NS_DispatchToCurrentThread(event);

      return NS_OK;
    }

    nsAutoCString header;
    mPendingReq->Headers()->GetFirst(NS_LITERAL_CSTRING("connection"),
                                     header,
                                     res);
    MOZ_ASSERT(!res.Failed());
    // 1.0 defaults to closing connections.
    // 1.1 and higher defaults to keep-alive.
    if (ContainsToken(header, NS_LITERAL_CSTRING("close")) ||
        (mPendingReqVersion == 0 &&
         !ContainsToken(header, NS_LITERAL_CSTRING("keep-alive")))) {
      mCloseAfterRequest = true;
    }

    mPendingReq->Headers()->GetFirst(NS_LITERAL_CSTRING("content-length"),
                                     header,
                                     res);
    MOZ_ASSERT(!res.Failed());

    LOG_V("HttpServer::Connection::ConsumeLine(%p) - content-length is \"%s\"",
          this, header.get());

    if (!header.IsEmpty()) {
      nsresult rv;
      mRemainingBodySize = header.ToInteger(&rv);
      NS_ENSURE_SUCCESS(rv, rv);
    } else {
      mRemainingBodySize = 0;
    }

    if (mRemainingBodySize) {
      LOG_V("HttpServer::Connection::ConsumeLine(%p) - Starting consume body", this);
      mState = eBody;

      // We use an unlimited buffer size here to ensure
      // that we get to the next request even if the webpage hangs on
      // to the request indefinitely without consuming the body.
      nsCOMPtr<nsIInputStream> input;
      nsCOMPtr<nsIOutputStream> output;
      nsresult rv = NS_NewPipe(getter_AddRefs(input),
                               getter_AddRefs(output),
                               0,          // Segment size
                               UINT32_MAX, // Unlimited buffer size
                               false,      // not nonBlockingInput
                               true);      // nonBlockingOutput
      NS_ENSURE_SUCCESS(rv, rv);

      mCurrentRequestBody = do_QueryInterface(output);
      mPendingReq->SetBody(input);
    } else {
      LOG_V("HttpServer::Connection::ConsumeLine(%p) - No body", this);
      mState = eRequestLine;
    }

    mPendingRequests.AppendElement(PendingRequest(mPendingReq, nullptr));

    LOG_V("HttpServer::Connection::ConsumeLine(%p) - Fire OnRequest", this);

    RefPtr<HttpServerListener> listener = mServer->mListener;
    RefPtr<InternalRequest> request = mPendingReq.forget();
    nsCOMPtr<nsIRunnable> event = NS_NewRunnableFunction(
      "dom::HttpServer::Connection::ConsumeLine",
      [listener, request]() { listener->OnRequest(request); });
    NS_DispatchToCurrentThread(event);

    mPendingReqVersion = 0;

    return NS_OK;
  }

  // Parse header line
  if (aBuffer[0] == ' ' || aBuffer[0] == '\t') {
    LOG_V("HttpServer::Connection::ConsumeLine(%p) - Add to header %s",
          this,
          mPendingHeaderName.get());

    NS_ENSURE_FALSE(mPendingHeaderName.IsEmpty(),
                    NS_ERROR_UNEXPECTED);

    // We might need to do whitespace trimming/compression here.
    mPendingHeaderValue.Append(aBuffer, aLength);
    return NS_OK;
  }

  MaybeAddPendingHeader();

  const char* colon = static_cast<const char*>(memchr(aBuffer, ':', aLength));
  NS_ENSURE_TRUE(colon, NS_ERROR_UNEXPECTED);

  ToLowerCase(Substring(aBuffer, colon - aBuffer), mPendingHeaderName);
  mPendingHeaderValue.Assign(colon + 1, aLength - (colon - aBuffer) - 1);

  NS_ENSURE_TRUE(NS_IsValidHTTPToken(mPendingHeaderName),
                 NS_ERROR_UNEXPECTED);

  LOG_V("HttpServer::Connection::ConsumeLine(%p) - Parsed header %s",
        this,
        mPendingHeaderName.get());

  return NS_OK;
}