void SoftMP3::onQueueFilled(OMX_U32 portIndex) {
    if (mSignalledError || mOutputPortSettingsChange != NONE) {
        return;
    }

    List<BufferInfo *> &inQueue = getPortQueue(0);
    List<BufferInfo *> &outQueue = getPortQueue(1);

    while (!inQueue.empty() && !outQueue.empty()) {
        BufferInfo *inInfo = *inQueue.begin();
        OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;

        BufferInfo *outInfo = *outQueue.begin();
        OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;

        if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
            inQueue.erase(inQueue.begin());
            inInfo->mOwnedByUs = false;
            notifyEmptyBufferDone(inHeader);

            outHeader->nFilledLen = 0;
            outHeader->nFlags = OMX_BUFFERFLAG_EOS;

            outQueue.erase(outQueue.begin());
            outInfo->mOwnedByUs = false;
            notifyFillBufferDone(outHeader);
            return;
        }

        if (inHeader->nOffset == 0) {
            mAnchorTimeUs = inHeader->nTimeStamp;
            mNumFramesOutput = 0;
        }

        mConfig->pInputBuffer =
            inHeader->pBuffer + inHeader->nOffset;

        mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
        mConfig->inputBufferMaxLength = 0;
        mConfig->inputBufferUsedLength = 0;

        mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);

        mConfig->pOutputBuffer =
            reinterpret_cast<int16_t *>(outHeader->pBuffer);

        ERROR_CODE decoderErr;
        if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
                != NO_DECODING_ERROR) {
            ALOGV("mp3 decoder returned error %d", decoderErr);

            if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR ||
                    mConfig->outputFrameSize == 0) {
                LOGE("mp3 decoder returned error %d", decoderErr);

                if (mConfig->outputFrameSize == 0) {
                    LOGE("Output frame size is 0");
                }

                notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
                mSignalledError = true;
                return;
            }

            // This is recoverable, just ignore the current frame and
            // play silence instead.
            memset(outHeader->pBuffer,
                   0,
                   mConfig->outputFrameSize * sizeof(int16_t));

            mConfig->inputBufferUsedLength = inHeader->nFilledLen;
        } else if (mConfig->samplingRate != mSamplingRate
                || mConfig->num_channels != mNumChannels) {
            mSamplingRate = mConfig->samplingRate;
            mNumChannels = mConfig->num_channels;

            notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
            mOutputPortSettingsChange = AWAITING_DISABLED;
            return;
        }

        outHeader->nOffset = 0;
        outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);

        outHeader->nTimeStamp =
            mAnchorTimeUs
                + (mNumFramesOutput * 1000000ll) / mConfig->samplingRate;

        outHeader->nFlags = 0;

        CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);

        inHeader->nOffset += mConfig->inputBufferUsedLength;
        inHeader->nFilledLen -= mConfig->inputBufferUsedLength;

        mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;

        if (inHeader->nFilledLen == 0) {
            inInfo->mOwnedByUs = false;
            inQueue.erase(inQueue.begin());
            inInfo = NULL;
            notifyEmptyBufferDone(inHeader);
            inHeader = NULL;
        }

        outInfo->mOwnedByUs = false;
        outQueue.erase(outQueue.begin());
        outInfo = NULL;
        notifyFillBufferDone(outHeader);
        outHeader = NULL;
    }
}
nsresult
AppleMP3Reader::ReadMetadata(MediaInfo* aInfo,
                             MetadataTags** aTags)
{
  MOZ_ASSERT(OnTaskQueue());

  *aTags = nullptr;

  /*
   * Feed bytes into the parser until we have all the metadata we need to
   * set up the decoder. When the parser has enough data, it will
   * synchronously call back to |AudioMetadataCallback| below.
   */
  OSStatus rv;
  nsresult readrv;
  uint32_t offset = 0;
  do {
    char bytes[AUDIO_READ_BYTES];
    uint32_t numBytes = AUDIO_READ_BYTES;
    readrv = Read(&numBytes, bytes);

    rv = AudioFileStreamParseBytes(mAudioFileStream,
                                   numBytes,
                                   bytes,
                                   0 /* flags */);

    mMP3FrameParser.Parse(reinterpret_cast<uint8_t*>(bytes), numBytes, offset);

    offset += numBytes;

    // We have to do our decoder setup from the callback. When it's done it will
    // set mStreamReady.
  } while (!mStreamReady && !rv && NS_SUCCEEDED(readrv));

  if (rv) {
    LOGE("Error decoding audio stream metadata\n");
    return NS_ERROR_FAILURE;
  }

  if (!mAudioConverter) {
    LOGE("Failed to setup the AudioToolbox audio decoder\n");
    return NS_ERROR_FAILURE;
  }

  if (!mMP3FrameParser.IsMP3()) {
    LOGE("Frame parser failed to parse MP3 stream\n");
    return NS_ERROR_FAILURE;
  }

  if (mStreamReady) {
    aInfo->mAudio.mRate = mAudioSampleRate;
    aInfo->mAudio.mChannels = mAudioChannels;
  }

  // This special snowflake reader doesn't seem to set *aInfo = mInfo like all
  // the others. Yuck.
  mDuration = mMP3FrameParser.GetDuration();
  mInfo.mMetadataDuration.emplace(TimeUnit::FromMicroseconds(mDuration));
  aInfo->mMetadataDuration.emplace(TimeUnit::FromMicroseconds(mDuration));

  return NS_OK;
}
bool TangoData::SetConfig(bool is_auto_recovery) {
  // Get the default TangoConfig.
  // We get the default config first and change the config
  // flag as needed.
  config_ = TangoService_getConfig(TANGO_CONFIG_DEFAULT);
  if (config_ == NULL) {
    LOGE("TangoService_getConfig(): Failed");
    return false;
  }

  // Turn on auto recovery for motion tracking.
  // Note that the auto-recovery is on by default.
  if (TangoConfig_setBool(config_, "config_enable_auto_recovery",
                          is_auto_recovery) != TANGO_SUCCESS) {
    LOGE("config_enable_auto_recovery(): Failed");
    return false;
  }

  // Get library version string from service.
  TangoConfig_getString(config_, "tango_service_library_version",
                        const_cast<char*>(lib_version_string.c_str()),
                        kVersionStringLength);

  // Setting up the start of service to ADF frame for the onPoseAvailable
  // callback,
  // it will check the localization status.
  TangoCoordinateFramePair pair;
  pair.base = TANGO_COORDINATE_FRAME_AREA_DESCRIPTION;
  pair.target = TANGO_COORDINATE_FRAME_START_OF_SERVICE;

  // Attach onPoseAvailable callback.
  // The callback will be called after the service is connected.
  if (TangoService_connectOnPoseAvailable(1, &pair, onPoseAvailable) !=
      TANGO_SUCCESS) {
    LOGE("TangoService_connectOnPoseAvailable(): Failed");
    return false;
  }

  // Attach onEventAvailable callback.
  // The callback will be called after the service is connected.
  if (TangoService_connectOnTangoEvent(onTangoEvent) != TANGO_SUCCESS) {
    LOGE("TangoService_connectOnTangoEvent(): Failed");
    return false;
  }

  // Load the most recent ADF.
  char* uuid_list;

  // uuid_list will contain a comma separated list of UUIDs.
  if (TangoService_getAreaDescriptionUUIDList(&uuid_list) != TANGO_SUCCESS) {
    LOGI("TangoService_getAreaDescriptionUUIDList");
  }

  // Parse the uuid_list to get the individual uuids.
  if (uuid_list != NULL && uuid_list[0] != '\0') {
    vector<string> adf_list;

    char* parsing_char;
    parsing_char = strtok(uuid_list, ",");
    while (parsing_char != NULL) {
      string s = string(parsing_char);
      adf_list.push_back(s);
      parsing_char = strtok(NULL, ",");
    }

    int list_size = adf_list.size();
    if (list_size == 0) {
      LOGE("List size is 0");
      return false;
    }
    cur_uuid = adf_list[list_size - 1];
    if (TangoConfig_setString(config_, "config_load_area_description_UUID",
                              adf_list[list_size - 1].c_str()) !=
        TANGO_SUCCESS) {
      LOGE("config_load_area_description_uuid Failed");
      return false;
    } else {
      LOGI("Load ADF: %s", adf_list[list_size - 1].c_str());
    }
  } else {
    LOGE("No area description file available, no file loaded.");
  }
  is_localized = false;
  return true;
}
Exemple #4
0
int gpu_context_t::alloc_impl(int w, int h, int format, int usage,
        buffer_handle_t* pHandle, int* pStride, int bufferSize) {
    if (!pHandle || !pStride)
        return -EINVAL;

    size_t size, alignedw, alignedh;

    alignedw = ALIGN(w, 32);
    alignedh = ALIGN(h, 32);
    int colorFormat, bufferType;
    getGrallocInformationFromFormat(format, &colorFormat, &bufferType);

    switch (colorFormat) {
        case HAL_PIXEL_FORMAT_RGBA_8888:
        case HAL_PIXEL_FORMAT_RGBX_8888:
        case HAL_PIXEL_FORMAT_BGRA_8888:
            size = alignedw * alignedh * 4;
            break;
        case HAL_PIXEL_FORMAT_RGB_888:
            size = alignedw * alignedh * 3;
            break;
        case HAL_PIXEL_FORMAT_RGB_565:
        case HAL_PIXEL_FORMAT_RGBA_5551:
        case HAL_PIXEL_FORMAT_RGBA_4444:
            size = alignedw * alignedh * 2;
            break;

        // adreno formats
        case HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO:  // NV21
            size  = ALIGN(alignedw*alignedh, 4096);
            size += ALIGN(2 * ALIGN(w/2, 32) * ALIGN(h/2, 32), 4096);
            break;
        case HAL_PIXEL_FORMAT_YCbCr_420_SP_TILED:   // NV12
            // The chroma plane is subsampled,
            // but the pitch in bytes is unchanged
            // The GPU needs 4K alignment, but the video decoder needs 8K
            alignedw = ALIGN(w, 128);
            size  = ALIGN( alignedw * alignedh, 8192);
            size += ALIGN( alignedw * ALIGN(h/2, 32), 8192);
            break;
        case HAL_PIXEL_FORMAT_YCbCr_420_SP:
        case HAL_PIXEL_FORMAT_YCrCb_420_SP:
        case HAL_PIXEL_FORMAT_YV12:
            if ((w&1) || (h&1)) {
                LOGE("w or h is odd for the YUV format");
                return -EINVAL;
            }
            alignedw = ALIGN(w, 16);
            alignedh = h;
            size = alignedw*alignedh +
                    (ALIGN(alignedw/2, 16) * (alignedh/2))*2;
            size = ALIGN(size, 4096);
            break;

        default:
            LOGE("unrecognized pixel format: %d", format);
            return -EINVAL;
    }

    if ((ssize_t)size <= 0)
        return -EINVAL;

    size = (bufferSize >= size)? bufferSize : size;

    // All buffers marked as protected or for external
    // display need to go to overlay
    if ((usage & GRALLOC_USAGE_EXTERNAL_DISP) ||
        (usage & GRALLOC_USAGE_PROTECTED)) {
            bufferType = BUFFER_TYPE_VIDEO;
    }
    int err;
    if (usage & GRALLOC_USAGE_HW_FB) {
        err = gralloc_alloc_framebuffer(size, usage, pHandle);
    } else {
        err = gralloc_alloc_buffer(size, usage, pHandle, bufferType, format, alignedw, alignedh);
    }

    if (err < 0) {
        return err;
    }

    *pStride = alignedw;
    return 0;
}
/**
 * @brief  : Configation UART           
 * @author : wchao
 * @date   :
 * @param  : fd,  nBits----, nParity----, nStop----
 * @return : int
 * @retval : 0----success; -1----fault
 * @Note   : 
 **/
int set_Parity(int fd,int nBits,int nParity,int nStop)
{
	struct termios newtio,oldtio;

	tcflush(fd, TCIOFLUSH);
	if  ( tcgetattr( fd,&oldtio)  !=  0)
	{
		LOGE("SetupSerial 1\n");
		return(FALSE);
	}

	bzero( &newtio, sizeof( newtio ) );
    newtio.c_cflag  |=  CLOCAL | CREAD;
    newtio.c_cflag &= ~CSIZE;
	
	switch (nBits) /*set databit*/
	{
	case 5:
        newtio.c_cflag |= CS5;
        break;
    case 6:
        newtio.c_cflag |= CS6;
        break;
    case 7:
        newtio.c_cflag |= CS7;
        break;
    case 8:
        newtio.c_cflag |= CS8;
        break;
    default:
        newtio.c_cflag |= CS8; //Unsupported data define CS8
        break;
	}
	
	switch (nParity)
	{
	case 'n':
	case 'N':
		newtio.c_cflag &= ~PARENB;			/* Clear parity enable */
		newtio.c_iflag &= ~INPCK;			/* Enable parity checking */
		break;
	case 'o':
	case 'O':
		newtio.c_cflag |= PARENB;
        newtio.c_cflag |= PARODD;			/* set party*/
        newtio.c_iflag |= (INPCK | ISTRIP);	/* Disnable parity checking */            
		break;
	case 'e':
	case 'E':
		newtio.c_iflag |= (INPCK | ISTRIP);	/* Disnable parity checking */
        newtio.c_cflag |= PARENB;			/* Enable parity */
        newtio.c_cflag &= ~PARODD;			/* Set party*/       
		break;
	case 'S':
	case 's':  /*as no parity*/
		newtio.c_cflag &= ~PARENB;
		newtio.c_cflag &= ~CSTOPB;
		break;
	default:
		newtio.c_cflag &= ~PARENB;
		newtio.c_iflag &= ~INPCK;
		break;
	}
	
	/* set stop*/   
	switch (nStop)
	{
	case 1:
		newtio.c_cflag &=  ~CSTOPB;
		break;
	case 2:
		newtio.c_cflag |=  CSTOPB;
		break;
	default:
		LOGE(stderr,"Unsupported stop bits\n");
		return (FALSE);
	}
	
	newtio.c_cc[VTIME] = 0; 
	newtio.c_cc[VMIN] = 0;

	tcflush(fd,TCIFLUSH); /* Update the options and do it NOW */
	if (tcsetattr(fd,TCSANOW,&newtio) != 0)
	{
		LOGE("SetupSerial 3\n");
		return (FALSE);
	}
	
#ifdef TEST_BUG
	LOGE("set done!\n");
#endif
	return (TRUE);
 }
/*
 * Invoke a method, using the specified arguments and return type, through
 * one of the reflection interfaces.  Could be a virtual or direct method
 * (including constructors).  Used for reflection.
 *
 * Deals with boxing/unboxing primitives and performs widening conversions.
 *
 * "invokeObj" will be null for a static method.
 *
 * If the invocation returns with an exception raised, we have to wrap it.
 */
Object* dvmInvokeMethod(Object* obj, const Method* method,
    ArrayObject* argList, ArrayObject* params, ClassObject* returnType,
    bool noAccessCheck)
{
    ClassObject* clazz;
    Object* retObj = NULL;
    Thread* self = dvmThreadSelf();
    s4* ins;
    int verifyCount, argListLength;
    JValue retval;

    /* verify arg count */
    if (argList != NULL)
        argListLength = argList->length;
    else
        argListLength = 0;
    if (argListLength != (int) params->length) {
        LOGI("invoke: expected %d args, received %d args\n",
            params->length, argListLength);
        dvmThrowException("Ljava/lang/IllegalArgumentException;",
            "wrong number of arguments");
        return NULL;
    }

    clazz = callPrep(self, method, obj, !noAccessCheck);
    if (clazz == NULL)
        return NULL;

    /* "ins" for new frame start at frame pointer plus locals */
    ins = ((s4*)self->curFrame) + (method->registersSize - method->insSize);
    verifyCount = 0;

    //LOGD("  FP is %p, INs live at >= %p\n", self->curFrame, ins);

    /* put "this" pointer into in0 if appropriate */
    if (!dvmIsStaticMethod(method)) {
        assert(obj != NULL);
        *ins++ = (s4) obj;
        verifyCount++;
    }

    /*
     * Copy the args onto the stack.  Primitive types are converted when
     * necessary, and object types are verified.
     */
    DataObject** args;
    ClassObject** types;
    int i;

    args = (DataObject**) argList->contents;
    types = (ClassObject**) params->contents;
    for (i = 0; i < argListLength; i++) {
        int width;

        width = dvmConvertArgument(*args++, *types++, ins);
        if (width < 0) {
            if (*(args-1) != NULL) {
                LOGV("invoke: type mismatch on arg %d ('%s' '%s')\n",
                    i, (*(args-1))->obj.clazz->descriptor,
                    (*(types-1))->descriptor);
            }
            dvmPopFrame(self);      // throw wants to pull PC out of stack
            dvmThrowException("Ljava/lang/IllegalArgumentException;",
                "argument type mismatch");
            goto bail_popped;
        }

        ins += width;
        verifyCount += width;
    }

    if (verifyCount != method->insSize) {
        LOGE("Got vfycount=%d insSize=%d for %s.%s\n", verifyCount,
            method->insSize, clazz->descriptor, method->name);
        assert(false);
        goto bail;
    }
    //dvmDumpThreadStack(dvmThreadSelf());

    if (dvmIsNativeMethod(method)) {
        /*
         * Because we leave no space for local variables, "curFrame" points
         * directly at the method arguments.
         */
        (*method->nativeFunc)(self->curFrame, &retval, method, self);
    } else {
        dvmInterpret(self, method, &retval);
    }

    /*
     * If an exception is raised, wrap and replace.  This is necessary
     * because the invoked method could have thrown a checked exception
     * that the caller wasn't prepared for.
     *
     * We might be able to do this up in the interpreted code, but that will
     * leave us with a shortened stack trace in the top-level exception.
     */
    if (dvmCheckException(self)) {
        dvmWrapException("Ljava/lang/reflect/InvocationTargetException;");
    } else {
        /*
         * If this isn't a void method or constructor, convert the return type
         * to an appropriate object.
         *
         * We don't do this when an exception is raised because the value
         * in "retval" is undefined.
         */
        if (returnType != NULL) {
            retObj = (Object*)dvmWrapPrimitive(retval, returnType);
            dvmReleaseTrackedAlloc(retObj, NULL);
        }
    }

bail:
    dvmPopFrame(self);
bail_popped:
    return retObj;
}
Exemple #7
0
char* Namespace::bson_to_json(char* val, const char *data, int depth,
		bool isObject, int bsonSize, int &jsonSize, int &cursor)
{

	char *object;

	int bufSize;

	char keybuf[512];
	char buf[512];
	int c = 0;

	bson_iterator i;
	const char *key;
	int temp;
	bson_timestamp_t ts;
	char oidhex[25];
	bson scope;
	bson_iterator_from_buffer(&i, data);
	//bson_iterator_init(&i, data);

	if (isObject)
	{
		memcpy(&val[cursor], "{", 1);
		cursor += 1;
	}
	else
	{
		memcpy(&val[cursor], "[", 1);
		cursor += 1;
	}

	while (bson_iterator_next(&i) && i.progress < bsonSize)
	{
		if (c > 0)
		{
			memcpy(&val[cursor], ",", 1);
			cursor += 1;
		}
		c++;

		bson_type t = bson_iterator_type(&i);
		if (t == 0)
		{
			break;
		}
		key = bson_iterator_key(&i);

		if (key[0] != '\0')
		{
			sprintf(keybuf, "\"%s\":", key);
			key = &keybuf[0];
		}

		switch (t)
		{
		case BSON_DOUBLE:
			sprintf(buf, "%s%f", key, bson_iterator_double(&i));
			bufSize = strlen(buf);
			memcpy(&val[cursor], buf, bufSize);
			cursor += bufSize;
			break;
		case BSON_STRING:
			sprintf(buf, "%s\"%s\"", key, bson_iterator_string(&i));
			bufSize = strlen(buf);
			memcpy(&val[cursor], buf, bufSize);
			cursor += bufSize;
			break;
		case BSON_OID:
			bson_oid_to_string(bson_iterator_oid(&i), oidhex);
			sprintf(buf, "%s\"%s\"", key, oidhex);
			bufSize = strlen(buf);
			memcpy(&val[cursor], buf, bufSize);
			cursor += bufSize;
			break;
		case BSON_BOOL:
			sprintf(buf, "%s%s", key,
					bson_iterator_bool(&i) ? "true" : "false");
			bufSize = strlen(buf);
			memcpy(&val[cursor], buf, bufSize);
			cursor += bufSize;
			break;
		case BSON_NULL:
			sprintf(buf, "%snull", key);
			bufSize = strlen(buf);
			memcpy(&val[cursor], buf, bufSize);
			cursor += bufSize;
			break;
		case BSON_INT:
			sprintf(buf, "%s%d", key, bson_iterator_int(&i));
			bufSize = strlen(buf);
			memcpy(&val[cursor], buf, bufSize);
			cursor += bufSize;
			break;
		case BSON_OBJECT:
			sprintf(buf, "%s\0", key);
			memcpy(&val[cursor], buf, strlen(buf));
			cursor += strlen(buf);

			object = bson_to_json(val, bson_iterator_value(&i), depth + 1, true,
					bsonSize - cursor, jsonSize, cursor);

			break;
		case BSON_ARRAY:
			sprintf(buf, "%s", key);
			bufSize = strlen(buf);
			memcpy(&val[cursor], buf, bufSize);
			cursor += bufSize;

			object = bson_to_json(val, bson_iterator_value(&i), depth + 1,
					false, bsonSize - cursor, jsonSize, cursor);

			break;
		default:
			LOGE("can't print type");
			FORCE_LOG_INT("type: ", t);

			memcpy(&val[cursor], "}", 1);
			cursor += 1;
			jsonSize = cursor;
			return val;
		}
	}

	if (isObject)
	{
		memcpy(&val[cursor], "}", 1);
		cursor += 1;
		memcpy(&val[cursor], "\0", 1);

	}
	else
	{
		memcpy(&val[cursor], "]", 1);
		cursor += 1;
	}

	jsonSize = cursor;
	return val;
}
/**
 * @brief Handle inotify events
 *
 * Calls the callcbacks
 *
 * @param files nb max of logs destination directories (crashlog,
 * aplogs, bz... )
 *
 * @return 0 on success, -1 on error.
 */
int receive_inotify_events(int inotify_fd) {
    int len = 0, orig_len, idx, wd, missing_bytes;
    char orig_buffer[sizeof(struct inotify_event)+PATHMAX], *buffer, lastevent[sizeof(struct inotify_event)+PATHMAX];
    struct inotify_event *event;
    struct watch_entry *entry = NULL;

    len = read(inotify_fd, orig_buffer, sizeof(orig_buffer));
    if (len < 0) {
        LOGE("%s: Cannot read file_monitor_fd, error is %s\n", __FUNCTION__, strerror(errno));
        return -errno;
    }

    buffer = &orig_buffer[0];
    orig_len = len;
    event = (struct inotify_event *)buffer;

    /* Preinitialize lastevent (in case it was not used so it is not dumped) */
    ((struct inotify_event *)lastevent)->wd = 0;
    ((struct inotify_event *)lastevent)->mask = 0;
    ((struct inotify_event *)lastevent)->cookie = 0;
    ((struct inotify_event *)lastevent)->len = 0;

    while (1) {
        if (len == 0) {
            /* End of the events to read */
            return 0;
        }
        if ((unsigned int)len < sizeof(struct inotify_event)) {
            /* Not enough room for an empty event */
            LOGI("%s: incomplete inotify_event received (%d bytes), complete it\n", __FUNCTION__, len);
            /* copy the last bytes received */
            if( (unsigned int)len <= sizeof(lastevent) )
                memcpy(lastevent, buffer, len);
            else {
                LOGE("%s: Cannot copy buffer\n", __FUNCTION__);
                return -1;
            }
            /* read the missing bytes to get the full length */
            missing_bytes = (int)sizeof(struct inotify_event)-len;
            if(((int) len + missing_bytes) < ((int)sizeof(lastevent))) {
                if (read(inotify_fd, &lastevent[len], missing_bytes) != missing_bytes ){
                    LOGE("%s: Cannot complete the last inotify_event received (structure part) - %s\n", __FUNCTION__, strerror(errno));
                    return -1;
                }
            }
            else {
                LOGE("%s: Cannot read missing bytes, not enought space in lastevent\n", __FUNCTION__);
                return -1;
            }
            event = (struct inotify_event*)lastevent;
            /* now, reads the full last event, including its name field */
            if ( read(inotify_fd, &lastevent[sizeof(struct inotify_event)],
                event->len) != (int)event->len) {
                LOGE("%s: Cannot complete the last inotify_event received (name part) - %s\n",
                    __FUNCTION__, strerror(errno));
                return -1;
            }
            len = 0;
            /* now, the last event is complete, we can continue the parsing */
        } else if ( (unsigned int)len < sizeof(struct inotify_event) + event->len ) {
            int res, missing_bytes = (int)sizeof(struct inotify_event) + event->len - len;
            event = (struct inotify_event*)lastevent;
            /* The event was truncated */
            LOGI("%s: truncated inotify_event received (%d bytes missing), complete it\n", __FUNCTION__, missing_bytes);

            /* Robustness : check 'lastevent' array size before reading inotify fd*/
            if( (unsigned int)len > sizeof(lastevent) ) {
                LOGE("%s: not enough space on array lastevent.\n", __FUNCTION__);
                return -1;
            }
            /* copy the last bytes received */
            memcpy(lastevent, buffer, len);
            /* now, reads the full last event, including its name field */
            res = read(inotify_fd, &lastevent[len], missing_bytes);
            if ( res != missing_bytes ) {
                LOGE("%s: Cannot complete the last inotify_event received (name part2); received %d bytes, expected %d bytes - %s\n",
                    __FUNCTION__, res, missing_bytes, strerror(errno));
                return -1;
            }
            len = 0;
            /* now, the last event is complete, we can continue the parsing */
        } else {
            event = (struct inotify_event *)buffer;
            buffer += sizeof(struct inotify_event) + event->len;
            len -= sizeof(struct inotify_event) + event->len;
        }
        /* Handle the event read from the buffer*/
        /* First check the kind of the subject of this event (file or directory?) */
        if (!(event->mask & IN_ISDIR)) {
            /* event concerns a file into a watched directory */
            entry = get_event_entry(event->wd, (event->len ? event->name : NULL));
            if ( !entry ) {
                /* Didn't find any entry for this event, check for
                 * a dropbox final event... */
                if (event->len > 8 && !strncmp(event->name, "dropbox-", 8)) {
                    /* dumpstate is done so remove the watcher */
                    LOGD("%s: Received a dropbox event(%s)...",
                        __FUNCTION__, event->name);
                    inotify_rm_watch(inotify_fd, event->wd);
                    finalize_dropbox_pending_event(event);
                    continue;
                }
                /* Stray event... */
                LOGD("%s: Can't handle the event \"%s\", no valid entry found, drop it...\n",
                    __FUNCTION__, (event->len ? event->name : "empty event"));
                continue;
            }
        }
        /*event concerns a watched directory itself */
        else {
            entry = NULL;
            /* Manage case where a watched directory is deleted*/
            if ( event->mask & (IN_DELETE_SELF | IN_MOVE_SELF) ) {
                /* Recreate the dir and reinstall the watch */
                for (idx = 0 ; idx < (int)DIM(wd_array) ; idx++) {
                    if ( wd_array[idx].wd == event->wd )
                        entry = &wd_array[idx];
                }
                if ( entry && entry->eventpath ) {
                    mkdir(entry->eventpath, 0777); /* TO DO : restoring previous rights/owner/group ?*/
                    inotify_rm_watch(inotify_fd, event->wd);
                    wd = inotify_add_watch(inotify_fd, entry->eventpath, entry->eventmask);
                    if ( wd < 0 ) {
                        LOGE("Can't add watch for %s.\n", entry->eventpath);
                        return -1;
                    }
                    LOGW("%s: watched directory %s : \'%s\' has been created and snooped",__FUNCTION__,
                            (event->mask & (IN_DELETE_SELF) ? "deleted" : "moved"), entry->eventpath);
                    /* if the watch was duplicated, set it for all the entries */
                    for (idx = 0 ; idx < (int)DIM(wd_array) ; idx++) {
                        if (wd_array[idx].wd == event->wd)
                            wd_array[idx].wd = wd;
                    }
                    /* Do nothing more on directory events */
                    continue;
                }
            }
            else {
                for (idx = 0 ; idx < (int)DIM(wd_array) ; idx++) {
                    if ( wd_array[idx].wd != event->wd )
                        continue;
                    entry = &wd_array[idx];
                    /* for modem generic */
                    /* TO IMPROVE : change flag management and put this in main loop */
                    if(strstr(LOGS_MODEM_DIR, entry->eventpath) && (generic_match(event->name, g_first_modem_config))){
                        process_modem_generic(entry, event, inotify_fd);
                        break;
                    }
                }
                pconfig check_config = generic_match_by_wd(event->name, g_first_modem_config, event->wd);
                if(check_config){
                        process_modem_generic( &check_config->wd_config, event, inotify_fd);
                }else{
                    LOGE("%s: Directory not catched %s.\n", __FUNCTION__, event->name);
                }
                /* Do nothing more on directory events */
                continue;
            }
        }
        if ( entry && entry->pcallback && entry->pcallback(entry, event) < 0 ) {
            LOGE("%s: Can't handle the event %s...\n", __FUNCTION__,
                event->name);
            dump_inotify_events(orig_buffer, orig_len, lastevent);
            return -1;
        }
    }

    return 0;
}
Exemple #9
0
extern "C" void orxAndroid_PumpEvents()
{
  int ident;
  int events;

  while ((ident=ALooper_pollAll(isInteractible() || sstAndroid.bDestroyRequested == orxTRUE ? 0 : -1, NULL, &events, NULL)) >= 0)
  {
    if(ident == LOOPER_ID_MAIN)
    {
      int8_t cmd = app_read_cmd();

      if(cmd == APP_CMD_PAUSE) {
        LOGI("APP_CMD_PAUSE");
        sstAndroid.bPaused = orxTRUE;
        orxEvent_SendShort(orxEVENT_TYPE_SYSTEM, orxSYSTEM_EVENT_BACKGROUND);
      }
      if(cmd == APP_CMD_RESUME) {
        LOGI("APP_CMD_RESUME");
        sstAndroid.bPaused = orxFALSE;
        orxEvent_SendShort(orxEVENT_TYPE_SYSTEM, orxSYSTEM_EVENT_FOREGROUND);
      }
      if(cmd == APP_CMD_SURFACE_DESTROYED) {
        LOGI("APP_CMD_SURFACE_DESTROYED");
        pthread_cond_broadcast(&sstAndroid.cond);

        sstAndroid.fSurfaceScale = orxFLOAT_0;
        orxEVENT_SEND(orxANDROID_EVENT_TYPE_SURFACE, orxANDROID_EVENT_SURFACE_DESTROYED, orxNULL, orxNULL, orxNULL);

        pthread_mutex_lock(&sstAndroid.mutex);
        if(sstAndroid.window != NULL)
        {
          ANativeWindow_release(sstAndroid.window);
          sstAndroid.window = NULL;
        }
        pthread_cond_broadcast(&sstAndroid.cond);
        pthread_mutex_unlock(&sstAndroid.mutex);
      }
      if(cmd == APP_CMD_SURFACE_CHANGED) {
        LOGI("APP_CMD_SURFACE_CHANGED");
        orxANDROID_SURFACE_CHANGED_EVENT stSurfaceChangedEvent;
        stSurfaceChangedEvent.u32Width = sstAndroid.u32SurfaceWidth;
        stSurfaceChangedEvent.u32Height = sstAndroid.u32SurfaceHeight;
        sstAndroid.fSurfaceScale = orxFLOAT_0;
        orxEVENT_SEND(orxANDROID_EVENT_TYPE_SURFACE, orxANDROID_EVENT_SURFACE_CHANGED, orxNULL, orxNULL, &stSurfaceChangedEvent);
      }
      if(cmd == APP_CMD_SURFACE_CREATED) {
        LOGI("APP_CMD_SURFACE_CREATED");
        pthread_mutex_lock(&sstAndroid.mutex);
        sstAndroid.window = sstAndroid.pendingWindow;
        pthread_cond_broadcast(&sstAndroid.cond);
        pthread_mutex_unlock(&sstAndroid.mutex);

        orxEVENT_SEND(orxANDROID_EVENT_TYPE_SURFACE, orxANDROID_EVENT_SURFACE_CREATED, orxNULL, orxNULL, orxNULL);
      }
      if(cmd == APP_CMD_QUIT) {
        LOGI("APP_CMD_QUIT");
        sstAndroid.bDestroyRequested = orxTRUE;
        orxEvent_SendShort(orxEVENT_TYPE_SYSTEM, orxSYSTEM_EVENT_CLOSE);
      }
      if(cmd == APP_CMD_FOCUS_GAINED) {
        LOGI("APP_CMD_FOCUS_GAINED");
        sstAndroid.bHasFocus = orxTRUE;
        orxEvent_SendShort(orxEVENT_TYPE_SYSTEM, orxSYSTEM_EVENT_FOCUS_GAINED);
      }
      if(cmd == APP_CMD_FOCUS_LOST) {
        LOGI("APP_CMD_FOCUS_LOST");
        sstAndroid.bHasFocus = orxFALSE;
        orxEvent_SendShort(orxEVENT_TYPE_SYSTEM, orxSYSTEM_EVENT_FOCUS_LOST);
      }
    }

    if(ident == LOOPER_ID_SENSOR)
    {
      orxEvent_SendShort(orxANDROID_EVENT_TYPE_ACCELERATE, 0);
    }

    if(ident == LOOPER_ID_KEY_EVENT)
    {
      orxANDROID_KEY_EVENT stKeyEvent;

      if (read(sstAndroid.pipeKeyEvent[0], &stKeyEvent, sizeof(stKeyEvent)) == sizeof(stKeyEvent))
      {
        orxEVENT_SEND(orxANDROID_EVENT_TYPE_KEYBOARD, 0, orxNULL, orxNULL, &stKeyEvent);
      } else {
        LOGE("No data on command pipe!");
      }
    }

    if(ident == LOOPER_ID_TOUCH_EVENT)
    {
      orxANDROID_TOUCH_EVENT stTouchEvent;

      if (read(sstAndroid.pipeTouchEvent[0], &stTouchEvent, sizeof(stTouchEvent)) == sizeof(stTouchEvent))
      {
        orxSYSTEM_EVENT_PAYLOAD stPayload;

        if(sstAndroid.fSurfaceScale == orxFLOAT_0)
        {
          orxConfig_PushSection(KZ_CONFIG_ANDROID);
          sstAndroid.fSurfaceScale = orxConfig_GetFloat(KZ_CONFIG_SURFACE_SCALE);
          orxConfig_PopSection();
        }

        /* Inits event's payload */
        orxMemory_Zero(&stPayload, sizeof(orxSYSTEM_EVENT_PAYLOAD));
        stPayload.stTouch.fPressure = orxFLOAT_0;
        stPayload.stTouch.fX = sstAndroid.fSurfaceScale * stTouchEvent.fX;
        stPayload.stTouch.fY = sstAndroid.fSurfaceScale * stTouchEvent.fY;
        stPayload.stTouch.u32ID = stTouchEvent.u32ID;

        switch(stTouchEvent.u32Action)
        {
        case 0: // MotionEvent.ACTION_DOWN
        case 5: // MotionEvent.ACTION_POINTER_DOWN
          orxEVENT_SEND(orxEVENT_TYPE_SYSTEM, orxSYSTEM_EVENT_TOUCH_BEGIN, orxNULL, orxNULL, &stPayload);
          break;
        case 1: // MotionEvent.ACTION_UP
        case 6: // MotionEvent.ACTION_POINTER_UP
          orxEVENT_SEND(orxEVENT_TYPE_SYSTEM, orxSYSTEM_EVENT_TOUCH_END, orxNULL, orxNULL, &stPayload);
          break;
        case 2: // MotionEvent.ACTION_MOVE
          orxEVENT_SEND(orxEVENT_TYPE_SYSTEM, orxSYSTEM_EVENT_TOUCH_MOVE, orxNULL, orxNULL, &stPayload);
          break;
        }
      } else {
        LOGE("No data on command pipe!");
      }
    }

    if(ident == LOOPER_ID_JOYSTICK_EVENT)
    {
      orxANDROID_JOYSTICK_EVENT stJoystickEvent;

      if (read(sstAndroid.pipeJoystickEvent[0], &stJoystickEvent, sizeof(stJoystickEvent)) == sizeof(stJoystickEvent))
      {
        orxEVENT_SEND(orxANDROID_EVENT_TYPE_JOYSTICK, 0, orxNULL, orxNULL, &stJoystickEvent);
      } else {
        LOGE("No data on command pipe!");
      }
    }
  }
}
Exemple #10
0
static void datacopier_readable(libxl__egc *egc, libxl__ev_fd *ev,
                                int fd, short events, short revents) {
    libxl__datacopier_state *dc = CONTAINER_OF(ev, *dc, toread);
    STATE_AO_GC(dc->ao);

    if (datacopier_pollhup_handled(egc, dc, revents, 0))
        return;

    if (revents & ~POLLIN) {
        LOG(ERROR, "unexpected poll event 0x%x (should be POLLIN)"
            " on %s during copy of %s", revents, dc->readwhat, dc->copywhat);
        datacopier_callback(egc, dc, -1, 0);
        return;
    }
    assert(revents & POLLIN);
    for (;;) {
        while (dc->used >= dc->maxsz) {
            libxl__datacopier_buf *rm = LIBXL_TAILQ_FIRST(&dc->bufs);
            dc->used -= rm->used;
            assert(dc->used >= 0);
            LIBXL_TAILQ_REMOVE(&dc->bufs, rm, entry);
            free(rm);
        }

        libxl__datacopier_buf *buf =
            LIBXL_TAILQ_LAST(&dc->bufs, libxl__datacopier_bufs);
        if (!buf || buf->used >= sizeof(buf->buf)) {
            buf = malloc(sizeof(*buf));
            if (!buf) libxl__alloc_failed(CTX, __func__, 1, sizeof(*buf));
            buf->used = 0;
            LIBXL_TAILQ_INSERT_TAIL(&dc->bufs, buf, entry);
        }
        int r = read(ev->fd,
                     buf->buf + buf->used,
                     sizeof(buf->buf) - buf->used);
        if (r < 0) {
            if (errno == EINTR) continue;
            if (errno == EWOULDBLOCK) break;
            LOGE(ERROR, "error reading %s during copy of %s",
                 dc->readwhat, dc->copywhat);
            datacopier_callback(egc, dc, 0, errno);
            return;
        }
        if (r == 0) {
            libxl__ev_fd_deregister(gc, &dc->toread);
            break;
        }
        if (dc->log) {
            int wrote = fwrite(buf->buf + buf->used, 1, r, dc->log);
            if (wrote != r) {
                assert(ferror(dc->log));
                assert(errno);
                LOGE(ERROR, "error logging %s", dc->copywhat);
                datacopier_callback(egc, dc, 0, errno);
                return;
            }
        }
        buf->used += r;
        dc->used += r;
        assert(buf->used <= sizeof(buf->buf));
    }
    datacopier_check_state(egc, dc);
}
Exemple #11
0
int libxl__openptys(libxl__openpty_state *op,
                    struct termios *termp,
                    struct winsize *winp) {
    /*
     * This is completely crazy.  openpty calls grantpt which the spec
     * says may fork, and may not be called with a SIGCHLD handler.
     * Now our application may have a SIGCHLD handler so that's bad.
     * We could perhaps block it but we'd need to block it on all
     * threads.  This is just Too Hard.
     *
     * So instead, we run openpty in a child process.  That child
     * process then of course has only our own thread and our own
     * signal handlers.  We pass the fds back.
     *
     * Since our only current caller actually wants two ptys, we
     * support calling openpty multiple times for a single fork.
     */
    STATE_AO_GC(op->ao);
    int count = op->count;
    int r, i, rc, sockets[2], ptyfds[count][2];
    libxl__carefd *for_child = 0;
    pid_t pid = -1;

    for (i=0; i<count; i++) {
        ptyfds[i][0] = ptyfds[i][1] = -1;
        libxl__openpty_result *res = &op->results[i];
        assert(!res->master);
        assert(!res->slave);
    }
    sockets[0] = sockets[1] = -1; /* 0 is for us, 1 for our child */

    libxl__carefd_begin();
    r = socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
    if (r) { sockets[0] = sockets[1] = -1; }
    for_child = libxl__carefd_opened(CTX, sockets[1]);
    if (r) { LOGE(ERROR,"socketpair failed"); rc = ERROR_FAIL; goto out; }

    pid = libxl__ev_child_fork(gc, &op->child, openpty_exited);
    if (pid == -1) {
        rc = ERROR_FAIL;
        goto out;
    }

    if (!pid) {
        /* child */
        close(sockets[0]);
        signal(SIGCHLD, SIG_DFL);

        for (i=0; i<count; i++) {
            r = openpty(&ptyfds[i][0], &ptyfds[i][1], NULL, termp, winp);
            if (r) { LOGE(ERROR,"openpty failed"); _exit(-1); }
        }
        rc = libxl__sendmsg_fds(gc, sockets[1], "",1,
                                2*count, &ptyfds[0][0], "ptys");
        if (rc) { LOGE(ERROR,"sendmsg to parent failed"); _exit(-1); }
        _exit(0);
    }

    libxl__carefd_close(for_child);
    for_child = 0;

    /* this should be fast so do it synchronously */

    libxl__carefd_begin();
    char buf[1];
    rc = libxl__recvmsg_fds(gc, sockets[0], buf,1,
                            2*count, &ptyfds[0][0], "ptys");
    if (!rc) {
        for (i=0; i<count; i++) {
            libxl__openpty_result *res = &op->results[i];
            res->master = libxl__carefd_record(CTX, ptyfds[i][0]);
            res->slave =  libxl__carefd_record(CTX, ptyfds[i][1]);
        }
    }
    /* now the pty fds are in the carefds, if they were ever open */
    libxl__carefd_unlock();
    if (rc)
        goto out;

    rc = 0;

 out:
    if (sockets[0] >= 0) close(sockets[0]);
    libxl__carefd_close(for_child);
    if (libxl__ev_child_inuse(&op->child)) {
        op->rc = rc;
        /* we will get a callback when the child dies */
        return 0;
    }

    assert(rc);
    openpty_cleanup(op);
    return rc;
}
bool MtkFormat::createImage(std::vector<unsigned char> *dataOut)
{
    BootImageHeader hdr;
    std::vector<unsigned char> data;

    memset(&hdr, 0, sizeof(BootImageHeader));

    bool hasKernelHdr = !mI10e->mtkKernelHdr.empty();
    bool hasRamdiskHdr = !mI10e->mtkRamdiskHdr.empty();

    // Check header sizes
    if (hasKernelHdr && mI10e->mtkKernelHdr.size() != sizeof(MtkHeader)) {
        LOGE("Expected %" PRIzu " byte kernel MTK header, but have %" PRIzu " bytes",
             sizeof(MtkHeader), mI10e->mtkKernelHdr.size());
        return false;
    }
    if (hasRamdiskHdr && mI10e->mtkRamdiskHdr.size() != sizeof(MtkHeader)) {
        LOGE("Expected %" PRIzu " byte ramdisk MTK header, but have %" PRIzu " bytes",
             sizeof(MtkHeader), mI10e->mtkRamdiskHdr.size());
        return false;
    }

    std::size_t kernelSize =
            mI10e->kernelImage.size() + mI10e->mtkKernelHdr.size();
    std::size_t ramdiskSize =
            mI10e->ramdiskImage.size() + mI10e->mtkRamdiskHdr.size();

    MtkHeader mtkKernelHdr;
    MtkHeader mtkRamdiskHdr;
    if (hasKernelHdr) {
        std::memcpy(&mtkKernelHdr, mI10e->mtkKernelHdr.data(), sizeof(MtkHeader));
        mtkKernelHdr.size = mI10e->kernelImage.size();
    }
    if (hasRamdiskHdr) {
        std::memcpy(&mtkRamdiskHdr, mI10e->mtkRamdiskHdr.data(), sizeof(MtkHeader));
        mtkRamdiskHdr.size = mI10e->ramdiskImage.size();
    }

    // Set header metadata fields
    memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);
    hdr.kernel_size = kernelSize;
    hdr.kernel_addr = mI10e->kernelAddr;
    hdr.ramdisk_size = ramdiskSize;
    hdr.ramdisk_addr = mI10e->ramdiskAddr;
    hdr.second_size = mI10e->hdrSecondSize;
    hdr.second_addr = mI10e->secondAddr;
    hdr.tags_addr = mI10e->tagsAddr;
    hdr.page_size = mI10e->pageSize;
    hdr.dt_size = mI10e->hdrDtSize;
    hdr.unused = mI10e->hdrUnused;
    // -1 for null byte
    std::strcpy(reinterpret_cast<char *>(hdr.name),
                mI10e->boardName.substr(0, BOOT_NAME_SIZE - 1).c_str());
    std::strcpy(reinterpret_cast<char *>(hdr.cmdline),
                mI10e->cmdline.substr(0, BOOT_ARGS_SIZE - 1).c_str());

    // Update SHA1
    updateSha1Hash(&hdr, mI10e,
                   hasKernelHdr ? &mtkKernelHdr : nullptr,
                   hasRamdiskHdr ? &mtkRamdiskHdr : nullptr,
                   kernelSize, ramdiskSize);

    switch (mI10e->pageSize) {
    case 2048:
    case 4096:
    case 8192:
    case 16384:
    case 32768:
    case 65536:
    case 131072:
        break;
    default:
        LOGE("Invalid page size: %u", mI10e->pageSize);
        return false;
    }

    // Header
    unsigned char *hdrBegin = reinterpret_cast<unsigned char *>(&hdr);
    data.insert(data.end(), hdrBegin, hdrBegin + sizeof(BootImageHeader));

    // Padding
    uint32_t paddingSize = skipPadding(sizeof(BootImageHeader), hdr.page_size);
    data.insert(data.end(), paddingSize, 0);

    // Kernel image
    if (hasKernelHdr) {
        data.insert(data.end(),
                    reinterpret_cast<const unsigned char *>(&mtkKernelHdr),
                    reinterpret_cast<const unsigned char *>(&mtkKernelHdr) + sizeof(MtkHeader));
    }
    data.insert(data.end(),
                mI10e->kernelImage.begin(),
                mI10e->kernelImage.end());

    // More padding
    paddingSize = skipPadding(kernelSize, hdr.page_size);
    data.insert(data.end(), paddingSize, 0);

    // Ramdisk image
    if (hasRamdiskHdr) {
        data.insert(data.end(),
                    reinterpret_cast<const unsigned char *>(&mtkRamdiskHdr),
                    reinterpret_cast<const unsigned char *>(&mtkRamdiskHdr) + sizeof(MtkHeader));
    }
    data.insert(data.end(),
                mI10e->ramdiskImage.begin(),
                mI10e->ramdiskImage.end());

    // Even more padding
    paddingSize = skipPadding(ramdiskSize, hdr.page_size);
    data.insert(data.end(), paddingSize, 0);

    // Second bootloader image
    if (!mI10e->secondImage.empty()) {
        data.insert(data.end(),
                    mI10e->secondImage.begin(),
                    mI10e->secondImage.end());

        // Enough padding already!
        paddingSize = skipPadding(mI10e->secondImage.size(), hdr.page_size);
        data.insert(data.end(), paddingSize, 0);
    }

    // Device tree image
    if (!mI10e->dtImage.empty()) {
        data.insert(data.end(),
                    mI10e->dtImage.begin(),
                    mI10e->dtImage.end());

        // Last bit of padding (I hope)
        paddingSize = skipPadding(mI10e->dtImage.size(), hdr.page_size);
        data.insert(data.end(), paddingSize, 0);
    }

    dataOut->swap(data);
    return true;
}
bool MtkFormat::loadImage(const unsigned char *data, std::size_t size)
{
    // We can load the image as an Android boot image
    if (!mbp::AndroidFormat::loadImage(data, size)) {
        return false;
    }

    // Check if the kernel has an mtk header
    if (mI10e->hdrKernelSize >= sizeof(MtkHeader)) {
        auto mtkHdr = reinterpret_cast<const MtkHeader *>(mI10e->kernelImage.data());
        // Check magic
        if (std::memcmp(mtkHdr->magic, MTK_MAGIC, MTK_MAGIC_SIZE) == 0) {
            dumpMtkHeader(mtkHdr);

            std::size_t expected = sizeof(MtkHeader) + mtkHdr->size;
            std::size_t actual = mI10e->kernelImage.size();

            // Check size
            if (actual < expected) {
                LOGE("Expected %" PRIzu " byte kernel image, but have %" PRIzu " bytes",
                     expected, actual);
                return false;
            } else if (actual != expected) {
                LOGW("Expected %" PRIzu " byte kernel image, but have %" PRIzu " bytes",
                     expected, actual);
                LOGW("Repacked boot image will not be byte-for-byte identical to original");
            }

            // Move header to mI10e->mtkKernelHdr
            mI10e->mtkKernelHdr.assign(
                    mI10e->kernelImage.begin(),
                    mI10e->kernelImage.begin() + sizeof(MtkHeader));
            std::vector<unsigned char>(
                    mI10e->kernelImage.begin() + sizeof(MtkHeader),
                    mI10e->kernelImage.end())
                    .swap(mI10e->kernelImage);

            auto newMtkHdr = reinterpret_cast<MtkHeader *>(mI10e->mtkKernelHdr.data());
            newMtkHdr->size = 0;
        }
    }

    // Check if the ramdisk has an mtk header
    if (mI10e->hdrRamdiskSize >= sizeof(MtkHeader)) {
        auto mtkHdr = reinterpret_cast<const MtkHeader *>(mI10e->ramdiskImage.data());
        // Check magic
        if (std::memcmp(mtkHdr->magic, MTK_MAGIC, MTK_MAGIC_SIZE) == 0) {
            dumpMtkHeader(mtkHdr);

            std::size_t expected = sizeof(MtkHeader) + mtkHdr->size;
            std::size_t actual = mI10e->ramdiskImage.size();

            // Check size
            if (actual != expected) {
                LOGE("Expected %" PRIzu " byte ramdisk image, but have %" PRIzu " bytes",
                     expected, actual);
                return false;
            }

            // Move header to mI10e->mtkRamdiskHdr
            mI10e->mtkRamdiskHdr.assign(
                    mI10e->ramdiskImage.begin(),
                    mI10e->ramdiskImage.begin() + sizeof(MtkHeader));
            std::vector<unsigned char>(
                    mI10e->ramdiskImage.begin() + sizeof(MtkHeader),
                    mI10e->ramdiskImage.end())
                    .swap(mI10e->ramdiskImage);

            auto newMtkHdr = reinterpret_cast<MtkHeader *>(mI10e->mtkRamdiskHdr.data());
            newMtkHdr->size = 0;
        }
    }

    return true;
}
Exemple #14
0
static int do_set_ums_enable(char *cmd)
{
#ifdef ADD_ISO
	static struct devmapping *loop = NULL;
	static struct devmapping loopback;
	static char devpath[4096];
	// TODO: lun_syspath を変更する必要がある。
	static char *lun_syspath = "/sys/devices/platform/s3c-usbgadget/gadget/lun0/file";
	LOG_VOL("do_set_ums_enable:%s:%s\n", cmd, lun_syspath);

	if (!strcmp(cmd, VOLD_CMD_ENABLE_UMS_SD)) {
		loop = NULL;
		LOG_VOL("do_set_ums_enable:%s\n", VOLD_CMD_ENABLE_UMS_SD);
        	return volmgr_enable_ums(true);
	} else if (!strncmp(cmd, VOLD_CMD_ENABLE_UMS_CD, strlen(VOLD_CMD_ENABLE_UMS_CD))) {
		/* ループバックデバイスパスの取得 */
		LOG_VOL("do_set_ums_enable:%s\n", VOLD_CMD_ENABLE_UMS_CD);
		int rc = 0;
		memset(devpath, 0, 4096);
		memcpy(devpath, &cmd[strlen(VOLD_CMD_ENABLE_UMS_CD)], 
				strlen(&cmd[strlen(VOLD_CMD_ENABLE_UMS_CD)]));
		LOG_VOL("do_set_ums_enable devpath=%s\n", devpath);

		/* ループバックデバイスの登録 */
		loopback.src_type = dmsrc_loopback;
		loopback.type_data.loop.loop_src = devpath;
		loopback.type_data.loop.loop_dev = NULL;
		rc = loopback_start(&loopback);
		if (rc) {
			LOGE("loopback_start err=%d\n", rc);
		}
		/* ループバックデバイスパスをカーネルに追加する */
		/* カーネルにはloopback dev登録であることを知らせナイトね */
		rc = ums_enable(loopback.type_data.loop.loop_dev, lun_syspath, false);
		if (rc) {
			LOGE("ums_enable err=%d\n", rc);
		}
		loop = &loopback;
		return 0;
	} else {
		int ret = 0;
		LOG_VOL("do_set_ums_enable:%s\n", "disable_ums\n");
		if (loop) {
			int rc;
			rc = ums_disable(lun_syspath);
			if (rc) {
				LOGE("ums_enable err=%d\n", rc);
			}
			/* ループバックデバイスの解除 */
			rc = loopback_stop(loop);
			if (rc) {
				LOGE("loopback_stop err=%d\n", rc);
			} else {
				free(loopback.type_data.loop.loop_dev);
				loopback.type_data.loop.loop_dev = NULL;
			}
		} else {
			ret = volmgr_enable_ums(false);
		}
		loop = NULL;
		return ret;
	}
#else
    if (!strcmp(cmd, VOLD_CMD_ENABLE_UMS))
        return volmgr_enable_ums(true);

    return volmgr_enable_ums(false);
#endif /* ADD_ISO */
}
/*
 * Issue a method call with a variable number of arguments.  We process
 * the contents of "args" by scanning the method signature.
 *
 * Pass in NULL for "obj" on calls to static methods.
 *
 * We don't need to take the class as an argument because, in Dalvik,
 * we don't need to worry about static synchronized methods.
 */
void dvmCallMethodV(Thread* self, const Method* method, Object* obj,
    JValue* pResult, va_list args)
{
    const char* desc = &(method->shorty[1]); // [0] is the return type.
    int verifyCount = 0;
    ClassObject* clazz;
    u4* ins;

    clazz = callPrep(self, method, obj, false);
    if (clazz == NULL)
        return;

    /* "ins" for new frame start at frame pointer plus locals */
    ins = ((u4*)self->curFrame) + (method->registersSize - method->insSize);

    //LOGD("  FP is %p, INs live at >= %p\n", self->curFrame, ins);

    /* put "this" pointer into in0 if appropriate */
    if (!dvmIsStaticMethod(method)) {
#ifdef WITH_EXTRA_OBJECT_VALIDATION
        assert(obj != NULL && dvmIsValidObject(obj));
#endif
        *ins++ = (u4) obj;
        verifyCount++;
    }

    while (*desc != '\0') {
        switch (*(desc++)) {
            case 'D': case 'J': {
                u8 val = va_arg(args, u8);
                memcpy(ins, &val, 8);       // EABI prevents direct store
                ins += 2;
                verifyCount += 2;
                break;
            }
            case 'F': {
                /* floats were normalized to doubles; convert back */
                float f = (float) va_arg(args, double);
                *ins++ = dvmFloatToU4(f);
                verifyCount++;
                break;
            }
#ifdef WITH_EXTRA_OBJECT_VALIDATION
            case 'L': {     /* 'shorty' descr uses L for all refs, incl array */
                Object* argObj = (Object*) va_arg(args, u4);
                assert(obj == NULL || dvmIsValidObject(obj));
                *ins++ = (u4) argObj;
                verifyCount++;
                break;
            }
#endif
            default: {
                *ins++ = va_arg(args, u4);
                verifyCount++;
                break;
            }
        }
    }

#ifndef NDEBUG
    if (verifyCount != method->insSize) {
        LOGE("Got vfycount=%d insSize=%d for %s.%s\n", verifyCount,
            method->insSize, clazz->descriptor, method->name);
        assert(false);
        goto bail;
    }
#endif

    //dvmDumpThreadStack(dvmThreadSelf());

    if (dvmIsNativeMethod(method)) {
        /*
         * Because we leave no space for local variables, "curFrame" points
         * directly at the method arguments.
         */
        (*method->nativeFunc)(self->curFrame, pResult, method, self);
    } else {
        dvmInterpret(self, method, pResult);
    }

bail:
    dvmPopFrame(self);
}
bool SocketsToSDL::CreateSignal()
{
    int tcp1, tcp2;
    sockaddr_in name;
	memset(&name, 0, sizeof(name));
	name.sin_family = AF_INET;
	name.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
#ifdef WIN32
    int namelen = sizeof(name);
#else
    size_t namelen = sizeof(name);;
#endif

    tcp1 = tcp2 = -1;
	int tcp = socket(AF_INET, SOCK_STREAM, 0);
	if (tcp == -1){
		goto clean;
	}
	if (bind(tcp, (sockaddr*)&name, namelen) == -1){
		goto clean;
	}
	if (::listen(tcp, 5) == -1){
		goto clean;
	}
#ifdef ANDROID
    if (getsockname(tcp, (sockaddr*)&name, (socklen_t *)&namelen) == -1){
#else
    if (getsockname(tcp, (sockaddr*)&name, &namelen) == -1){
#endif
        goto clean;
	}
    tcp1 = socket(AF_INET, SOCK_STREAM, 0);
	if (tcp1 == -1){
		goto clean;
	}
    if (-1 == connect(tcp1, (sockaddr*)&name, namelen)){
		goto clean;
	}
#ifdef ANDROID
    tcp2 = accept(tcp, (sockaddr*)&name, (socklen_t *)&namelen);
#else
    tcp2 = accept(tcp, (sockaddr*)&name, &namelen);
#endif
	if (tcp2 == -1){
		goto clean;
	}
#ifdef WIN32
    if (closesocket(tcp) == -1){
#else
    if (close(tcp) == -1){
#endif
        goto clean;
	}
	m_Write_Sign = tcp1;
	m_Read_Sign = tcp2;
#ifdef WIN32
    {
        u_long iMode = 1;
        ioctlsocket(m_Read_Sign, FIONBIO, (u_long FAR*) &iMode);
    }
#else
    #include<fcntl.h>
    fcntl(m_Read_Sign,F_SETFL, O_NONBLOCK);
#endif
    return true;

clean:
	if (tcp != -1){
#ifdef WIN32
        closesocket(tcp);
#else
        close(tcp);
#endif
    }
	if (tcp2 != -1){
#ifdef WIN32
        closesocket(tcp2);
#else
        close(tcp2);
#endif
    }
	if (tcp1 != -1){
#ifdef WIN32
        closesocket(tcp1);
#else
        close(tcp1);
#endif
    }
	return false;
}

void* StartSocketThread(void* p) {
	SocketsToSDL * pThis = (SocketsToSDL *)p;
	pThis->RunThread();
	return 0;
}

bool SocketsToSDL::ConnectTo(std::vector<IChannel *> Channels, INetworkStatus * pNetwork)
{
    m_pNetwork = pNetwork;
	if (!CreateSignal())
		return false;

    int iNum = Channels.size();
    for (int i = 0; i < iNum; i++)
	{
        LOGE("-------");
        SOCK_HANDLE * pHandle = getNewSocketHandle(Channels[i], m_sHost, m_iPort);

        if(pHandle != NULL)
        {
            m_SocketHandles.push_back(pHandle);
            Channels[i]->setSocketManager(this, pHandle);
        }
        else
        {
            goto FAILED;
        }
	}

    m_bTerminate = false;
	if (0 != pthread_create(&m_SendThread, 0, &StartSocketThread, this))
		goto FAILED;

    return true;

FAILED:
    CloseSockets();
    return false;
}
/*
 * Issue a method call with arguments provided in an array.  We process
 * the contents of "args" by scanning the method signature.
 *
 * The values were likely placed into an uninitialized jvalue array using
 * the field specifiers, which means that sub-32-bit fields (e.g. short,
 * boolean) may not have 32 or 64 bits of valid data.  This is different
 * from the varargs invocation where the C compiler does a widening
 * conversion when calling a function.  As a result, we have to be a
 * little more precise when pulling stuff out.
 */
void dvmCallMethodA(Thread* self, const Method* method, Object* obj,
    JValue* pResult, const jvalue* args)
{
    const char* desc = &(method->shorty[1]); // [0] is the return type.
    int verifyCount = 0;
    ClassObject* clazz;
    u4* ins;

    clazz = callPrep(self, method, obj, false);
    if (clazz == NULL)
        return;

    /* "ins" for new frame start at frame pointer plus locals */
    ins = ((u4*)self->curFrame) + (method->registersSize - method->insSize);

    /* put "this" pointer into in0 if appropriate */
    if (!dvmIsStaticMethod(method)) {
        assert(obj != NULL);
        *ins++ = (u4) obj;
        verifyCount++;
    }

    while (*desc != '\0') {
        switch (*(desc++)) {
            case 'D': case 'J': {
                memcpy(ins, &args->j, 8);   /* EABI prevents direct store */
                ins += 2;
                verifyCount += 2;
                args++;
                break;
            }
            case 'F': case 'I': case 'L': { /* (no '[' in short signatures) */
                *ins++ = args->i;           /* get all 32 bits */
                verifyCount++;
                args++;
                break;
            }
            case 'S': {
                *ins++ = args->s;           /* 16 bits, sign-extended */
                verifyCount++;
                args++;
                break;
            }
            case 'C': {
                *ins++ = args->c;           /* 16 bits, unsigned */
                verifyCount++;
                args++;
                break;
            }
            case 'B': {
                *ins++ = args->b;           /* 8 bits, sign-extended */
                verifyCount++;
                args++;
                break;
            }
            case 'Z': {
                *ins++ = args->z;           /* 8 bits, zero or non-zero */
                verifyCount++;
                args++;
                break;
            }
            default: {
                LOGE("Invalid char %c in short signature of %s.%s\n",
                    *(desc-1), clazz->descriptor, method->name);
                assert(false);
                goto bail;
            }
        }
    }

#ifndef NDEBUG
    if (verifyCount != method->insSize) {
        LOGE("Got vfycount=%d insSize=%d for %s.%s\n", verifyCount,
            method->insSize, clazz->descriptor, method->name);
        assert(false);
        goto bail;
    }
#endif

    if (dvmIsNativeMethod(method)) {
        /*
         * Because we leave no space for local variables, "curFrame" points
         * directly at the method arguments.
         */
        (*method->nativeFunc)(self->curFrame, pResult, method, self);
    } else {
        dvmInterpret(self, method, pResult);
    }

bail:
    dvmPopFrame(self);
}
Exemple #18
0
bool obj_loader::LoadOBJData(const char* path, std::vector<GLfloat>& vertices,
                             std::vector<GLfloat>& normals) {
  std::vector<unsigned int> vertexIndices, normalIndices;
  std::vector<GLfloat> temp_vertices, temp_normals;

  FILE* file = fopen(path, "r");
  if (file == NULL) {
    LOGE("Failed to open file: %s", path);
    return false;
  }

  while (1) {
    char lineHeader[128];
    int res = fscanf(file, "%s", lineHeader);
    if (res == EOF) break;
    if (strcmp(lineHeader, "v") == 0) {
      GLfloat vertex[3];
      int matches =
          fscanf(file, "%f %f %f\n", &vertex[0], &vertex[1], &vertex[2]);
      if (matches != 3) {
        LOGE("Format of 'v float float float' required for each vertice line");
        return false;
      }
      temp_vertices.push_back(vertex[0]);
      temp_vertices.push_back(vertex[1]);
      temp_vertices.push_back(vertex[2]);
    } else if (strcmp(lineHeader, "vn") == 0) {
      GLfloat normal[3];
      int matches =
          fscanf(file, "%f %f %f\n", &normal[0], &normal[1], &normal[2]);
      if (matches != 3) {
        LOGE("Format of 'vn float float float' required for each normal line");
        return false;
      }
      temp_normals.push_back(normal[0]);
      temp_normals.push_back(normal[1]);
      temp_normals.push_back(normal[2]);
    } else if (strcmp(lineHeader, "f") == 0) {
      GLushort vertexIndex[3];
      GLushort normalIndex[3];
      int matches = fscanf(file, "%hu//%hu %hu//%hu %hu//%hu\n",
                           &vertexIndex[0], &normalIndex[0], &vertexIndex[1],
                           &normalIndex[1], &vertexIndex[2], &normalIndex[2]);
      if (matches != 6) {
        LOGE("Format of 'f int//int int//int int//int' required for each face");
        return false;
      }
      // .obj file is 1-indexed, so subtract 1 from all indices.
      vertexIndices.push_back(vertexIndex[0] - 1);
      vertexIndices.push_back(vertexIndex[1] - 1);
      vertexIndices.push_back(vertexIndex[2] - 1);
      normalIndices.push_back(normalIndex[0] - 1);
      normalIndices.push_back(normalIndex[1] - 1);
      normalIndices.push_back(normalIndex[2] - 1);
    } else {
      char comments_buffer[1000];
      fgets(comments_buffer, 1000, file);
    }
  }

  for (unsigned int i = 0; i < vertexIndices.size(); i++) {
    unsigned int vertexIndex = vertexIndices[i];
    unsigned int normalIndex = normalIndices[i];

    vertices.push_back(temp_vertices[vertexIndex * 3]);
    vertices.push_back(temp_vertices[vertexIndex * 3 + 1]);
    vertices.push_back(temp_vertices[vertexIndex * 3 + 2]);
    normals.push_back(temp_normals[normalIndex * 3]);
    normals.push_back(temp_normals[normalIndex * 3 + 1]);
    normals.push_back(temp_normals[normalIndex * 3 + 2]);
  }
  fclose(file);
  return true;
}
void ui_init(void) {
    ui_has_initialized = 1;
    gr_init();
    set_min_swipe_lengths();
#ifdef USE_VIRTUAL_KEY
    ui_get_virtualkey_size();
#endif
    ev_init(input_callback, NULL);

    text_col = text_row = 0;
    text_rows = (gr_fb_height() - virtualkey_h) / CHAR_HEIGHT;
    max_menu_rows = text_rows - MIN_LOG_ROWS;
    if (max_menu_rows > MENU_MAX_ROWS)
        max_menu_rows = MENU_MAX_ROWS;
    if (text_rows > MAX_ROWS) text_rows = MAX_ROWS;
    text_top = 1;

    text_cols = gr_fb_width() / CHAR_WIDTH;
    if (text_cols > MAX_COLS - 1) text_cols = MAX_COLS - 1;

    int i;
    for (i = 0; BITMAPS[i].name != NULL; ++i) {
        int result = res_create_surface(BITMAPS[i].name, BITMAPS[i].surface);
        if (result < 0) {
            LOGE("Missing bitmap %s\n(Code %d)\n", BITMAPS[i].name, result);
        }
    }

    gProgressBarIndeterminate = malloc(ui_parameters.indeterminate_frames *
                                       sizeof(gr_surface));
    for (i = 0; i < ui_parameters.indeterminate_frames; ++i) {
        char filename[40];
        // "indeterminate01.png", "indeterminate02.png", ...
        sprintf(filename, "indeterminate%02d", i+1);
        int result = res_create_surface(filename, gProgressBarIndeterminate+i);
        if (result < 0) {
            LOGE("Missing bitmap %s\n(Code %d)\n", filename, result);
        }
    }

    if (ui_parameters.installing_frames > 0) {
        gInstallationOverlay = malloc(ui_parameters.installing_frames *
                                      sizeof(gr_surface));
        for (i = 0; i < ui_parameters.installing_frames; ++i) {
            char filename[40];
            // "icon_installing_overlay01.png",
            // "icon_installing_overlay02.png", ...
            sprintf(filename, "icon_installing_overlay%02d", i+1);
            int result = res_create_surface(filename, gInstallationOverlay+i);
            if (result < 0) {
                LOGE("Missing bitmap %s\n(Code %d)\n", filename, result);
            }
        }

        // Adjust the offset to account for the positioning of the
        // base image on the screen.
        if (gBackgroundIcon[BACKGROUND_ICON_INSTALLING] != NULL) {
            gr_surface bg = gBackgroundIcon[BACKGROUND_ICON_INSTALLING];
            ui_parameters.install_overlay_offset_x +=
                (gr_fb_width() - gr_get_width(bg)) / 2;
            ui_parameters.install_overlay_offset_y +=
                (gr_fb_height() - gr_get_height(bg)) / 2;
        }
    } else {
        gInstallationOverlay = NULL;
    }

    char enable_key_repeat[PROPERTY_VALUE_MAX];
    property_get("ro.cwm.enable_key_repeat", enable_key_repeat, "");
    if (!strcmp(enable_key_repeat, "true") || !strcmp(enable_key_repeat, "1")) {
        boardEnableKeyRepeat = 1;

        char key_list[PROPERTY_VALUE_MAX];
        property_get("ro.cwm.repeatable_keys", key_list, "");
        if (strlen(key_list) == 0) {
            boardRepeatableKeys[boardNumRepeatableKeys++] = KEY_UP;
            boardRepeatableKeys[boardNumRepeatableKeys++] = KEY_DOWN;
            boardRepeatableKeys[boardNumRepeatableKeys++] = KEY_VOLUMEUP;
            boardRepeatableKeys[boardNumRepeatableKeys++] = KEY_VOLUMEDOWN;
        } else {
            char *pch = strtok(key_list, ",");
            while (pch != NULL) {
                boardRepeatableKeys[boardNumRepeatableKeys++] = atoi(pch);
                pch = strtok(NULL, ",");
            }
        }
    }

    pthread_t t;
    pthread_create(&t, NULL, progress_thread, NULL);
    pthread_create(&t, NULL, input_thread, NULL);
}
int format_device(const char *device, const char *path, const char *fs_type) {
    Volume* v = volume_for_path(path);
    if (v == NULL) {
        // silent failure for sd-ext
        if (strcmp(path, "/sd-ext") == 0)
            return -1;
        LOGE("unknown volume \"%s\"\n", path);
        return -1;
    }
    if (is_data_media_volume_path(path)) {
        return format_unknown_device(NULL, path, NULL);
    }
    if (strstr(path, "/data") == path && is_data_media()) {
        return format_unknown_device(NULL, path, NULL);
    }
    if (strcmp(fs_type, "ramdisk") == 0) {
        // you can't format the ramdisk.
        LOGE("can't format_volume \"%s\"", path);
        return -1;
    }

    if (strcmp(fs_type, "rfs") == 0) {
        if (ensure_path_unmounted(path) != 0) {
            LOGE("format_volume failed to unmount \"%s\"\n", v->mount_point);
            return -1;
        }
        if (0 != format_rfs_device(device, path)) {
            LOGE("format_volume: format_rfs_device failed on %s\n", device);
            return -1;
        }
        return 0;
    }

    if (strcmp(v->mount_point, path) != 0) {
        return format_unknown_device(v->device, path, NULL);
    }

    if (ensure_path_unmounted(path) != 0) {
        LOGE("format_volume failed to unmount \"%s\"\n", v->mount_point);
        return -1;
    }

    if (strcmp(fs_type, "yaffs2") == 0 || strcmp(fs_type, "mtd") == 0) {
        mtd_scan_partitions();
        const MtdPartition* partition = mtd_find_partition_by_name(device);
        if (partition == NULL) {
            LOGE("format_volume: no MTD partition \"%s\"\n", device);
            return -1;
        }

        MtdWriteContext *write = mtd_write_partition(partition);
        if (write == NULL) {
            LOGW("format_volume: can't open MTD \"%s\"\n", device);
            return -1;
        } else if (mtd_erase_blocks(write, -1) == (off_t) -1) {
            LOGW("format_volume: can't erase MTD \"%s\"\n", device);
            mtd_write_close(write);
            return -1;
        } else if (mtd_write_close(write)) {
            LOGW("format_volume: can't close MTD \"%s\"\n",device);
            return -1;
        }
        return 0;
    }

    if (strcmp(fs_type, "ext4") == 0) {
        int length = 0;
        if (strcmp(v->fs_type, "ext4") == 0) {
            // Our desired filesystem matches the one in fstab, respect v->length
            length = v->length;
        }
        reset_ext4fs_info();
        int result = make_ext4fs(device, length, v->mount_point, sehandle);
        if (result != 0) {
            LOGE("format_volume: make_extf4fs failed on %s\n", device);
            return -1;
        }
        return 0;
    }

    return format_unknown_device(device, path, fs_type);
}
Exemple #21
0
int gpu_context_t::gralloc_alloc_buffer(size_t size, int usage, buffer_handle_t* pHandle,
                                        int bufferType, int format, int width, int height)
{
    int err = 0;
    int flags = 0;

    int fd = -1;
    void* base = 0; // XXX JMG: This should change to just get an address from
                    // the PmemAllocator rather than getting the base & offset separately
    int offset = 0;
    int lockState = 0;

    size = roundUpToPageSize(size);
#ifndef USE_ASHMEM
    if (usage & GRALLOC_USAGE_HW_TEXTURE) {
        // enable pmem in that case, so our software GL can fallback to
        // the copybit module.
        flags |= private_handle_t::PRIV_FLAGS_USES_PMEM;
    }

    if (usage & GRALLOC_USAGE_HW_2D) {
        flags |= private_handle_t::PRIV_FLAGS_USES_PMEM;
    }
#else
    // Enable use of PMEM only when MDP composition is used (and other conditions apply).
    // Else fall back on using ASHMEM
    if ((get_composition_type() == MDP_COMPOSITION) &&
        ((usage & GRALLOC_USAGE_HW_TEXTURE) || (usage & GRALLOC_USAGE_HW_2D)) ) {
        flags |= private_handle_t::PRIV_FLAGS_USES_PMEM;
    }

    if (usage & GRALLOC_USAGE_PRIVATE_PMEM) {
        flags |= private_handle_t::PRIV_FLAGS_USES_PMEM;
    }
#endif
    if ((usage & GRALLOC_USAGE_PRIVATE_PMEM_ADSP) || (usage & GRALLOC_USAGE_PRIVATE_PMEM_SMIPOOL)
        || (usage & GRALLOC_USAGE_EXTERNAL_DISP) || (usage & GRALLOC_USAGE_PROTECTED)) {
        flags |= private_handle_t::PRIV_FLAGS_USES_PMEM_ADSP;
        flags &= ~private_handle_t::PRIV_FLAGS_USES_PMEM;
    }

    private_module_t* m = reinterpret_cast<private_module_t*>(common.module);
    if((flags & private_handle_t::PRIV_FLAGS_USES_PMEM) == 0 &&
       (flags & private_handle_t::PRIV_FLAGS_USES_PMEM_ADSP) == 0) {
       flags |= private_handle_t::PRIV_FLAGS_USES_ASHMEM;
       err = alloc_ashmem_buffer(size, (unsigned int)pHandle, &base, &offset, &fd);
       if(err >= 0)
            lockState |= private_handle_t::LOCK_STATE_MAPPED; 
    }
    else if ((flags & private_handle_t::PRIV_FLAGS_USES_PMEM) != 0 ||
        (flags & private_handle_t::PRIV_FLAGS_USES_PMEM_ADSP) != 0) {

        PmemAllocator* pma = 0;

        if ((flags & private_handle_t::PRIV_FLAGS_USES_PMEM) != 0) {
          if ((flags & private_handle_t::PRIV_FLAGS_USES_PMEM_ADSP) != 0) {
              LOGE("attempting to allocate a gralloc buffer with both the "
                   "USES_PMEM and USES_PMEM_ADSP flags.  Unsetting the "
                   "USES_PMEM_ADSP flag.");
              flags &= ~private_handle_t::PRIV_FLAGS_USES_PMEM_ADSP;
          }
          pma = &pmemAllocator;
        } else { // (flags & private_handle_t::PRIV_FLAGS_USES_PMEM_ADSP) != 0
          pma = &pmemAdspAllocator;
        }

        // PMEM buffers are always mmapped
        lockState |= private_handle_t::LOCK_STATE_MAPPED;

        err = pma->alloc_pmem_buffer(size, usage, &base, &offset, &fd, format);
        if (err < 0) {
            // Pmem allocation failed. Try falling back to ashmem iff we are:
            // a. not using MDP composition
            // b. not allocating memory for a buffer to be used by overlays
            // c. The client has not explicitly requested a PMEM buffer
            if ((get_composition_type() != MDP_COMPOSITION) &&
                (bufferType != BUFFER_TYPE_VIDEO) &&
                ((usage & GRALLOC_USAGE_PRIVATE_PMEM) == 0) &&
                ((usage & GRALLOC_USAGE_PRIVATE_PMEM_ADSP) == 0)) {
                // the caller didn't request PMEM, so we can try something else
                flags &= ~private_handle_t::PRIV_FLAGS_USES_PMEM;
                err = 0;
                LOGE("Pmem allocation failed. Trying ashmem");
                goto try_ashmem;
            } else {
                LOGE("couldn't open pmem (%s)", strerror(errno));
            }
        }
    } else {
try_ashmem:
        err = alloc_ashmem_buffer(size, (unsigned int)pHandle, &base, &offset, &fd);
        if (err >= 0) {
            lockState |= private_handle_t::LOCK_STATE_MAPPED;
            flags |= private_handle_t::PRIV_FLAGS_USES_ASHMEM;
        } else {
            LOGE("Ashmem fallback failed");
        }
    }

    if (err == 0) {
        private_handle_t* hnd = new private_handle_t(fd, size, flags, bufferType, format, width, height);
        hnd->offset = offset;
        hnd->base = int(base)+offset;
        hnd->lockState = lockState;
        *pHandle = hnd;
    }

    LOGE_IF(err, "gralloc failed err=%s", strerror(-err));

    return err;
}
int format_unknown_device(const char *device, const char* path, const char *fs_type)
{
    LOGI("Formatting unknown device.\n");

    if (fs_type != NULL && get_flash_type(fs_type) != UNSUPPORTED)
        return erase_raw_partition(fs_type, device);

    // if this is SDEXT:, don't worry about it if it does not exist.
    if (0 == strcmp(path, "/sd-ext"))
    {
        struct stat st;
        Volume *vol = volume_for_path("/sd-ext");
        if (vol == NULL || 0 != stat(vol->device, &st))
        {
            ui_print("No app2sd partition found. Skipping format of /sd-ext.\n");
            return 0;
        }
    }

    if (NULL != fs_type) {
        if (strcmp("ext3", fs_type) == 0) {
            LOGI("Formatting ext3 device.\n");
            if (0 != ensure_path_unmounted(path)) {
                LOGE("Error while unmounting %s.\n", path);
                return -12;
            }
            return format_ext3_device(device);
        }

        if (strcmp("ext2", fs_type) == 0) {
            LOGI("Formatting ext2 device.\n");
            if (0 != ensure_path_unmounted(path)) {
                LOGE("Error while unmounting %s.\n", path);
                return -12;
            }
            return format_ext2_device(device);
        }
    }

    if (0 != ensure_path_mounted(path))
    {
        ui_print("Error mounting %s!\n", path);
        ui_print("Skipping format...\n");
        return 0;
    }

    static char tmp[PATH_MAX];
    if (strcmp(path, "/data") == 0) {
        sprintf(tmp, "cd /data ; for f in $(ls -a | grep -v ^media$); do rm -rf $f; done");
        __system(tmp);
        // if the /data/media sdcard has already been migrated for android 4.2,
        // prevent the migration from happening again by writing the .layout_version
        struct stat st;
        if (0 == lstat("/data/media/0", &st)) {
			char* layout_version = "2";
			FILE* f = fopen("/data/.layout_version", "wb");
			if (NULL != f) {
				fwrite(layout_version, 1, 2, f);
				fclose(f);
			} else {
				LOGI("error opening /data/.layout_version for write.\n");
			}
		} else {
			LOGI("/data/media/0 not found. migration may occur.\n");
		}
    }
    else {
        sprintf(tmp, "rm -rf %s/*", path);
        __system(tmp);
        sprintf(tmp, "rm -rf %s/.*", path);
        __system(tmp);
    }

    ensure_path_unmounted(path);
    return 0;
}
int set_Speed(int fd, int nSpeed)
{
	int   i;
	int   status;
	struct termios Opt;
	
	tcgetattr(fd, &Opt);
	LOGE("num = %d  %d\n",sizeof(speed_arr),sizeof(int));
/*	for ( i= 0;  i < sizeof(speed_arr) / sizeof(int);  i++)
	{
		if  (nSpeed == name_arr[i])
		{
			printf("nSpeed = %d  %d\n",nSpeed,fd);
		    tcflush(fd, TCIOFLUSH);
			cfsetispeed(&Opt, speed_arr[i]);
			cfsetospeed(&Opt, speed_arr[i]);
			printf("speed = %d \n",speed_arr[i]);
			status = tcsetattr(fd, TCSANOW, &Opt);
			if  (status != 0)
			{
		        printf("tcsetattr fd1\n");
				return(FALSE);
			}
		 	return(TRUE);
	 	}
		tcflush(fd,TCIOFLUSH);
	}
	printf("no this speed!!1\n");
	return(FALSE);*/
	tcflush(fd, TCIOFLUSH);
	switch( nSpeed )
    {
    case 2400:
        cfsetispeed(&Opt, B2400);
        cfsetospeed(&Opt, B2400);
        break;
    case 4800:
        cfsetispeed(&Opt, B4800);
        cfsetospeed(&Opt, B4800);
        break;
    case 9600:
        cfsetispeed(&Opt, B9600);
        cfsetospeed(&Opt, B9600);
        break;
    case 19200:
        cfsetispeed(&Opt, B19200);
        cfsetospeed(&Opt, B19200);
        break;
    case 115200:
        cfsetispeed(&Opt, B115200);
        cfsetospeed(&Opt, B115200);
        break;
    default:
        cfsetispeed(&Opt, B19200);
        cfsetospeed(&Opt, B19200);
        break;
    }

	status = tcsetattr(fd, TCSANOW, &Opt);
	if  (status != 0)
	{
        LOGE("tcsetattr fd1\n");
		return(FALSE);
	}

	return(TRUE);
}
Exemple #24
0
    void load_key_map() {
        FILE* fstab = fopen("/etc/recovery.kl", "r");
        if (fstab != NULL) {
            LOGI("loaded /etc/recovery.kl\n");
            int alloc = 2;
            device_keys = (KeyMapItem*)malloc(alloc * sizeof(KeyMapItem));

            device_keys[0].type = "select";
            device_keys[0].value = kNoAction;
            device_keys[0].key[0] = -1;
            device_keys[0].key[1] = -1;
            device_keys[0].key[2] = -1;
            device_keys[0].key[3] = -1;
            device_keys[0].key[4] = -1;
            device_keys[0].key[5] = -1;
            num_keys = 0;

            char buffer[1024];
            int i;
            while (fgets(buffer, sizeof(buffer)-1, fstab)) {
                for (i = 0; buffer[i] && isspace(buffer[i]); ++i);
                if (buffer[i] == '\0' || buffer[i] == '#') continue;

                char* original = strdup(buffer);

                char* type = strtok(buffer+i, " \t\n");
                char* key1 = strtok(NULL, " \t\n");
                char* key2 = strtok(NULL, " \t\n");
                char* key3 = strtok(NULL, " \t\n");
                char* key4 = strtok(NULL, " \t\n");
                char* key5 = strtok(NULL, " \t\n");
                char* key6 = strtok(NULL, " \t\n");

                if (type && key1) {
                    while (num_keys >= alloc) {
                        alloc *= 2;
                        device_keys = (KeyMapItem*)realloc(device_keys, alloc*sizeof(KeyMapItem));
                    }
                    device_keys[num_keys].type = strdup(type);
                    device_keys[num_keys].value = getKey(type);
                    device_keys[num_keys].key[0] = key1?atoi(key1):-1;
                    device_keys[num_keys].key[1] = key2?atoi(key2):-1;
                    device_keys[num_keys].key[2] = key3?atoi(key3):-1;
                    device_keys[num_keys].key[3] = key4?atoi(key4):-1;
                    device_keys[num_keys].key[4] = key5?atoi(key5):-1;
                    device_keys[num_keys].key[5] = key6?atoi(key6):-1;

                    ++num_keys;
                } else {
                    LOGE("skipping malformed recovery.lk line: %s\n", original);
                }
                free(original);
            }

            fclose(fstab);

        } else {
            LOGE("failed to open /etc/recovery.kl, use default map\n");
            num_keys = NUM_DEFAULT_KEY_MAP;
            device_keys = g_default_keymap;
        }

        LOGI("recovery key map table\n");
        LOGI("=========================\n");

        int i;
        for (i = 0; i < num_keys; ++i) {
            KeyMapItem* v = &device_keys[i];
            LOGI("  %d type:%s value:%d key:%d %d %d %d %d %d\n", i, v->type, v->value,
                 v->key[0], v->key[1], v->key[2], v->key[3], v->key[4], v->key[5]);
        }
        LOGI("\n");
    }
/*
 * This callback is called when |AudioFileStreamParseBytes| has enough data to
 * extract one or more MP3 packets.
 */
void
AppleMP3Reader::AudioSampleCallback(UInt32 aNumBytes,
                                    UInt32 aNumPackets,
                                    const void *aData,
                                    AudioStreamPacketDescription *aPackets)
{
  LOGD("got %u bytes, %u packets\n", aNumBytes, aNumPackets);

  // 1 frame per packet * num channels * 32-bit float
  uint32_t decodedSize = MAX_AUDIO_FRAMES * mAudioChannels *
                         sizeof(AudioDataValue);

  // descriptions for _decompressed_ audio packets. ignored.
  nsAutoArrayPtr<AudioStreamPacketDescription>
    packets(new AudioStreamPacketDescription[MAX_AUDIO_FRAMES]);

  // This API insists on having MP3 packets spoon-fed to it from a callback.
  // This structure exists only to pass our state and the result of the parser
  // on to the callback above.
  PassthroughUserData userData = { this, aNumPackets, aNumBytes, aData, aPackets, false };

  do {
    // Decompressed audio buffer
    nsAutoArrayPtr<uint8_t> decoded(new uint8_t[decodedSize]);

    AudioBufferList decBuffer;
    decBuffer.mNumberBuffers = 1;
    decBuffer.mBuffers[0].mNumberChannels = mAudioChannels;
    decBuffer.mBuffers[0].mDataByteSize = decodedSize;
    decBuffer.mBuffers[0].mData = decoded.get();

    // in: the max number of packets we can handle from the decoder.
    // out: the number of packets the decoder is actually returning.
    UInt32 numFrames = MAX_AUDIO_FRAMES;

    OSStatus rv = AudioConverterFillComplexBuffer(mAudioConverter,
                                                  PassthroughInputDataCallback,
                                                  &userData,
                                                  &numFrames /* in/out */,
                                                  &decBuffer,
                                                  packets.get());

    if (rv && rv != kNeedMoreData) {
      LOGE("Error decoding audio stream: %x\n", rv);
      break;
    }

    // If we decoded zero frames then AudiOConverterFillComplexBuffer is out
    // of data to provide.  We drained its internal buffer completely on the
    // last pass.
    if (numFrames == 0 && rv == kNeedMoreData) {
      LOGD("FillComplexBuffer out of data exactly\n");
      break;
    }

    int64_t time = FramesToUsecs(mCurrentAudioFrame, mAudioSampleRate).value();
    int64_t duration = FramesToUsecs(numFrames, mAudioSampleRate).value();

    LOGD("pushed audio at time %lfs; duration %lfs\n",
         (double)time / USECS_PER_S, (double)duration / USECS_PER_S);

    AudioData *audio = new AudioData(mResource.Tell(),
                                     time, duration, numFrames,
                                     reinterpret_cast<AudioDataValue *>(decoded.forget()),
                                     mAudioChannels, mAudioSampleRate);
    mAudioQueue.Push(audio);

    mCurrentAudioFrame += numFrames;

    if (rv == kNeedMoreData) {
      // No error; we just need more data.
      LOGD("FillComplexBuffer out of data\n");
      break;
    }
  } while (true);
}
static void remote_recv_cb(EV_P_ ev_io *w, int revents)
{
    struct remote_ctx *remote_ctx = (struct remote_ctx *)w;
    struct server_ctx *server_ctx = remote_ctx->server_ctx;

    // server has been closed
    if (server_ctx == NULL) {
        LOGE("[udp] invalid server.");
        close_and_free_remote(EV_A_ remote_ctx);
        return;
    }

    if (verbose) {
        LOGD("[udp] remote receive a packet");
    }

    // triger the timer
    ev_timer_again(EV_A_ & remote_ctx->watcher);

    struct sockaddr src_addr;
    socklen_t src_addr_len = sizeof(src_addr);
    char *buf = malloc(BUF_SIZE);

    // recv
    ssize_t buf_len = recvfrom(remote_ctx->fd, buf, BUF_SIZE, 0, &src_addr,
                               &src_addr_len);

    if (buf_len == -1) {
        // error on recv
        // simply drop that packet
        if (verbose) {
            ERROR("[udp] server_recvfrom");
        }
        goto CLEAN_UP;
    }

#ifdef UDPRELAY_LOCAL
    buf = ss_decrypt_all(BUF_SIZE, buf, &buf_len, server_ctx->method);
    if (buf == NULL) {
        if (verbose) {
            ERROR("[udp] server_ss_decrypt_all");
        }
        goto CLEAN_UP;
    }

    int len = parse_udprealy_header(buf, buf_len, NULL, NULL);
    if (len == 0) {
        LOGD("[udp] error in parse header");
        // error in parse header
        goto CLEAN_UP;
    }
    // server may return using a different address type other than the type we
    // have used during sending

#ifdef UDPRELAY_TUNNEL
    // Construct packet
    buf_len -= len;
    memmove(buf, buf + len, buf_len);
#else
    // Construct packet
    char *tmpbuf = malloc(buf_len + 3);
    memset(tmpbuf, 0, 3);
    memcpy(tmpbuf + 3, buf, buf_len);
    free(buf);
    buf = tmpbuf;
    buf_len += 3;
#endif
#endif

#ifdef UDPRELAY_REMOTE

    unsigned int addr_header_len = remote_ctx->addr_header_len;

    // Construct packet
    char *tmpbuf = malloc(buf_len + addr_header_len);
    memcpy(tmpbuf, remote_ctx->addr_header, addr_header_len);
    memcpy(tmpbuf + addr_header_len, buf, buf_len);
    free(buf);
    buf = tmpbuf;
    buf_len += addr_header_len;

    buf = ss_encrypt_all(BUF_SIZE, buf, &buf_len, server_ctx->method);
#endif

    size_t addr_len = sizeof(struct sockaddr_in);
    if (remote_ctx->src_addr.ss_family == AF_INET6) {
        addr_len = sizeof(struct sockaddr_in6);
    }
    int s = sendto(server_ctx->fd, buf, buf_len, 0,
                   (struct sockaddr *)&remote_ctx->src_addr, addr_len);

    if (s == -1) {
        ERROR("[udp] sendto_local");
    }

 CLEAN_UP:
    free(buf);

}
void TangoData::UpdateColorTexture() {
  if (TangoService_updateTexture(TANGO_CAMERA_COLOR, &timestamp)
      != TANGO_SUCCESS) {
    LOGE("TangoService_updateTexture(): Failed");
  }
}
static void server_recv_cb(EV_P_ ev_io *w, int revents)
{
    struct server_ctx *server_ctx = (struct server_ctx *)w;
    struct sockaddr_storage src_addr;
    char *buf = malloc(BUF_SIZE);

    socklen_t src_addr_len = sizeof(struct sockaddr_storage);
    unsigned int offset = 0;

    ssize_t buf_len =
        recvfrom(server_ctx->fd, buf, BUF_SIZE, 0, (struct sockaddr *)&src_addr,
                 &src_addr_len);

    if (buf_len == -1) {
        // error on recv
        // simply drop that packet
        if (verbose) {
            ERROR("[udp] server_recvfrom");
        }
        goto CLEAN_UP;
    }

    if (verbose) {
        LOGD("[udp] server receive a packet.");
    }

#ifdef UDPRELAY_REMOTE
    buf = ss_decrypt_all(BUF_SIZE, buf, &buf_len, server_ctx->method);
    if (buf == NULL) {
        if (verbose) {
            ERROR("[udp] server_ss_decrypt_all");
        }
        goto CLEAN_UP;
    }
#endif

#ifdef UDPRELAY_LOCAL
#ifndef UDPRELAY_TUNNEL
    uint8_t frag = *(uint8_t *)(buf + 2);
    offset += 3;
#endif
#endif

    /*
     *
     * SOCKS5 UDP Request
     * +----+------+------+----------+----------+----------+
     * |RSV | FRAG | ATYP | DST.ADDR | DST.PORT |   DATA   |
     * +----+------+------+----------+----------+----------+
     * | 2  |  1   |  1   | Variable |    2     | Variable |
     * +----+------+------+----------+----------+----------+
     *
     * SOCKS5 UDP Response
     * +----+------+------+----------+----------+----------+
     * |RSV | FRAG | ATYP | DST.ADDR | DST.PORT |   DATA   |
     * +----+------+------+----------+----------+----------+
     * | 2  |  1   |  1   | Variable |    2     | Variable |
     * +----+------+------+----------+----------+----------+
     *
     * shadowsocks UDP Request (before encrypted)
     * +------+----------+----------+----------+
     * | ATYP | DST.ADDR | DST.PORT |   DATA   |
     * +------+----------+----------+----------+
     * |  1   | Variable |    2     | Variable |
     * +------+----------+----------+----------+
     *
     * shadowsocks UDP Response (before encrypted)
     * +------+----------+----------+----------+
     * | ATYP | DST.ADDR | DST.PORT |   DATA   |
     * +------+----------+----------+----------+
     * |  1   | Variable |    2     | Variable |
     * +------+----------+----------+----------+
     *
     * shadowsocks UDP Request and Response (after encrypted)
     * +-------+--------------+
     * |   IV  |    PAYLOAD   |
     * +-------+--------------+
     * | Fixed |   Variable   |
     * +-------+--------------+
     *
     */

#ifdef UDPRELAY_TUNNEL
    char addr_header[256] = { 0 };
    char * host = server_ctx->tunnel_addr.host;
    char * port = server_ctx->tunnel_addr.port;
    int host_len = strlen(host);
    uint16_t port_num = (uint16_t)atoi(port);
    uint16_t port_net_num = htons(port_num);
    int addr_header_len = 2 + host_len + 2;

    // initialize the addr header
    addr_header[0] = 3;
    addr_header[1] = host_len;
    memcpy(addr_header + 2, host, host_len);
    memcpy(addr_header + 2 + host_len, &port_net_num, 2);

    // reconstruct the buffer
    char *tmp = malloc(buf_len + addr_header_len);
    memcpy(tmp, addr_header, addr_header_len);
    memcpy(tmp + addr_header_len, buf, buf_len);
    free(buf);
    buf = tmp;
    buf_len += addr_header_len;

#else
    char host[256] = { 0 };
    char port[64] = { 0 };

    int addr_header_len = parse_udprealy_header(buf + offset,
                                                buf_len - offset, host, port);
    if (addr_header_len == 0) {
        // error in parse header
        goto CLEAN_UP;
    }
    char *addr_header = buf + offset;
#endif

    char *key = hash_key(addr_header, addr_header_len, &src_addr);
    struct cache *conn_cache = server_ctx->conn_cache;

    struct remote_ctx *remote_ctx = NULL;
    cache_lookup(conn_cache, key, (void *)&remote_ctx);

    if (remote_ctx != NULL) {
        if (memcmp(&src_addr, &remote_ctx->src_addr, sizeof(src_addr))
            || strcmp(addr_header, remote_ctx->addr_header) != 0) {
            remote_ctx = NULL;
        }
    }

    if (remote_ctx == NULL) {
        if (verbose) {
            LOGD("[udp] cache missed: %s:%s <-> %s", host, port,
                 get_addr_str((struct sockaddr *)&src_addr));
        }
    } else {
        if (verbose) {
            LOGD("[udp] cache hit: %s:%s <-> %s", host, port,
                 get_addr_str((struct sockaddr *)&src_addr));
        }
    }

#ifdef UDPRELAY_LOCAL

#ifndef UDPRELAY_TUNNEL
    if (frag) {
        LOGE("[udp] drop a message since frag is not 0, but %d", frag);
        goto CLEAN_UP;
    }
#endif

    if (remote_ctx == NULL) {
        struct addrinfo hints;
        struct addrinfo *result;

        memset(&hints, 0, sizeof(struct addrinfo));
        hints.ai_family = AF_UNSPEC;    /* Return IPv4 and IPv6 choices */
        hints.ai_socktype = SOCK_DGRAM; /* We want a UDP socket */

        int s = getaddrinfo(server_ctx->remote_host, server_ctx->remote_port,
                            &hints, &result);
        if (s != 0 || result == NULL) {
            LOGE("[udp] getaddrinfo: %s", gai_strerror(s));
            goto CLEAN_UP;
        }

        // Bind to any port
        int remotefd = create_remote_socket(result->ai_family == AF_INET6);
        if (remotefd < 0) {
            ERROR("[udp] udprelay bind() error..");
            // remember to free addrinfo
            freeaddrinfo(result);
            goto CLEAN_UP;
        }
        setnonblocking(remotefd);

#ifdef SO_NOSIGPIPE
        set_nosigpipe(remotefd);
#endif
#ifdef SET_INTERFACE
        if (server_ctx->iface) {
            setinterface(remotefd, server_ctx->iface);
        }
#endif

        // Init remote_ctx
        remote_ctx = new_remote(remotefd, server_ctx);
        remote_ctx->src_addr = src_addr;
        remote_ctx->dst_addr = *((struct sockaddr_storage *)result->ai_addr);
        remote_ctx->addr_header_len = addr_header_len;
        memcpy(remote_ctx->addr_header, addr_header, addr_header_len);

        // Add to conn cache
        cache_insert(conn_cache, key, (void *)remote_ctx);

        // Start remote io
        ev_io_start(EV_A_ & remote_ctx->io);

        // clean up
        freeaddrinfo(result);
    }

    if (offset > 0) {
        buf_len -= offset;
        memmove(buf, buf + offset, buf_len);
    }

    buf = ss_encrypt_all(BUF_SIZE, buf, &buf_len, server_ctx->method);

    size_t addr_len = sizeof(struct sockaddr_in);
    if (remote_ctx->dst_addr.ss_family == AF_INET6) {
        addr_len = sizeof(struct sockaddr_in6);
    }
    int s = sendto(remote_ctx->fd, buf, buf_len, 0,
                   (struct sockaddr *)&remote_ctx->dst_addr, addr_len);

    if (s == -1) {
        ERROR("[udp] sendto_remote");
    }

#else

    if (remote_ctx == NULL) {
        struct addrinfo hints;
        asyncns_query_t *query;
        memset(&hints, 0, sizeof(hints));
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_DGRAM;

        query = asyncns_getaddrinfo(server_ctx->asyncns,
                                    host, port, &hints);

        if (query == NULL) {
            ERROR("[udp] asyncns_getaddrinfo");
            goto CLEAN_UP;
        }

        struct query_ctx *query_ctx = new_query_ctx(query,
                                                    buf + addr_header_len,
                                                    buf_len - addr_header_len);
        query_ctx->server_ctx = server_ctx;
        query_ctx->addr_header_len = addr_header_len;
        query_ctx->src_addr = src_addr;
        memcpy(query_ctx->addr_header, addr_header, addr_header_len);
        asyncns_setuserdata(server_ctx->asyncns, query, query_ctx);
    } else {
        size_t addr_len = sizeof(struct sockaddr_in);
        if (remote_ctx->dst_addr.ss_family == AF_INET6) {
            addr_len = sizeof(struct sockaddr_in6);
        }
        int s = sendto(remote_ctx->fd, buf + addr_header_len,
                       buf_len - addr_header_len, 0,
                       (struct sockaddr *)&remote_ctx->dst_addr, addr_len);

        if (s == -1) {
            ERROR("[udp] sendto_remote");
        }
    }
#endif

 CLEAN_UP:
    free(buf);

}
Exemple #29
0
static int do_handshake(uv_stream_t *stream)
{
	server_ctx *ctx = (server_ctx *)stream->data;
	int n;

	if (!ctx->remote_ip) {
		if (ctx->buffer_len < 2) // Not interpretable
			return 1;
		uint8_t addrtype = ctx->handshake_buffer[0];
		if (addrtype == ADDRTYPE_IPV4) {
			if (ctx->buffer_len < 5)
				return 1;
			ctx->remote_ip = *((uint32_t *)(ctx->handshake_buffer + 1));
			SHIFT_BYTE_ARRAY_TO_LEFT(ctx->handshake_buffer, 5, HANDSHAKE_BUFFER_SIZE);
			ctx->buffer_len -= 5;
			// TODO: Print out
		} else if (addrtype == ADDRTYPE_DOMAIN) {
			uint8_t domain_len = ctx->handshake_buffer[1];
			if (!domain_len) { // Domain length is zero
				LOGE("Domain length is zero");
				HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
				return 0;
			}
			if (ctx->buffer_len < domain_len + 2)
				return 1;
			char domain[domain_len+1];
			domain[domain_len] = 0;
			memcpy(domain, ctx->handshake_buffer+2, domain_len);
			struct addrinfo hints;
    		hints.ai_family = AF_INET; // IPv4 Only
    		hints.ai_socktype = SOCK_STREAM;
    		hints.ai_protocol = IPPROTO_TCP;
    		hints.ai_flags = 0;
			uv_getaddrinfo_t *resolver = (uv_getaddrinfo_t *)malloc(sizeof(uv_getaddrinfo_t));
			if (!resolver) {
				HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
				FATAL("malloc() failed!");
			}
			resolver->data = ctx; // We need to locate back the stream
			LOGI("Domain is: %s", domain);
			n = uv_getaddrinfo(stream->loop, resolver, client_handshake_domain_resolved, domain, NULL, &hints);
			if (n) {
				SHOW_UV_ERROR(stream->loop);
				HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
				free(resolver);
				return 0;
			}
			SHIFT_BYTE_ARRAY_TO_LEFT(ctx->handshake_buffer, 2+domain_len, HANDSHAKE_BUFFER_SIZE);
			ctx->buffer_len -= 2 + domain_len;
			uv_read_stop(stream); // Pause the reading process, wait for resolve result
			return 1;
		} else { // Unsupported addrtype
			LOGI("addrtype unknown, closing");
			HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
			return 0;
		}
	} // !ctx->remote_ip

	if (!ctx->remote_port) {
		if (ctx->buffer_len < 2) // Not interpretable
			return 1;
		ctx->remote_port = *((uint16_t *)ctx->handshake_buffer);
		if (!ctx->remote_port) {
			LOGE("Remote port is zero");
			HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
			return 0;
		}
		SHIFT_BYTE_ARRAY_TO_LEFT(ctx->handshake_buffer, 2, HANDSHAKE_BUFFER_SIZE);
		ctx->buffer_len -= 2;
		// Try connect now
		n = uv_tcp_init(stream->loop, &ctx->remote);
		if (n)
			SHOW_UV_ERROR_AND_EXIT(stream->loop);
		uv_connect_t *req = (uv_connect_t *)malloc(sizeof(uv_connect_t));
		if (!req) {
			HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
			FATAL("malloc() failed!");
		}
		req->data = ctx;
		struct sockaddr_in remote_addr;
		memset(&remote_addr, 0, sizeof(remote_addr));
		remote_addr.sin_family = AF_INET;
		remote_addr.sin_addr.s_addr = ctx->remote_ip;
		remote_addr.sin_port = ctx->remote_port;
		n = uv_tcp_connect(req, &ctx->remote, remote_addr, connect_to_remote_cb);
		if (n) {
			SHOW_UV_ERROR(stream->loop);
			HANDLE_CLOSE((uv_handle_t*)stream, handshake_client_close_cb);
			free(req);
			return 0;
		}
	}

	uv_read_stop(stream);
	return 0;
}
Exemple #30
0
static int sensors_poll(struct sensors_data_device_t *dev, sensors_data_t* values)
{
    fd_set rfds;
    char coord[20];
    int ret;
    uint32_t new_sensors = 0;
    int fd, select_dim;
	struct timeval timeout;

    fd = event_fd;
	if (fd < 1) {
		LOGE("Bad coord file descriptor: %d", fd);
		return -1;
	}

#if 0
    select_dim = (fd > control_fd[CONTROL_READ]) ?
                 fd + 1 : control_fd[CONTROL_READ] + 1;
#else
	select_dim = fd + 1;
#endif

    while (1)
    {
        FD_ZERO(&rfds);
        FD_SET(fd, &rfds);
        //FD_SET(control_fd[CONTROL_READ], &rfds);

        do {
			timeout.tv_sec = 0;
			timeout.tv_usec = 100000;
            ret = select(select_dim, &rfds, NULL, NULL, &timeout);
        } while (ret < 0 && errno == EINTR);

		if (ret < 0) {
			LOGE("%s select error: %d", __func__, errno);
			return ret;
		}

#if 0
        if (FD_ISSET(control_fd[CONTROL_READ], &rfds))
        {
            char ch;
            read(control_fd[CONTROL_READ], &ch, sizeof(ch));
            LOGD("Wake up by the control system\n");
            return -EWOULDBLOCK;
        }
#endif

        lseek(fd, 0, SEEK_SET);
        ret = read(fd, coord, sizeof(coord));
        if (ret < 0)
            break;

        FD_CLR(control_fd[CONTROL_READ], &rfds);

		float x = 0, y = 0, z = 0;
		sscanf(coord, "%f %f %f\n", &x, &y, &z);
        sensors.acceleration.x = (-GRAVITY_EARTH * y) / 1000;
        sensors.acceleration.y = (-GRAVITY_EARTH * x) / 1000;
        sensors.acceleration.z = (-GRAVITY_EARTH * z) / 1000;
        sensors.time = 0;
#if 0
        LOGD("%s: sensor event %f, %f, %f\n", __FUNCTION__,
             sensors.acceleration.x, sensors.acceleration.y,
             sensors.acceleration.z);
#endif
        *values = sensors;
        values->sensor = ID_ACCELERATION;
        return ID_ACCELERATION;
    }
    return 0;
}