Ejemplo n.º 1
0
void* q__AllocateMemory(size_t size)
{
    // dumb alloc, no free
    qprintf("*** AllocateMemory(%x)", size);
    
    static uint32_t alloc_ptr = 0x10000000;
    void* ans = (void*)ALIGN32(alloc_ptr + 64);
    alloc_ptr = ALIGN32(alloc_ptr + size + 128);
    qprintf(" => %x\n", ans);
    return ans;
}
Ejemplo n.º 2
0
int NandTitle::LoadFileFromNand(const char *filepath, u8 **outbuffer, u32 *outfilesize)
{
	if(!filepath)
		return -1;

	fstats *stats = (fstats *) memalign(32, ALIGN32(sizeof(fstats)));
	if(!stats)
		return IPC_ENOMEM;

	int fd = ISFS_Open(filepath, ISFS_OPEN_READ);
	if(fd < 0)
	{
		free(stats);
		return fd;
	}

	int ret = ISFS_GetFileStats(fd, stats);
	if (ret < 0)
	{
		free(stats);
		ISFS_Close(fd);
		return ret;
	}

	u32 filesize = stats->file_length;

	free(stats);

	u8 *buffer = (u8 *) memalign(32, ALIGN32(filesize));
	if(!buffer)
	{
		ISFS_Close(fd);
		return IPC_ENOMEM;
	}

	ret = ISFS_Read(fd, buffer, filesize);

	ISFS_Close(fd);

	if (ret < 0)
	{
		free(buffer);
		return ret;
	}

	*outbuffer = buffer;
	*outfilesize = filesize;

	return 0;
}
Ejemplo n.º 3
0
int Playlog_Delete(void)
{
	s32 res = -1;

	//Open play_rec.dat
	s32 fd = IOS_Open(PLAYRECPATH, IPC_OPEN_RW);
	if(fd < 0)
		return fd;

	PlayRec * playrec_buf = memalign(32, ALIGN32(sizeof(PlayRec)));
	if(!playrec_buf)
		goto cleanup;

	//Read play_rec.dat
	if(IOS_Read(fd, playrec_buf, sizeof(PlayRec)) != sizeof(PlayRec))
		goto cleanup;

	if(IOS_Seek(fd, 0, 0) < 0)
		goto cleanup;

	// invalidate checksum
	playrec_buf->checksum = 0;

	if(IOS_Write(fd, playrec_buf, sizeof(PlayRec)) != sizeof(PlayRec))
		goto cleanup;

	res = 0;

cleanup:
	free(playrec_buf);
	IOS_Close(fd);
	return res;
}
Ejemplo n.º 4
0
int Playlog_Update(const char * ID, const u16 * title)
{
	if(!ID || !title)
		return -1;

	//If not started from SystemMenu, create playlog
	Playlog_Create();

	s32 fd = -1, res = -1;
	u32 sum = 0;
	u8 i;

	//Open play_rec.dat
	fd = IOS_Open(PLAYRECPATH, IPC_OPEN_RW);
	if(fd == -106)
	{
		//In case the play_rec.dat wasn´t found create one and try again
		int ret = Playlog_Create();
		if(ret < 0)
			return ret;

		fd = IOS_Open(PLAYRECPATH, IPC_OPEN_RW);
	}

	if(fd < 0)
		return res;

	PlayRec * playrec_buf = memalign(32, ALIGN32(sizeof(PlayRec))); //! Should be 32 byte aligned
	if(!playrec_buf)
	{
		IOS_Close(fd);
		return res;
	}

	memset(playrec_buf, 0, sizeof(PlayRec));

	u64 stime = getWiiTime();
	playrec_buf->ticks_boot = stime;
	playrec_buf->ticks_last = stime;

	//Update channel name and ID
	memcpy(playrec_buf->name, title, 84);
	memcpy(playrec_buf->title_id, ID, 6);

	//Calculate and update checksum
	for(i = 0; i < 31; i++)
		sum += playrec_buf->data[i];

	playrec_buf->checksum = sum;

	//Write play_rec.dat
	if(IOS_Write(fd, playrec_buf, sizeof(PlayRec)) == sizeof(PlayRec))
		res = 0;

	IOS_Close(fd);

	free(playrec_buf);

	return res;
}
Ejemplo n.º 5
0
Decode_Status VaapiDecoderVP9::ensureContext(const Vp9FrameHdr* hdr)
{
    // only reset va context when there is a larger frame
    if (m_configBuffer.width < hdr->width
        || m_configBuffer.height <  hdr->height) {
        INFO("frame size changed, reconfig codec. orig size %d x %d, new size: %d x %d",
                m_configBuffer.width, m_configBuffer.height, hdr->width, hdr->height);
        Decode_Status status = VaapiDecoderBase::terminateVA();
        if (status != DECODE_SUCCESS)
            return status;
        m_configBuffer.width = hdr->width;
        m_configBuffer.height = hdr->height;
        m_configBuffer.surfaceWidth = ALIGN8(hdr->width);
        m_configBuffer.surfaceHeight = ALIGN32(hdr->height);
        status = VaapiDecoderBase::start(&m_configBuffer);
        if (status != DECODE_SUCCESS)
            return status;
        return DECODE_FORMAT_CHANGE;
    } else if (m_videoFormatInfo.width != hdr->width
        || m_videoFormatInfo.height != hdr->height) {
        // notify client of resolution change, no need to reset hw context
            INFO("frame size changed, reconfig codec. orig size %d x %d, new size: %d x %d\n", m_videoFormatInfo.width, m_videoFormatInfo.height, hdr->width, hdr->height);
            m_videoFormatInfo.width = hdr->width;
            m_videoFormatInfo.height = hdr->height;
            return DECODE_FORMAT_CHANGE;
    }
    return DECODE_SUCCESS;

}
Ejemplo n.º 6
0
//------------------------------------------------------------------------------
tQueueReturn lfq_entryEnqueue (tQueueInstance pInstance_p,
        UINT8 *pData_p, UINT16 size_p)
{
    tQueue *pQueue = (tQueue*)pInstance_p;
    UINT16 entryPayloadSize;
    tEntryHeader entryHeader;

    if(pQueue == NULL || pData_p == NULL || size_p > QUEUE_MAX_PAYLOAD)
        return kQueueInvalidParameter;

    switch(getHwQueueState(pQueue))
    {
        case kQueueStateOperational:
            break;
        case kQueueStateReset:
            /// queue was reset by consumer, producer reactivates queue
            setHwQueueState(pQueue, kQueueStateOperational);
            break;
        default:
        case kQueueStateInvalid:
            return kQueueHwError;
    }

    if(UNALIGNED32(pData_p))
        return kQueueAlignment;

    getHwQueueBufferHeader(pQueue);

    entryPayloadSize = ALIGN32(size_p);

    if(!checkPayloadFitable(pQueue, entryPayloadSize))
        return kQueueFull;

    /// prepare header
    entryHeader.magic = QUEUE_MAGIC;
    entryHeader.payloadSize = entryPayloadSize;
    memset(entryHeader.aReserved, 0, sizeof(entryHeader.aReserved));

    writeHeader(pQueue, &entryHeader);

    writeData(pQueue, pData_p, entryPayloadSize);

    /// new element is written
    pQueue->local.entryIndices.write += 1;

    /// the new indices are written to hw only if the queue is still operational
    if(getHwQueueState(pQueue) != kQueueStateOperational)
        return kQueueSuccessful;

    setHwQueueWrite(pQueue);

    return kQueueSuccessful;
}
Ejemplo n.º 7
0
int
cpu_coredump32(struct lwp *l, struct coredump_iostate *iocookie,
    struct core32 *chdr)
{
	struct md_core32 md_core;
	struct coreseg cseg;
	int error;

	if (iocookie == NULL) {
		CORE_SETMAGIC(*chdr, COREMAGIC, MID_I386, 0);
		chdr->c_hdrsize = ALIGN32(sizeof(*chdr));
		chdr->c_seghdrsize = ALIGN32(sizeof(cseg));
		chdr->c_cpusize = sizeof(md_core);
		chdr->c_nseg++;
		return 0;
	}

	/* Save integer registers. */
	error = netbsd32_process_read_regs(l, &md_core.intreg);
	if (error)
		return error;

	/* Save floating point registers. */
	error = netbsd32_process_read_fpregs(l, &md_core.freg, NULL);
	if (error)
		return error;

	CORE_SETMAGIC(cseg, CORESEGMAGIC, MID_I386, CORE_CPU);
	cseg.c_addr = 0;
	cseg.c_size = chdr->c_cpusize;

	error = coredump_write(iocookie, UIO_SYSSPACE, &cseg,
	    chdr->c_seghdrsize);
	if (error)
		return error;

	return coredump_write(iocookie, UIO_SYSSPACE, &md_core,
	    sizeof(md_core));
}
Ejemplo n.º 8
0
status_t VideoThread::convertNV12Linear2Tiled(const AtomBuffer &buff)
{
#ifdef GRAPHIC_IS_GEN
    VAStatus ret;
    RenderTarget Src, Dst;
    ANativeWindowBuffer *nativeBuffer = buff.gfxInfo_rec.gfxBuffer->getNativeBuffer();

    if (mVpp == NULL) {
        ALOGE("@%s vpp is not valid", __FUNCTION__);
        return UNKNOWN_ERROR;
    }

    Src.width  = buff.bpl;
    Src.height = buff.height;
    Src.stride = buff.bpl;
    Src.format = VA_RT_FORMAT_YUV420;
    Src.pixel_format = VA_FOURCC_NV12;
    Src.type   = RenderTarget::ANDROID_GRALLOC;
    Src.handle = (int)*buff.gfxInfo.gfxBufferHandle;
    Src.rect.x = Src.rect.y = 0;
    Src.rect.width = buff.width;
    Src.rect.height = buff.height;

    // Specific format information is in graphic handle.
    Dst.width  = nativeBuffer->stride;
    Dst.height = ALIGN32(buff.height);
    Dst.stride = nativeBuffer->stride;
    Dst.format = VA_RT_FORMAT_YUV420;
    Dst.pixel_format = VA_FOURCC_NV12;
    Dst.type   = RenderTarget::ANDROID_GRALLOC;
    Dst.handle = (int)*buff.gfxInfo_rec.gfxBufferHandle;
    Dst.rect.x = Dst.rect.y = 0;
    Dst.rect.width = buff.width;
    Dst.rect.height = buff.height;

    LOG2("@%s Src %dx%d s:%d handle:%x", __FUNCTION__, Src.width, Src.height, Src.stride, Src.handle);
    LOG2("@%s Dst %dx%d s:%d handle:%x", __FUNCTION__, Dst.width, Dst.height, Dst.stride, Dst.handle);

    /**
     * vpp start will be called automatically inside perform
     * perform asynchronously to speed up recording process.
     */
    ret = mVpp->perform(Src, Dst, NULL, true);
    if (ret != VA_STATUS_SUCCESS) {
        ALOGE("@%s error:%x", __FUNCTION__, ret);
        return UNKNOWN_ERROR;
    }
#endif //GRAPHIC_IS_GEN
    return OK;
}
Ejemplo n.º 9
0
unsigned char *dcps_key_data_get (Topic_t          *tp,
			          const void       *data,
				  int              dynamic,
				  int              secure,
				  unsigned char    buf [16],
				  size_t           *size,
				  DDS_ReturnCode_t *ret)
{
	unsigned char		*keys;
	const TypeSupport_t	*ts;

	ts = tp->type->type_support;
	if (!ts->ts_keys) {
		*ret = DDS_RETCODE_PRECONDITION_NOT_MET;
		return (NULL);
	}
	if (!data) {
		*ret = DDS_RETCODE_BAD_PARAMETER;
		return (NULL);
	}
	*size = ts->ts_mkeysize;
	if (!*size || !ts->ts_fksize) {
		*size = DDS_KeySizeFromNativeData (data, dynamic, ts, ret);
		if (!*size) {
			*ret = DDS_RETCODE_BAD_PARAMETER;
			warn_printf ("key_data_get: DDS_KeySize() returns error!");
			return (NULL);
		}
	}
	if (*size > 16) {
		keys = xmalloc (ALIGN32 (*size));
		if (!keys) {
			*ret = DDS_RETCODE_OUT_OF_RESOURCES;
			warn_printf ("key_data_get: xmalloc() returns NULL!");
			return (NULL);
		}
	}
	else
		keys = buf;
	*ret = DDS_KeyFromNativeData (keys, data, dynamic, secure, ts);
	if (*ret != DDS_RETCODE_OK) {
		if (*size > 16)
			xfree (keys);

		return (NULL);
	}
	*ret = DDS_RETCODE_OK;
	return (keys);
}
Ejemplo n.º 10
0
void BufferCircle::SetBufferBlockSize(int size)
{
	if(size < 0)
		return;

	BufferBlockSize = size;

	for(int i = 0; i < Size(); i++)
	{
		if(SoundBuffer[i] != NULL)
			free(SoundBuffer[i]);

		SoundBuffer[i] = (u8 *) memalign(32, ALIGN32(BufferBlockSize));
		BufferSize[i] = 0;
		BufferReady[i] = false;
	}
}
Ejemplo n.º 11
0
//------------------------------------------------------------------------------
tQueueReturn lfq_entryDequeue (tQueueInstance pInstance_p,
        UINT8 *pData_p, UINT16 *pSize_p)
{
    tQueue *pQueue = (tQueue*)pInstance_p;
    tEntryHeader EntryHeader;
    UINT16 size;

    if(pQueue == NULL || pData_p == NULL)
        return kQueueInvalidParameter;

    /// not operational queues are empty for the consumer
    if(getHwQueueState(pQueue) != kQueueStateOperational)
        return kQueueEmpty;

    if(UNALIGNED32(pData_p))
        return kQueueAlignment;

    getHwQueueBufferHeader(pQueue);

    if(checkQueueEmpty(pQueue))
        return kQueueEmpty;

    readHeader(pQueue, &EntryHeader);

    if(!checkMagicValid(&EntryHeader))
        return kQueueInvalidEntry;

    size = ALIGN32(EntryHeader.payloadSize);

    if(size > *pSize_p)
        return kQueueNoResource;

    readData(pQueue, pData_p, size);

    /// element is read
    pQueue->local.entryIndices.read += 1;

    setHwQueueRead(pQueue);

    /// return entry size
    *pSize_p = size;

    return kQueueSuccessful;
}
Ejemplo n.º 12
0
static void write_pcapng_decrypted(struct wlantest *wt)
{
	size_t len;
	struct pcapng_enhanced_packet *pkt;
	u8 *pos;
	u32 *block_len;

	if (!wt->pcapng || wt->decrypted == NULL)
		return;

	add_note(wt, MSG_EXCESSIVE, "decrypted version of the previous frame");

	len = sizeof(*pkt) + wt->decrypted_len + 100 + notes_len(wt, 32);
	pkt = os_zalloc(len);
	if (pkt == NULL)
		return;

	pkt->block_type = PCAPNG_BLOCK_ENHANCED_PACKET;
	pkt->interface_id = 0;
	pkt->timestamp_high = wt->write_pcapng_time_high;
	pkt->timestamp_low = wt->write_pcapng_time_low;
	pkt->captured_len = wt->decrypted_len;
	pkt->packet_len = wt->decrypted_len;

	pos = (u8 *) (pkt + 1);

	os_memcpy(pos, wt->decrypted, wt->decrypted_len);
	pos += ALIGN32(wt->decrypted_len);

	pos = pcapng_add_comments(wt, pos);

	block_len = (u32 *) pos;
	pos += 4;
	*block_len = pkt->block_total_len = pos - (u8 *) pkt;

	fwrite(pkt, pos - (u8 *) pkt, 1, wt->pcapng);
	if (wt->pcap_no_buffer)
		fflush(wt->pcapng);

	os_free(pkt);
}
Ejemplo n.º 13
0
void BufferCircle::Resize(int size)
{
	while(size < Size())
		RemoveBuffer(Size()-1);

	int oldSize = Size();

	SoundBuffer.resize(size);
	BufferSize.resize(size);
	BufferReady.resize(size);

	for(int i = oldSize; i < Size(); i++)
	{
		if(BufferBlockSize > 0)
			SoundBuffer[i] = (u8 *) memalign(32, ALIGN32(BufferBlockSize));
		else
			SoundBuffer[i] = NULL;
		BufferSize[i] = 0;
		BufferReady[i] = false;
	}
}
Ejemplo n.º 14
0
void GuiImageData::LoadTPL(const u8 *img, int imgSize)
{
    TplImage TplFile(img, imgSize);

    width = TplFile.GetWidth(0);
    height = TplFile.GetHeight(0);
    format = (u8) TplFile.GetFormat(0);

    const u8 * ImgPtr = TplFile.GetTextureBuffer(0);

    if(ImgPtr)
    {
        int len =  ALIGN32(TplFile.GetTextureSize(0));

        data = (u8 *) memalign(32, len);
        if(!data)
            return;

        memcpy(data, ImgPtr, len);
        DCFlushRange(data, len);
    }
}
Ejemplo n.º 15
0
u8 *ISFS_GetFile(u8 *path, u32 *size, s32 length)
{
	*size = 0;
	
	s32 fd = ISFS_Open((const char *) path, ISFS_OPEN_READ);
	u8 *buf = NULL;
	static fstats stats ATTRIBUTE_ALIGN(32);
	
	if (fd >= 0)
	{
		if (ISFS_GetFileStats(fd, &stats) >= 0)
		{
			if (length <= 0) length = stats.file_length;
			if (length > 0)
				buf = (u8 *) MEM2_alloc(ALIGN32(length));

			if (buf)
			{
				*size = stats.file_length;
				if (ISFS_Read(fd, (char*)buf, length) != length)
				{
					*size = 0;
					SAFE_FREE(buf);
				}
			}
		}
		ISFS_Close(fd);
	}

	if (*size > 0)
	{
		DCFlushRange(buf, *size);
		ICInvalidateRange(buf, *size);
	}
	
	return buf;
}
SIGN32 MV_DRMLIB_Load_Customer_Key(UNSG8* pbCustKeyStore, UNSG32 uKeyStoreSize)
{
  FIGODRV_HANDLE  hFigoDrv = NULL;
  UNSG32 i = 0;
  UNSG32 uEncImgSize = MEMPOLL_SIZE;
  SIGN32 nRet = 0;
  UNSG32 uErrCode = 0;
  UNSG32 uCheckSize = 1024;
  UNSG8* pbSrcDDR = NULL;
  UNSG8* pbDstImg = NULL;
  SIE_DRMROM_CMD  drmCmd;
  SIE_DRMROM_CMD  drmRsp;
  T32SECSTATUS_CFG cfgSecStatus;
  void *pDiagDtcm = NULL;
  UNSG32 uReady = 0;
  UNSG32 uRspFlag = 0;
  UNSG32 uCmdFlag = 0;
  UNSG32 uErrorCode = 0;
  UNSG32 uKeyNum = 0;
  UNSG32 uKeyId = 0;
  UNSG32 uSize = 0;
  UNSG8 * pbTemp = NULL;

  get_figo_img(gp_cust_figo_image);
  flush_all_dcache();
  nRet = MV_DRMLIB_PreProcess_Customer_KeyStore(pbCustKeyStore, uKeyStoreSize, &uKeyNum);
  if(0 != nRet) {
    lgpl_printf("Warning: Failed to preprocess keystore \n");
    return -1;
  }
  pbCustKeyStore = pbCustKeyStore + 8;    //Skip the key store header: 16 bytes
  uKeyStoreSize  = uKeyStoreSize - 8;

  //!Wait FIGO Ready
  Wait_FIGO();
  //!Prepare the Image
  {
    UNSG8* pbAlloc = NULL;
    UNSG32  uVSize = MEMPOLL_SIZE;
    unsigned int i = 0;
    pbAlloc = (UNSG8*)mempool;
    pbSrcDDR = (UNSG8*)(ALIGN32(pbAlloc) + 32);
    pbTemp = pbSrcDDR;
    for (i = 0; i< uVSize - 64; i = i + 4)
    {
      pbTemp = pbSrcDDR + i;
      *(UNSG32 *)(pbTemp) = 0;
    }
  }
  pbDstImg = pbSrcDDR;
  {
    unsigned int i = 0;
    for (i = 0; i < CUSTK_IMAGE_MAX_SIZE; i++)
      *(pbDstImg + i) = *((UNSG8*)gp_cust_figo_image + i);

  }
  //! Init DTCM
  {
    int i = 0;
    void* pDiagDtcm = NULL;
    UNSG32 uSize = 0;
    pDiagDtcm = (void *)(ALIGN32(dtcmpool) + 32);
    for(i = 0 ; i< (9688/4); i = i+1 )
      *(((UNSG32*)pDiagDtcm) + i) = 0;

    uSize = 9688 - RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag;
    //lgpl_printf("Before Init the DTCM, the Size = [0x%x]\n", uSize);
    for ( i = 0; i < uSize/4; i +=1 )
    {
      MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag + i*4, 0);
    }
  }
  flush_all_dcache();
  //Load FIGO Image
  {
    int i = 0;
    for (i = 0; i < sizeof(drmCmd)/8; i = i + 8)
      *((UNSG64 *)&drmCmd + i) = 0;
    cfgSecStatus.u32 = MV_FIGODRV_IO_RD32(DRMFIGOREG_SECSTAT);
    if ( cfgSecStatus.uCFG_flag  != SECSTATUS_CFG_flag_ENABLED )
    {
      return MV_FIGODRV_ERR_INVLAID_ARG;
    }
    //! Check figo command status
    drmCmd.u32DRMROM_CMD_STAT = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_STAT);
    if ( drmCmd.uSTAT_en )
    {
      return MV_FIGODRV_ERR_INVLAID_STATUS;
    }

    drmCmd.uCMD_CFG_tag     = DRMROM_CMD_TYPE_LD_FIGOIMG;
    drmCmd.uCMD_CFG_nonce   = (UNSG32)0xffffffff;

    drmCmd.uCMD_DAT0_crcCmd32   = 0;
    drmCmd.uCMD_DAT1_imgSz      = 0;
    drmCmd.uCMD_DAT2_imgSrcAddr = (UNSG32)pbDstImg;
    drmCmd.uSTAT_en = 1;
    //! Issue command
    MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_CFG,  drmCmd.u32DRMROM_CMD_CMD_CFG);
    MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_DAT0, drmCmd.u32DRMROM_CMD_CMD_DAT0);
    MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_DAT1, drmCmd.u32DRMROM_CMD_CMD_DAT1);
    MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_DAT2, drmCmd.u32DRMROM_CMD_CMD_DAT2);
    MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_DAT3, drmCmd.u32DRMROM_CMD_CMD_DAT3);

    MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_STAT,     drmCmd.u32DRMROM_CMD_STAT);
    //! Check figo command status
    while(1)
    {
      drmRsp.u32DRMROM_CMD_STAT = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_STAT);
      if ( drmRsp.uSTAT_en )
      {
        continue;
      }
      break;
    }
    //! Load Reponse
    drmRsp.u32DRMROM_CMD_RSP_CFG = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_RSP_CFG);
    drmRsp.u32DRMROM_CMD_RSP_DAT0 = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_RSP_DAT0);
    drmRsp.u32DRMROM_CMD_RSP_DAT1 = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_RSP_DAT1);

    if ( drmRsp.uRSP_CFG_tag != DRMROM_CMD_TYPE_LD_FIGOIMG)
    {
      return MV_FIGODRV_ERR;
    }
    //!Todo verify crc32 value with nonce
    uErrorCode = drmRsp.uRSP_DAT1_error;
    if (0 != uErrorCode)
      return MV_FIGODRV_ERR;

  }
  flush_all_dcache();
  // Load the customer keystore into DTCM
  {
    UNSG32 uAESKeyCnt = 0;
    UNSG32 uRSAPubKeyCnt = 0;
    UNSG32 uRSAPrvKeyCnt = 0;
    UNSG32 j = 0;
    for(i =0; i< uKeyNum; i++)
    {
      uKeyId = *(UNSG32*)pbCustKeyStore;      //! First Word is Key ID
      uSize = *((UNSG32*)(pbCustKeyStore + 4));   //! Second word is size
      //printf("%s, %d, key id == 0x%x\n", __FUNCTION__, __LINE__, uKeyId);
      if((uKeyId == 0x80 || uKeyId == 0x81)&& uSize == 0x90)
      {
        uAESKeyCnt++;
#if 0
        pbCustKeyStore = pbCustKeyStore + 8 + uSize;
        continue;
#endif
        lgpl_printf("Load No.%d AES Key into User Key DTCM Area\n", uAESKeyCnt);
      }
      else if(uKeyId == 0x82&& uSize == 0x140)
      {
        uRSAPubKeyCnt++;
        lgpl_printf("Load No.%d RSA Public Key into User Key DTCM Area\n", uRSAPubKeyCnt);
      }
      else if(uKeyId == 0x8e && uSize == 0x180)
      {
        uRSAPrvKeyCnt++;
        lgpl_printf("Load No.%d RSA Private Key into User Key DTCM Area\n", uRSAPrvKeyCnt);
      }
      else
      {
        lgpl_printf("Warning: Invalid key store!Key Id is:0x%x, keystore size is: 0x%x\n", uKeyId, uSize);
        uErrorCode = 0xff;
        break;
      }

      pbCustKeyStore = pbCustKeyStore + 8;
      for(j = 0; j < uSize/4; j++)
      {
        MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_custKeystore + j*4,  *(UNSG32*)(pbCustKeyStore + j*4));
      }
      lgpl_printf("Loading Secure Customer Key Store is finished\n");

      do{
        uRspFlag = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_rspFlag);
        uRspFlag = uRspFlag & 0xffff;
        MV_FIGODRV_SLEEP(1000);
      } while (uRspFlag != 0x3010);
      // Send Command to FIOG image
      {
        MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_uKeyId, uKeyId);
        uCmdFlag = 0xa5;
        MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag, uCmdFlag);
      }

      // Wait the Command is executed
      do{
        uCmdFlag = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag);
        uCmdFlag = uCmdFlag & 0xff;
        MV_FIGODRV_SLEEP(1000);
      } while (uCmdFlag != 0x30);
      uErrorCode = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + BA_DRMDiag_CUSTOMER_KEYSTORE_CTX_uErrorCode);
      uErrorCode = uErrorCode&0xff;
      MV_DRMLIB_Check_ReturnError(uErrorCode);

      if(uErrorCode != 0)
      {
        break;
      }
      //lgpl_printf("******* Load Customer Key store successfully*********\n");
      pbCustKeyStore = pbCustKeyStore + uSize;
    }
  }
  uCmdFlag = 0x5a;
  MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag, uCmdFlag);

  do{
    uRspFlag = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_rspFlag);
    uRspFlag = uRspFlag & 0xffff;
    MV_FIGODRV_SLEEP(1000);
  } while (uRspFlag != 0x88de);

  //  uCmdFlag = 0xf3;
  //  MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag, uCmdFlag);
  lgpl_printf("Finish to load Customer Key store\n");
  uErrorCode = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + BA_DRMDiag_CUSTOMER_KEYSTORE_CTX_uErrorCode);
  uErrorCode = uErrorCode&0xff;

  MV_DRMLIB_Check_ReturnError(uErrorCode);

  if(uErrorCode != 0)
  {
    lgpl_printf("uErrorCode = 0x%x\n", uErrorCode);
    //return -1;
  }

  uCmdFlag = 0xde;
  MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag, uCmdFlag);
  // Wait Figo ROM code ready
  Wait_FIGO();
  lgpl_printf("FIGO is running at FIGO ROM Code agian\n");

  if(uErrorCode != 0)
  {
    return -1;
  }

  return MV_FIGODRV_OK;
}
Ejemplo n.º 17
0
s8 LoadHacks_Hash( bool Force_Load_Nand )
{	
	if( hacks_hash.size() ) //hacks_hash already loaded
	{
		hacks_hash.clear();
		if(states_hash)
		{
			mem_free(states_hash);
		}
	}
	if(foff != 0)
		foff=0;
	bool mode = true;
	s32 fd=0;
	char *buf=NULL;
	STACK_ALIGN(fstats,status,sizeof(fstats),32);
	unsigned int size=0;
	FILE* in = NULL;
	if(!Force_Load_Nand)
	{
		in = fopen ("fat:/apps/priiloader/hacks_hash.ini","rb");
		if(!in)
			gprintf("fopen error : strerror %s\n",strerror(errno));

	}
	if( !in )
	{
		fd = ISFS_Open("/title/00000001/00000002/data/hackshas.ini", 1 );
		if( fd < 0 )
		{
			gprintf("LoadHacks : hacks_hash.ini not on FAT or Nand. ISFS_Open error %d\n",fd);
			return 0;
		} 
		mode = false;
	}
	if( mode )	//read file from FAT
	{
		//read whole file in
		fseek( in, 0, SEEK_END );
		size = ftell(in);
		fseek( in, 0, 0);

		if( size == 0 )
		{
			PrintFormat( 1, ((640/2)-((strlen("Error \"hacks_hash.ini\" is 0 byte!"))*13/2))>>1, 208, "Error \"hacks_hash.ini\" is 0 byte!");
			sleep(5);
			return 0;
		}

		buf = (char*)mem_align( 32, ALIGN32(size));
		if( buf == NULL )
		{
			error = ERROR_MALLOC;
			return 0;
		}
		memset( buf, 0, size );
		if(fread( buf, sizeof( char ), size, in ) != size )
		{
			mem_free(buf);
			PrintFormat( 1, ((640/2)-((strlen("Error reading \"hacks_hash.ini\""))*13/2))>>1, 208, "Error reading \"hacks_hash.ini\"");
			sleep(5);
			return 0;
		}
Ejemplo n.º 18
0
int NandTitle::ExtractFile(const char *nandPath, const char *filepath)
{
	if(!nandPath || !filepath)
		return -1;

	char *strDup = strdup(filepath);
	if(!strDup)
		return -666;

	char *ptr = strrchr(strDup, '/');
	if(!ptr)
	{
		free(strDup);
		return -333;
	}
	else
	{
		*ptr = 0;
		CreateSubfolder(strDup);
		free(strDup);
	}

	int done = 0;
	int fd = -1;
	int blocksize = 32*1024;
	u8 *buffer = (u8 *) memalign(32, ALIGN32(blocksize));
	if(!buffer)
		return -666;

	fstats *stats = (fstats *) memalign(32, ALIGN32(sizeof(fstats)));
	if(!stats)
	{
		free(buffer);
		return -666;
	}

	do
	{
		fd = ISFS_Open(nandPath, ISFS_OPEN_READ);
		if(fd < 0)
			break;

		int ret = ISFS_GetFileStats(fd, stats);
		if (ret < 0)
			break;

		int filesize = stats->file_length;

		FILE *pFile = fopen(filepath, "wb");
		if(!pFile)
			break;

		while(done < filesize)
		{
			if(filesize-done < blocksize)
				blocksize = filesize-done;

			ret = ISFS_Read(fd, buffer, blocksize);
			if(ret < 0)
			{
				done = ret;
				break;
			}

			fwrite(buffer, 1, ret, pFile);

			done += ret;
		}

		fclose(pFile);

	} while(0);

	free(buffer);
	free(stats);

	if(fd >= 0)
		ISFS_Close(fd);

	return done;

}
Ejemplo n.º 19
0
int NandTitle::InternalExtractDir(char *nandPath, std::string &filepath)
{
	int ret = -1;

	u32 list_len = 0;
	ret = ISFS_ReadDir(nandPath, NULL, &list_len);
	if(ret < 0)
		return ret;

	char * name_list = (char *) memalign(32, ALIGN32(list_len * ISFS_MAXPATH));
	if(!name_list)
		return -666;

	ret = ISFS_ReadDir(nandPath, name_list, &list_len);
	if(ret < 0)
	{
		free(name_list);
		return ret;
	}

	char *entry = name_list;

	for(u32 i = 0; i < list_len; ++i)
	{
		u32 dummy;
		int posNandPath = strlen(nandPath);
		int posFilePath = filepath.size();

		if(posFilePath > 0 && filepath[posFilePath-1] != '/')
			filepath += '/';
		filepath += entry;

		if(posNandPath > 0 && nandPath[posNandPath-1] != '/')
			strcat(nandPath, "/");
		strcat(nandPath, entry);

		if(ISFS_ReadDir(nandPath, NULL, &dummy) < 0)
		{
			std::string filepathCpy = filepath;
			ConvertInvalidCharacters(filepathCpy);

			int res = ExtractFile(nandPath, filepathCpy.c_str());
			if(res < 0) {
				gprintf("ExtractFile: Error %i occured on file extract: %s\n", res, nandPath);
				ret = -2;
			}
		}
		else
		{
			int res = InternalExtractDir(nandPath, filepath);
			if(res < 0) {
				gprintf("InternalExtractDir: Error %i occured in: %s\n", res, nandPath);
				ret = -3;
			}
		}

		nandPath[posNandPath] = 0;
		filepath.erase(posFilePath);
		entry += strlen(entry) + 1;
	}

	free(name_list);

	return ret;
}
Ejemplo n.º 20
0
s8 WritePriiloader( bool priiloader_found )
{
    s32 ret = 0;
    s32 fd = 0;
    Nand_Permissions SysPerm;
    if(priiloader_found == false)
    {
        memset(&SysPerm,0,sizeof(Nand_Permissions));
        SysPerm.otherperm = 3;
        SysPerm.groupperm = 3;
        SysPerm.ownerperm = 3;
        //system menu coping
        printf("Moving System Menu app...");
        ret = nand_copy(original_app,copy_app,SysPerm);
        if (ret < 0)
        {
            if (ret == -80)
            {
                //checksum issues
                printf("\x1b[%u;%dm", 33, 1);
                printf("\nWARNING!!\n  Installer could not calculate the Checksum for the System menu app");
                printf("\nbut Copy was successfull.\n");
                printf("Do you want the Continue ?\n");
                printf("A = Yes       B = No\n  ");
                printf("\x1b[%u;%dm", 37, 1);
                if(!UserYesNoStop())
                {
                    printf("reverting changes...\n");
                    ISFS_Delete(copy_app);
                    abort("System Menu Copying Failure");
                }
                else
                    printf("\nDone!\n");
            }
            else
                abort("\nUnable to move the system menu. error %d",ret);
        }
        else
        {
            gprintf("Moving System Menu Done\n");
            printf("Done!\n");
        }
    }
    ret = 0;
    //sys_menu app moved. lets write priiloader
    STACK_ALIGN(fstats,status,sizeof(fstats),32);
    memset(&SysPerm,0,sizeof(Nand_Permissions));
    SysPerm.otherperm = 3;
    SysPerm.groupperm = 3;
    SysPerm.ownerperm = 3;

    printf("Writing Priiloader app...");
    gprintf("Writing Priiloader\n");

    char temp_dest[ISFS_MAXPATH];
    memset(temp_dest,0,ISFS_MAXPATH);
    char *ptemp = NULL;
    ptemp = strstr(original_app,"/");
    while(ptemp != NULL && strstr(ptemp+1,"/") != NULL)
    {
        ptemp = strstr(ptemp+1,"/");
    }
    if(ptemp[0] == '/')
    {
        ptemp = ptemp+1;
    }
    memset(temp_dest,0,ISFS_MAXPATH);
    sprintf(temp_dest,"/tmp/%s",ptemp);
    ISFS_Delete(temp_dest);
    ret = ISFS_CreateFile(temp_dest,SysPerm.attributes,SysPerm.ownerperm,SysPerm.groupperm,SysPerm.otherperm);

    fd = ISFS_Open(temp_dest,ISFS_OPEN_RW);
    if (fd < 0)
    {
        gprintf("error %d\n",fd);
        abort("\nFailed to open file for Priiloader writing");
    }
    ret = ISFS_Write(fd,priiloader_app,priiloader_app_size);
    if (ret < 0 ) //check if the app was writen correctly
    {
        ISFS_Close(fd);
        ISFS_Delete(copy_app);
        ISFS_Delete(temp_dest);
        gprintf("Write failed. ret %d\n",ret);
        abort("\nWrite of Priiloader app failed");
    }
    ISFS_Close(fd);

    //SHA1 check here
    fd = ISFS_Open(temp_dest,ISFS_OPEN_READ);
    if (fd < 0)
    {
        ISFS_Delete(copy_app);
        abort("\nFailed to open file for Priiloader checking");
    }
    if (ISFS_GetFileStats(fd,status) < 0)
    {
        ISFS_Close(fd);
        ISFS_Delete(copy_app);
        abort("Failed to get stats of %s. System Menu Recovered",temp_dest);
    }
    else
    {
        if ( status->file_length != priiloader_app_size )
        {
            ISFS_Close(fd);
            ISFS_Delete(copy_app);
            abort("Written Priiloader app isn't the correct size.System Menu Recovered");
        }
        else
        {
            gprintf("Size Check Success\n");
            printf("Size Check Success!\n");
        }
    }
    u8 *AppData = (u8 *)memalign(32,ALIGN32(status->file_length));
    if (AppData)
        ret = ISFS_Read(fd,AppData,status->file_length);
    else
    {
        ISFS_Close(fd);
        ISFS_Delete(copy_app);
        abort("Checksum comparison Failure! MemAlign Failure of AppData\n");
    }
    ISFS_Close(fd);
    if (ret < 0)
    {
        if (AppData)
        {
            free(AppData);
            AppData = NULL;
        }
        ISFS_Delete(copy_app);
        abort("Checksum comparison Failure! read of priiloader app returned %u\n",ret);
    }
    if(CompareSha1Hash((u8*)priiloader_app,priiloader_app_size,AppData,status->file_length))
        printf("Checksum comparison Success!\n");
    else
    {
        if (AppData)
        {
            free(AppData);
            AppData = NULL;
        }
        ISFS_Delete(copy_app);
        abort("Checksum comparison Failure!\n");
    }
    if (AppData)
    {
        free(AppData);
        AppData = NULL;
    }
    // rename and do a final SHA1 chezck
    ISFS_Delete(original_app);
    ret = ISFS_Rename(temp_dest,original_app);
    if(ret < 0 )
    {
        gprintf("WritePriiloader : rename returned %d\n",ret);
        nand_copy(copy_app,original_app,SysPerm);
        ISFS_Delete(copy_app);
        abort("\nFailed to Write Priiloader : error Ren %d",ret);
    }
    printf("Done!!\n");
    gprintf("Wrote Priiloader App.Checking Installation\n");
    printf("\nChecking Priiloader Installation...\n");
    memset(status,0,sizeof(fstats));
    fd = ISFS_Open(original_app,ISFS_OPEN_READ);
    if (fd < 0)
    {
        nand_copy(copy_app,original_app,SysPerm);
        ISFS_Delete(copy_app);
        abort("\nFailed to open file for Priiloader checking");
    }
    if (ISFS_GetFileStats(fd,status) < 0)
    {
        ISFS_Close(fd);
        nand_copy(copy_app,original_app,SysPerm);
        abort("Failed to get stats of %s. System Menu Recovered",original_app);
    }
    else
    {
        if ( status->file_length != priiloader_app_size )
        {
            ISFS_Close(fd);
            nand_copy(copy_app,original_app,SysPerm);
            ISFS_Delete(copy_app);
            abort("Written Priiloader app isn't the correct size.System Menu Recovered");
        }
        else
        {
            gprintf("Size Check Success\n");
            printf("Size Check Success!\n");
        }
    }
    AppData = (u8 *)memalign(32,ALIGN32(status->file_length));
    if (AppData != NULL)
        ret = ISFS_Read(fd,AppData,status->file_length);
    else
    {
        ISFS_Close(fd);
        nand_copy(copy_app,original_app,SysPerm);
        ISFS_Delete(copy_app);
        abort("Checksum comparison Failure! MemAlign Failure of AppData\n");
    }
    ISFS_Close(fd);
    if (ret < 0)
    {
        if (AppData)
        {
            free(AppData);
            AppData = NULL;
        }
        nand_copy(copy_app,original_app,SysPerm);
        ISFS_Delete(copy_app);
        abort("Checksum comparison Failure! read of priiloader app returned %u\n",ret);
    }
    if(CompareSha1Hash((u8*)priiloader_app,priiloader_app_size,AppData,status->file_length))
        printf("Checksum comparison Success!\n");
    else
    {
        if (AppData)
        {
            free(AppData);
            AppData = NULL;
        }
        nand_copy(copy_app,original_app,SysPerm);
        ISFS_Delete(copy_app);
        abort("Checksum comparison Failure!\n");
    }
    if (AppData)
    {
        free(AppData);
        AppData = NULL;
    }
    gprintf("Priiloader Update Complete\n");
    printf("Done!\n\n");
    return 1;
}
Ejemplo n.º 21
0
/*
 *  ======== RMP_create ========
 */
RMP_Handle RMP_create(RMP_Attrs *attrs)
{
    RMP_Obj         *handle = NULL;
    Int             shmId = -1;
    unsigned int    shmSize = 0;
    Void            * addr = NULL;
    RMM_Attrs       rmmAttrs;
    static Int shmCount = 0;

    /* Create a shared memory object RMP_Obj using the key and the lock
    Size of this will depend numResources and RMM_Obj etc  */

    Assert_isTrue(shmCount < RMMP_MAXINSTANCES, (Assert_Id)NULL);

    shmSize = sizeof(RMP_Obj) + sizeof(RMM_Obj) + sizeof(UInt32);
    shmSize = ALIGN32(shmSize);
    shmSize += (attrs->maxFreeListBlocks * sizeof(RMM_Header));
    shmSize = ALIGN32(shmSize);

#ifdef xdc_target__os_Linux
    addr = SHM_getObj((GateProcess_Handle_upCast)(attrs->gate), shmSize,
            (key_t)attrs->key, (SHM_InitFxn)&setInternalState, &shmId);
#else
    addr = (void *)malloc(shmSize);
    if (NULL != addr) {
        setInternalState(addr);
        shmId = 0;
    }
#endif

    if (shmId != -1) {
        handle = (RMP_Obj *)addr;

        if (0 == handle->refCount) {
            /* RMM_create has to happen */
            rmmAttrs.segid = shmCount;          /* Use shmCount as segId */
            rmmAttrs.base = attrs->base;
            rmmAttrs.length = attrs->length;
            rmmAttrs.maxFreeListBlocks = attrs->maxFreeListBlocks;
            /* My alloc fxn will use the sharedMem address to increment an
               offset pointer */

            rmmAttrs.allocFxn = shmAlloc;
            rmmAttrs.freeFxn = shmFree;

            /* Store the shmCount in the  SHM_Obj part of the handle */
            handle->shmCount = shmCount;
            shmCount++;
        }

        /* Successful acquisition of shared Mem object, so store in array
           for use by allocFxn */
        shmAddrs[handle->shmCount] = (unsigned int)addr;
        shmIndex[handle->shmCount] = sizeof(RMP_Obj); /* Change this to work for
                the allocFxn */

        if (handle->refCount == 0) {
            /* Whatever the RMM_create returns, store that as an offset from
               shmBase */
            handle->rmmOffset = OFFSET(handle, RMM_create(&rmmAttrs));
        }
        handle->refCount++;

        /* Store the sharedMemId in the RMP_Obj */
        handle->sharedMemId = shmId;
    }

    return (handle);
}
Ejemplo n.º 22
0
u8 *U8Archive::DecompressCopy( const u8 * stuff, u32 len, u32 *size ) const
{
	// check for IMD5 header and skip it
	if( len > 0x40 && *(u32*)stuff == 0x494d4435 )// IMD5
	{
		stuff += 0x20;
		len -= 0x20;
	}

	u8* ret = NULL;
	// determine if it needs to be decompressed
	if( IsAshCompressed( stuff, len ) )
	{
		//u32 len2 = len;
		// ASH0
		ret = DecompressAsh( stuff, len );
		if( !ret )
		{
			gprintf( "out of memory\n" );
			return NULL;
		}
	}
	else if( (len > 8) && *(u32*)( stuff ) == 0x59617a30 )// Yaz0
	{
		// Yaz0 with a magic word
		Yaz0_Header *header = (Yaz0_Header *) stuff;
		// set decompress length
		len = header->decompressed_size;
		// allocate memory
		ret = (u8*) memalign(32, ALIGN32(len));
		if(!ret)
		{
			gprintf("out of memory\n");
			return NULL;
		}
		// function can not fail at this point
		uncompressYaz0(stuff, ret, len);
	}
	else if( isLZ77compressed( stuff ) )
	{
		// LZ77 with no magic word
		if( decompressLZ77content( stuff, len, &ret, &len ) )
		{
			return NULL;
		}
	}
	else if( *(u32*)( stuff ) == 0x4C5A3737 )// LZ77
	{
		// LZ77 with a magic word
		if( decompressLZ77content( stuff + 4, len - 4, &ret, &len ) )
		{
			return NULL;
		}
	}
	else
	{
		// just copy the data out of the archive
		ret = (u8*)memalign( 32, ALIGN32( len ) );
		if( !ret )
		{
			gprintf( "out of memory\n" );
			return NULL;
		}
		memcpy( ret, stuff, len );
	}
	if( size )
	{
		*size = len;
	}

	// flush the cache so if there are any textures in this data, it will be ready for the GX
	DCFlushRange( ret, len );
	return ret;
}
Ejemplo n.º 23
0
s8 GetTitleName(u64 id, u32 app, char* name,u8* _dst_uncode_name) {
	s32 r;
    int lang = 1; //CONF_GetLanguage();
    /*
    languages:
    enum {
	CONF_LANG_JAPANESE = 0,
	CONF_LANG_ENGLISH,
	CONF_LANG_GERMAN,
	CONF_LANG_FRENCH,
	CONF_LANG_SPANISH,
	CONF_LANG_ITALIAN,
	CONF_LANG_DUTCH,
	CONF_LANG_SIMP_CHINESE,
	CONF_LANG_TRAD_CHINESE,
	CONF_LANG_KOREAN
	};
	cause we dont support unicode stuff in font.cpp we will force to use english then(1)
    */
	u8 return_unicode_name = 0;
	if(_dst_uncode_name == NULL)
	{
		return_unicode_name = 0;
	}
	else
	{
		return_unicode_name = 1;
	}
    char file[256] ATTRIBUTE_ALIGN(32);
	memset(file,0,256);
    sprintf(file, "/title/%08x/%08x/content/%08x.app", (u32)(id >> 32), (u32)(id & 0xFFFFFFFF), app);
	gdprintf("GetTitleName : %s\n",file);
	u32 cnt ATTRIBUTE_ALIGN(32);
	cnt = 0;
	IMET *data = (IMET *)mem_align(32, ALIGN32( sizeof(IMET) ) );
	if(data == NULL)
	{
		gprintf("GetTitleName : IMET header align failure\n");
		return -1;
	}
	memset(data,0,sizeof(IMET) );
	r = ES_GetNumTicketViews(id, &cnt);
	if(r < 0)
	{
		gprintf("GetTitleName : GetNumTicketViews error %d!\n",r);
		mem_free(data);
		return -1;
	}
	tikview *views = (tikview *)mem_align( 32, sizeof(tikview)*cnt );
	if(views == NULL)
	{
		mem_free(data);
		return -2;
	}
	r = ES_GetTicketViews(id, views, cnt);
	if (r < 0)
	{
		gprintf("GetTitleName : GetTicketViews error %d \n",r);
		mem_free(data);
		mem_free(views);
		return -3;
	}

	//lets get this party started with the right way to call ES_OpenTitleContent. and not like how libogc < 1.8.3 does it. patch was passed on , and is done correctly in 1.8.3
	//the right way is ES_OpenTitleContent(u64 TitleID,tikview* views,u16 Index); note the views >_>
	s32 fh = ES_OpenTitleContent(id, views, 0);
	if (fh == -106)
	{
		CheckTitleOnSD(id);
		mem_free(data);
		mem_free(views);
		return -106;
	}
	else if(fh < 0)
	{
		//ES method failed. remove tikviews from memory and fall back on ISFS method
		gprintf("GetTitleName : ES_OpenTitleContent error %d\n",fh);
		mem_free(views);
		fh = ISFS_Open(file, ISFS_OPEN_READ);
		// f**k failed. lets check SD & GTFO
		if (fh == -106)
		{
			CheckTitleOnSD(id);
			return -106;
		}
		else if (fh < 0)
		{
			mem_free(data);
			gprintf("open %s error %d\n",file,fh);
			return -5;
		}
		// read the completed IMET header
		r = ISFS_Read(fh, data, sizeof(IMET));
		if (r < 0) {
			gprintf("IMET read error %d\n",r);
			ISFS_Close(fh);
			mem_free(data);
			return -6;
		}
		ISFS_Close(fh);
	}
	else
	{
		//ES method
		r = ES_ReadContent(fh,(u8*)data,sizeof(IMET));
		if (r < 0) {
			gprintf("GetTitleName : ES_ReadContent error %d\n",r);
			ES_CloseContent(fh);
			mem_free(data);
			mem_free(views);
			return -8;
		}
		//free data and let it point to IMET_data so everything else can work just fine
		ES_CloseContent(fh);
		mem_free(views);
	}
	char str[10][84];
	char str_unprocessed[10][84];
	//clear any memory that is in the place of the array cause we dont want any confusion here
	memset(str,0,10*84);
	if(return_unicode_name)
		memset(str_unprocessed,0,10*84);
	if(data->imet == 0x494d4554) // check if its a valid imet header
	{
		for(u8 y =0;y <= 9;y++)
		{
			u8 p = 0;
			u8 up = 0;
			for(u8 j=0;j<83;j++)
			{
				if(data->names[y][j] < 0x20)
					if(return_unicode_name && data->names[y][j] == 0x00)
						str_unprocessed[y][up++] = data->names[y][j];
					else
						continue;
				else if(data->names[y][j] > 0x7E)
					continue;
				else
				{
					str[y][p++] = data->names[y][j];
					str_unprocessed[y][up++] = data->names[y][j];
				}
			}
			str[y][83] = '\0';

		}
		mem_free(data);
	}
	else
	{
		gprintf("invalid IMET header for 0x%08x/0x%08x\n", (u32)(id >> 32), (u32)(id & 0xFFFFFFFF));
		return -9;
	}
	if(str[lang][0] != '\0')
	{
		gdprintf("GetTitleName : title %s\n",str[lang]);
		snprintf(name,255, "%s", str[lang]);
		if (return_unicode_name && str_unprocessed[lang][1] != '\0')
		{
			memcpy(_dst_uncode_name,&str_unprocessed[lang][0],83);
		}
		else if(return_unicode_name)
			gprintf("WARNING : empty unprocessed string\n");
	}
	else
		gprintf("GetTitleName: no name found\n");
	memset(str,0,10*84);
	memset(str_unprocessed,0,10*84);
	return 1;
}
Ejemplo n.º 24
0
s32 nand_copy(const char *destination,u8* Buf_To_Write_to_Copy, u32 buf_size,Nand_Permissions src_perm)
{
    if( Buf_To_Write_to_Copy == NULL || buf_size < 1 )
    {
        return -1;
    }
    s32 ret, dest_handler;
    gprintf("owner %d group %d attributes %X perm:%X-%X-%X\n", src_perm.owner, (u32)src_perm.group, (u32)src_perm.attributes, (u32)src_perm.ownerperm, (u32)src_perm.groupperm, (u32)src_perm.otherperm);

    //extract filename from destination
    char temp_dest[ISFS_MAXPATH];
    memset(temp_dest,0,ISFS_MAXPATH);
    char *ptemp = NULL;
    ptemp = strstr(destination,"/");
    while(ptemp != NULL && strstr(ptemp+1,"/") != NULL)
    {
        ptemp = strstr(ptemp+1,"/");
    }
    if(ptemp[0] == '/')
    {
        ptemp = ptemp+1;
    }

    //create temp path
    memset(temp_dest,0,ISFS_MAXPATH);
    sprintf(temp_dest,"/tmp/%s",ptemp);
    ISFS_Delete(temp_dest);

    //and go for it
    ret = ISFS_CreateFile(temp_dest,src_perm.attributes,src_perm.ownerperm,src_perm.groupperm,src_perm.otherperm);
    if (ret != ISFS_OK)
    {
        printf("Failed to create file %s. ret = %d\n",temp_dest,ret);
        gprintf("Failed to create file %s. ret = %d\n",temp_dest,ret);
        return ret;
    }
    dest_handler = ISFS_Open(temp_dest,ISFS_OPEN_RW);
    if (dest_handler < 0)
    {
        gprintf("failed to open destination : %s\n",temp_dest);
        ISFS_Delete(temp_dest);
        return dest_handler;
    }

    ret = ISFS_Write(dest_handler,Buf_To_Write_to_Copy,buf_size);
    if (ret < 0)
    {
        gprintf("failed to write destination : %s\n",temp_dest);
        ISFS_Close(dest_handler);
        ISFS_Delete(temp_dest);
        return ret;
    }
    ISFS_Close(dest_handler);
    s32 temp = 0;
    u8 *Data2 = NULL;
    STACK_ALIGN(fstats,D2stat,sizeof(fstats),32);
    /*if (D2stat == NULL)
    {
    	temp = -1;
    	goto free_and_Return;
    }*/
    dest_handler = ISFS_Open(temp_dest,ISFS_OPEN_RW);
    if(dest_handler < 0)
    {
        gprintf("temp_dest open error %d\n",dest_handler);
        temp = -2;
        goto free_and_Return;
    }
    temp = ISFS_GetFileStats(dest_handler,D2stat);
    if(temp < 0)
    {
        goto free_and_Return;
    }
    Data2 = (u8*)memalign(32,ALIGN32(D2stat->file_length));
    if (Data2 == NULL)
    {
        temp = -3;
        goto free_and_Return;
    }
    if( ISFS_Read(dest_handler,Data2,D2stat->file_length) > 0 )
    {
        if( !CompareSha1Hash(Buf_To_Write_to_Copy,buf_size,Data2,D2stat->file_length))
        {
            temp = -4;
            goto free_and_Return;
        }
    }
    else
    {
        temp = -5;
        goto free_and_Return;
    }
    if(Data2)
    {
        free(Data2);
        Data2 = NULL;
    }
    ISFS_Close(dest_handler);
    //so it was written to /tmp correctly. lets call ISFS_Rename and compare AGAIN
    ISFS_Delete(destination);
    ret = ISFS_Rename(temp_dest,destination);
    if(ret < 0 )
    {
        gprintf("nand_copy(buf) : rename returned %d\n",ret);
        temp = -6;
        goto free_and_Return;
    }
free_and_Return:
    if(Data2 != NULL)
    {
        free(Data2);
        Data2 = NULL;
    }
    ISFS_Close(dest_handler);
    if (temp < 0)
    {
        gprintf("temp %d\n",temp);
        //ISFS_Delete(destination);
        return -80;
    }
    return 1;
}
Ejemplo n.º 25
0
s32 nand_copy(const char *source, const char *destination,Nand_Permissions src_perm)
{
    //variables
    u8 *buffer = NULL;
    STACK_ALIGN(fstats,status,sizeof(fstats),32);
    s32 file_handler, ret;
    u32 FileHash_D1[5];
    memset(FileHash_D1,0,5);
    u32 FileHash_D2[5];
    memset(FileHash_D2,0xFF,5); //place different data in D2 so that if something goes wrong later on, the comparison will fail
    SHA1 sha;
    sha.Reset();

    //variables - temp dir & SHA1 check
    char temp_dest[ISFS_MAXPATH];
    memset(temp_dest,0,ISFS_MAXPATH);
    char *ptemp = NULL;
    u8 temp = 0;

    //get temp filename
    ptemp = strstr(destination,"/");
    while(ptemp != NULL && strstr(ptemp+1,"/") != NULL)
    {
        ptemp = strstr(ptemp+1,"/");
    }
    if(ptemp[0] == '/')
    {
        ptemp = ptemp+1;
    }
    memset(temp_dest,0,ISFS_MAXPATH);
    sprintf(temp_dest,"/tmp/%s",ptemp);

    //get data into pointer from original file
    file_handler = ISFS_Open(source,ISFS_OPEN_READ);
    if (file_handler < 0)
    {
        gprintf("failed to open source : %s\n",source);
        return file_handler;
    }

    ret = ISFS_GetFileStats(file_handler,status);
    if (ret < 0)
    {
        printf("\n\nFailed to get information about %s!\n",source);
        sleepx(2);
        ISFS_Close(file_handler);
        return ret;
    }

    buffer = (u8 *)memalign(32,ALIGN32(status->file_length));
    if (buffer == NULL)
    {
        gprintf("buffer failed to align\n");
        sleepx(2);
        ISFS_Close(file_handler);
        return 0;
    }
    memset(buffer,0,status->file_length);
    ret = ISFS_Read(file_handler,buffer,status->file_length);
    if (ret < 0)
    {
        printf("\n\nFailed to Read Data from %s!\n",source);
        sleepx(2);
        ISFS_Close(file_handler);
        free(buffer);
        buffer = NULL;
        return ret;
    }
    ISFS_Close(file_handler);
    //everything read into buffer. generate SHA1 hash of the buffer
    sha.Input(buffer,status->file_length);
    if (!sha.Result(FileHash_D1))
    {
        gprintf("could not compute Hash of D1!\n");
        free(buffer);
        buffer = NULL;
        return -80;
    }
    sha.Reset();
    //done, lets create temp file and write :')

    ISFS_Delete(temp_dest);
    ISFS_CreateFile(temp_dest,src_perm.attributes,src_perm.ownerperm,src_perm.groupperm,src_perm.otherperm);
    //created. opening it...
    file_handler = ISFS_Open(temp_dest,ISFS_OPEN_RW);
    if (file_handler < 0)
    {
        gprintf("failed to open destination : %s\n",temp_dest);
        ISFS_Delete(temp_dest);
        free(buffer);
        buffer = NULL;
        return file_handler;
    }
    ret = ISFS_Write(file_handler,buffer,status->file_length);
    if (ret < 0)
    {
        gprintf("failed to write destination : %s\n",destination);
        ISFS_Close(file_handler);
        ISFS_Delete(temp_dest);
        free(buffer);
        buffer = NULL;
        return ret;
    }
    //write done. reopen file for reading and compare SHA1 hash
    ISFS_Close(file_handler);
    free(buffer);
    buffer = NULL;
    memset(status,0,sizeof(fstats));
    file_handler = ISFS_Open(temp_dest,ISFS_OPEN_READ);
    if(!file_handler)
    {
        temp = -1;
        goto free_and_Return;
    }
    ret = ISFS_GetFileStats(file_handler,status);
    if (ret < 0)
    {
        ISFS_Close(file_handler);
        temp = -2;
        goto free_and_Return;
    }
    buffer = (u8 *)memalign(32,ALIGN32(status->file_length));
    if (buffer == NULL)
    {
        gprintf("buffer failed to align\n");
        ISFS_Close(file_handler);
        temp = -3;
        goto free_and_Return;
    }
    memset(buffer,0,status->file_length);
    if( ISFS_Read(file_handler,buffer,status->file_length) < 0 )
    {
        temp = -4;
        goto free_and_Return;
    }
    ISFS_Close(file_handler);
    sha.Reset();
    sha.Input(buffer,status->file_length);
    free(buffer);
    buffer = NULL;
    if (!sha.Result(FileHash_D2))
    {
        gprintf("could not compute Hash of D2!\n");
        return -80;
    }
    sha.Reset();
    /*gprintf("sha1 original : %x %x %x %x %x\nsha1 written : %x %x %x %x %x\n",
    																	  FileHash_D1[0],FileHash_D1[1],FileHash_D1[2],FileHash_D1[3],FileHash_D1[4],
    																	  FileHash_D2[0],FileHash_D2[1],FileHash_D2[2],FileHash_D2[3],FileHash_D2[4]);*/
    if (!memcmp(FileHash_D1,FileHash_D2,sizeof(FileHash_D1)))
    {
        gprintf("nand_copy : SHA1 hash success\n");
        ISFS_Delete(destination);
        ret = ISFS_Rename(temp_dest,destination);
        gprintf("ISFS_Rename ret %d\n",ret);
        if ( ret < 0)
            temp = -5;
        goto free_and_Return;
    }
    else
    {
        temp = -6;
        goto free_and_Return;
    }
free_and_Return:
    if(buffer)
    {
        free(buffer);
        buffer = NULL;
    }
    if (temp < 0)
    {
        gprintf("nand_copy temp %d fail o.o;\n",temp);
        ISFS_Delete(temp_dest);
        return -80;
    }
    return 1;
}
HRESULT MV_Gen_Random_Server(UINT8* pbOutDat, UINT32*uOutSize )
{
    HRESULT lRes = S_OK;

	UNSG32 i = 0;
	UNSG32 uEncImgSize = MEMPOLL_SIZE;
	SIGN32 nRet = 0;
	UNSG32 uErrCode = 0;
	UNSG32 uCheckSize = 1024;
	UNSG8* pbSrcDDR = NULL;
	UNSG8* pbDstImg = NULL;
	SIE_DRMROM_CMD	drmCmd;
	SIE_DRMROM_CMD	drmRsp;
	T32SECSTATUS_CFG cfgSecStatus;
	SIE_DRMDiag_CUSTOMER_KEYSTORE_CTX *pDiagDtcm = NULL;
	UNSG32 uReady = 0;
	UNSG32 uRspFlag = 0;
	UNSG32 uCmdFlag = 0;
	UNSG32 uErrorCode = 0;
	UNSG32 uKeyNum = 0;
	UNSG32 uKeyId = 0;
	UNSG32 uSize = 0;
	UNSG32 uOut_data = 0;
	UNSG8 * pbTemp = NULL;

        UINT8* pbBufAligned32 = NULL;
        UINT32 uBufSizeAligned32 = (32 + 31)&(~(32-1));

    if((pbOutDat ==NULL) && (uOutSize == NULL) && (*uOutSize == 0))
    {
        lRes = MV_FIGODRV_ERR_INVLAID_ARG;
        printf("invalid lenght of randon number(0)\n");
        return lRes;
    }
    uBufSizeAligned32 = (*uOutSize + 15)&(~(16-1));
	#if 1
	{
		get_figo_img(gp_cust_figo_image);
	}
	#endif
	flush_all_dcache();

	//!Wait FIGO Ready
	Wait_FIGO();
	//!Prepare the Image
	{
		UNSG8* pbAlloc = NULL;
		UNSG32	uVSize = MEMPOLL_SIZE;
		unsigned int i = 0;
		pbAlloc = (UNSG8*)mempool;
		pbSrcDDR = (UNSG8*)(ALIGN32(pbAlloc) + 32);
		pbTemp = pbSrcDDR;
		for (i = 0; i< uVSize - 64; i = i + 4)
		{
			pbTemp = pbSrcDDR + i;
			*(UNSG32 *)(pbTemp) = 0;
		}
	}
	pbDstImg = pbSrcDDR;
	{
		unsigned int i = 0;
		for (i = 0; i < CUSTK_IMAGE_MAX_SIZE; i++)
			*(pbDstImg + i) = *((UNSG8*)gp_cust_figo_image + i);

	}
	//! Init DTCM
	{
		int i = 0;
		SIE_DRMDiag_CUSTOMER_KEYSTORE_CTX* pDiagDtcm = NULL;
		UNSG32 uSize = 0;
		pDiagDtcm = (SIE_DRMDiag_CUSTOMER_KEYSTORE_CTX *)(ALIGN32(dtcmpool) + 32);
		for(i = 0 ; i< sizeof(SIE_DRMDiag_CUSTOMER_KEYSTORE_CTX)/4; i = i+1 )
			*(((UNSG32*)pDiagDtcm) + i) = 0;

		uSize = sizeof(SIE_DRMDiag_CUSTOMER_KEYSTORE_CTX) - RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag;
		//lgpl_printf("Before Init the DTCM, the Size = [0x%x]\n", uSize);
		for ( i = 0; i < uSize/4; i +=1 )
		{
			MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag + i*4, 0);
		}
	}
	flush_all_dcache();
	//Load FIGO Image
	{
		int i = 0;
		for (i = 0; i < sizeof(drmCmd)/8; i = i + 8)
			*((UNSG64 *)&drmCmd + i) = 0;
		cfgSecStatus.u32 = MV_FIGODRV_IO_RD32(DRMFIGOREG_SECSTAT);
		if ( cfgSecStatus.uCFG_flag  != SECSTATUS_CFG_flag_ENABLED )
		{
			return MV_FIGODRV_ERR_INVLAID_ARG;
		}
		//! Check figo command status
		drmCmd.u32DRMROM_CMD_STAT = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_STAT);
		if ( drmCmd.uSTAT_en )
		{
			return MV_FIGODRV_ERR_INVLAID_STATUS;
		}

		drmCmd.uCMD_CFG_tag		= DRMROM_CMD_TYPE_LD_FIGOIMG;
		drmCmd.uCMD_CFG_nonce	= (UNSG32)0xffffffff;

		drmCmd.uCMD_DAT0_crcCmd32	= 0;
		drmCmd.uCMD_DAT1_imgSz		= 0;
		drmCmd.uCMD_DAT2_imgSrcAddr = (UNSG32)pbDstImg;
		drmCmd.uSTAT_en = 1;
		//! Issue command
		MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_CFG,	drmCmd.u32DRMROM_CMD_CMD_CFG);
		MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_DAT0, drmCmd.u32DRMROM_CMD_CMD_DAT0);
		MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_DAT1, drmCmd.u32DRMROM_CMD_CMD_DAT1);
		MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_DAT2, drmCmd.u32DRMROM_CMD_CMD_DAT2);
		MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_CMD_DAT3, drmCmd.u32DRMROM_CMD_CMD_DAT3);

		MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_STAT,		drmCmd.u32DRMROM_CMD_STAT);
		//! Check figo command status
		while(1)
		{
			drmRsp.u32DRMROM_CMD_STAT = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_STAT);
			if ( drmRsp.uSTAT_en )
			{
				continue;
			}
			break;
		}
		//! Load Reponse
		drmRsp.u32DRMROM_CMD_RSP_CFG = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_RSP_CFG);
		drmRsp.u32DRMROM_CMD_RSP_DAT0 = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_RSP_DAT0);
		drmRsp.u32DRMROM_CMD_RSP_DAT1 = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMROM_CMD_RSP_DAT1);

		if ( drmRsp.uRSP_CFG_tag != DRMROM_CMD_TYPE_LD_FIGOIMG)
		{
			return MV_FIGODRV_ERR;
		}
		//!Todo verify crc32 value with nonce
		uErrorCode = drmRsp.uRSP_DAT1_error;
		if (0 != uErrorCode)
			return MV_FIGODRV_ERR;

	}
	flush_all_dcache();
	// Load the customer keystore into DTCM
	{
		UNSG32 uAESKeyCnt = 0;
		UNSG32 uRSAPubKeyCnt = 0;
		UNSG32 uRSAPrvKeyCnt = 0;
		UNSG32 j = 0;
		//for(i =0; i< uKeyNum; i++)
		{
			uKeyId = uBufSizeAligned32;		//! First Word is Key ID

			do{
				uRspFlag = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_rspFlag);
				uRspFlag = uRspFlag & 0xffff;
				MV_FIGODRV_SLEEP(1000);
			} while (uRspFlag != 0x3010);
			// Send Command to FIOG image
			{
				MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_uKeyId, uKeyId);
				uCmdFlag = 0xbf;
				MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag, uCmdFlag);
			}
		}
	}
	do{
		uRspFlag = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_rspFlag);
		uRspFlag = uRspFlag & 0xffff;
		MV_FIGODRV_SLEEP(1000);
	} while (uRspFlag != 0x88de);
	for ( i = 0; i < uBufSizeAligned32/4; i +=1 )
	{
		uOut_data = MV_FIGODRV_IO_RD32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_custKeystore + i*4);
		memcpy(((UINT8 *)pDiagDtcm->ie_custKeystore + i*4), &uOut_data, sizeof(uOut_data));
	}
	memcpy(pbOutDat, pDiagDtcm->ie_custKeystore, *uOutSize);
//	uCmdFlag = 0xf3;
//	MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag, uCmdFlag);

	uCmdFlag = 0xde;
	MV_FIGODRV_IO_WR32(DRMFIGOREG_CMDSTAT + RA_DRMDiag_CUSTOMER_KEYSTORE_CTX_cmdFlag, uCmdFlag);
	// Wait Figo ROM code ready
	Wait_FIGO();

	return MV_FIGODRV_OK;
}
/*
 *  ======== SMGRMP_create ========
 */
SMGRMP_Handle SMGRMP_create(SMGRMP_Attrs *attrs)
{
    SMGRMP_Obj         *handle;
    Int             shmId = -1;
    unsigned int    shmSize = 0;
    Void            * addr;
    SMGR_Attrs       smgrAttrs;

    /* Create a shared memory object SMGRMP_Obj using the key and the lock 
    Size of this will depend numResources and SMGR_Obj etc  */
   
    GT_assert(CURTRACE, shmCount < SMGRMP_MAXINSTANCES); 

    shmSize = sizeof(SMGRMP_Obj) + sizeof(SMGR_Obj) + sizeof(UInt32); 
    shmSize = ALIGN32(shmSize);
    shmSize += (sizeof(SMGR_Counter) * attrs->numResources);
    shmSize = ALIGN32(shmSize);

#ifdef xdc_target__os_Linux
    addr = SHM_getObj(attrs->lock, shmSize, (key_t)attrs->key, 
            (SHM_InitFxn)&setInternalState, &shmId);
#else
    addr = (void *)malloc(shmSize);
    setInternalState(addr);
    shmId = 0;
#endif

    if (shmId != -1) {

       handle = (SMGRMP_Obj *)addr;

        /* This will return a unique object for each key, and the same object
           for different processes */
        if (0 == handle->refCount) {

            /* SMGR_create has to happen */ 
            smgrAttrs.segid = shmCount;          /* Use shmCount as segId */ 
            smgrAttrs.numResources = attrs->numResources;
            smgrAttrs.numScratchGroups = attrs->numScratchGroups;
            smgrAttrs.allocFxn = shmAlloc;
            smgrAttrs.freeFxn = shmFree;

            /* Store the shmCount in the  SHM_Obj part of the handle */
            handle->shmCount = shmCount;
            shmCount++;
            shmTotal++;
        }
        /* Successful acquisition of shared Mem object, so store in array
           for use by alloc/free functions */ 
        shmAddrs[handle->shmCount] = (unsigned int)addr;
        shmIndex[handle->shmCount] = sizeof(SMGRMP_Obj); /* Change this to 
                                                            work for the alloFxn
                                                          */
        if (handle->refCount == 0) {

            /* Whatever the SMGR_create returns, store that as an offset from 
               shmBase */
            handle->smgrOffset = OFFSET(handle, SMGR_create(&smgrAttrs));
        }

        handle->refCount++;
        /* Store the sharedMemId in the SMGRMP_Obj */ 
        handle->sharedMemId = shmId;
        return (handle);
    }
    else {
        return (NULL);
    }
}