コード例 #1
0
ファイル: rtest.cpp プロジェクト: wildparky/ptex
int main(int /*argc*/, char** /*argv*/)
{
    Ptex::String error;
    PtexPtr<PtexCache> c(PtexCache::create());
    c->setSearchPath("foo/bar:.");
    PtexPtr<PtexTexture> r(c->get("test.ptx", error));

    if (!r) {
	std::cerr << error.c_str() << std::endl;
	return 1;
    }
    std::cout << "meshType: " << Ptex::MeshTypeName(r->meshType()) << std::endl;
    std::cout << "dataType: " << Ptex::DataTypeName(r->dataType()) << std::endl;
    std::cout << "numChannels: " << r->numChannels() << std::endl;
    std::cout << "alphaChannel: ";
    if (r->alphaChannel() == -1) std::cout << "(none)" << std::endl;
    else std::cout << r->alphaChannel() << std::endl;
    std::cout << "numFaces: " << r->numFaces() << std::endl;

    PtexMetaData* meta = r->getMetaData();
    std::cout << "numMetaKeys: " << meta->numKeys() << std::endl;
    if (meta->numKeys()) DumpMetaData(meta);
    meta->release();

    int nfaces = r->numFaces();
    for (int i = 0; i < nfaces; i++) {
	const Ptex::FaceInfo& f = r->getFaceInfo(i);
	std::cout << "face " << i << ":\n"
		  << "  res: " << int(f.res.ulog2) << ' ' << int(f.res.vlog2) << "\n"
		  << "  adjface: " 
		  << f.adjfaces[0] << ' '
		  << f.adjfaces[1] << ' '
		  << f.adjfaces[2] << ' '
		  << f.adjfaces[3] << "\n"
		  << "  adjedge: " 
		  << f.adjedge(0) << ' '
		  << f.adjedge(1) << ' '
		  << f.adjedge(2) << ' '
		  << f.adjedge(3) << "\n"
		  << "  flags: " << int(f.flags) << "\n";

	Ptex::Res res = f.res;
	while (res.ulog2 > 0 || res.vlog2 > 0) {
	    PtexFaceData* dh = r->getData(i, res);
	    if (!dh) break;
	    DumpData(r->dataType(), r->numChannels(), dh, "  ");
	    bool isconst = dh->isConstant();
	    dh->release();
	    if (isconst) break;
	    if (res.ulog2) res.ulog2--;
	    if (res.vlog2) res.vlog2--;
	}
	PtexFaceData* dh = r->getData(i, Ptex::Res(0,0));
	DumpData(r->dataType(), r->numChannels(), dh, "  ");
	dh->release();
    }

    return 0;
}
コード例 #2
0
ファイル: ipmpx_dump.c プロジェクト: ARSekkat/gpac
void gf_ipmpx_dump_ByteArray(GF_IPMPX_ByteArray *_p, const char *attName, FILE *trace, u32 indent, Bool XMTDump)
{
	if (_p && _p->data) {
		if (XMTDump) {
			StartElement(trace, attName ? attName : (char*)"ByteArray", indent, XMTDump);
			indent++;
			DumpData(trace, "array", _p->data, _p->length, indent, XMTDump);
			indent--;
			EndAttributes(trace, GF_TRUE, GF_FALSE);
		} else {
			DumpData(trace, attName ? attName : "ByteArray", _p->data, _p->length, indent, GF_FALSE);
		}
	}
}
コード例 #3
0
ファイル: MPICUDAStencil.cpp プロジェクト: tositrino/shoc
void
MPICUDAStencil<T>::operator()( Matrix2D<T>& mtx, unsigned int nIters )
{
    if( this->ParticipatingInProgram() )
    {
        // we need to do a halo exchange before our first push of
        // data onto the device
        if( dumpData )
        {
            this->DumpData( ofs, mtx, "before initial halo exchange" );
        }
        DoHaloExchange( mtx );
        if( dumpData )
        {
            this->DumpData( ofs, mtx, "after initial halo exchange" );
        }

        // apply the operator
        CUDAStencil<T>::operator()( mtx, nIters );
        if( dumpData )
        {
            DumpData( ofs, mtx, "after all iterations" );
        }
    }
    MPI_Barrier( MPI_COMM_WORLD );
}
コード例 #4
0
ファイル: ipmpx_dump.c プロジェクト: ARSekkat/gpac
void gf_ipmpx_dump_AUTH(GF_IPMPX_Authentication *ipa, FILE *trace, u32 indent, Bool XMTDump)
{
	switch (ipa->tag) {
	case GF_IPMPX_AUTH_KeyDescr_Tag:
	{
		GF_IPMPX_AUTH_KeyDescriptor *p = (GF_IPMPX_AUTH_KeyDescriptor *)ipa;
		StartElement(trace, "IPMP_KeyDescriptor", indent, XMTDump);
		DumpData(trace, "keyBody", p->keyBody, p->keyBodyLength, indent+1, XMTDump);
		if (XMTDump) EndAttributes(trace, GF_TRUE, GF_FALSE);
		else EndElement(trace, "", indent, GF_FALSE);
	}
	break;
	case GF_IPMPX_AUTH_AlgorithmDescr_Tag:
	{
		GF_IPMPX_AUTH_AlgorithmDescriptor *p = (GF_IPMPX_AUTH_AlgorithmDescriptor *)ipa;
		StartElement(trace, "IPMP_AlgorithmDescriptor", indent, XMTDump);
		if (p->regAlgoID) {
			DumpInt(trace, "regAlgoID", p->regAlgoID, indent+1, XMTDump);
		} else {
			gf_ipmpx_dump_ByteArray(p->specAlgoID, "specAlgoID", trace, indent+1, XMTDump);
		}
		EndAttributes(trace, XMTDump, GF_TRUE);
		if (p->OpaqueData) gf_ipmpx_dump_ByteArray(p->OpaqueData, "OpaqueData", trace, indent+1, XMTDump);

		EndElement(trace, "IPMP_AlgorithmDescriptor", indent, XMTDump);
	}
	break;
	}
}
コード例 #5
0
ファイル: mainwindow.cpp プロジェクト: Mandar-Shinde/AtomRSS
void MainWindow::on_Fetch_clicked()
{
    QUrl url(ui->lineEdit->text());
    WebWorker *w = new WebWorker(url);
    connect(w,SIGNAL(WorkCompleted(QString)),this,SLOT(DumpData(QString)));
    QThreadPool::globalInstance()->start(w);    
}
コード例 #6
0
ファイル: NXbrowse.c プロジェクト: ebknudsen/code
/* Dumps data to a file. Uses recursion because of unknown number of dimensions. */
void DumpData(FILE * fd, int rank, int dimensions[], int dataType, void *data)
{
    char *dataPtr;
    int i, dimSize, dataSize, lineSize;

    if (rank > 1) {		/* Recursively call DumpData until rank = 1 */
        for (i = 1, dimSize = 1; i < rank; i++) {
            dimSize *= dimensions[i];
        }
        for (i = 0; i < dimensions[0]; i++) {
            dataPtr =
                (char *)data + i * dimSize * nxTypeSize(dataType);
            DumpData(fd, rank - 1, &dimensions[1], dataType,
                     dataPtr);
        }
        return;
    } else {		/* Actually print the data */
        dataSize = dimensions[0];
        dataPtr = (char *)data;
        while (dataSize > 0) {
            if (dataSize > 10) {
                lineSize = 10;
            } else {
                lineSize = dataSize;
            }
            WriteData(fd, dataPtr, dataType, lineSize);
            fprintf(fd, "\n");
            dataSize -= lineSize;
            dataPtr += lineSize * nxTypeSize(dataType);
        }
    }
}
コード例 #7
0
ファイル: CAISAVLD.CPP プロジェクト: Marenz/EnemyNations
void CAISavLd::Save( void )
{
    CFile *pFile;
    CFileException* theException = new CFileException;
    CString sStdExt, sHead, sSave;
    sStdExt = ".std";

    for( int i=TASK_DATA; i<=GOAL_DATA; ++i )
    {
        switch( i )
        {
        case GOAL_DATA:
            sHead = "goals";
            break;
        case TASK_DATA:
            sHead = "tasks";
            break;
        default:
            return;
        }
        sSave = sHead + sStdExt;

        CString sMsg;
        // save the list of objects
        TRY
        {
            pFile = OpenForDump( sSave );
            ASSERT( pFile != NULL );

            DumpData( pFile, i );
        }
        CATCH( CFileException, theException )
        {
            // "Save Error"
            sMsg = "Save Error";
            if( m_pParent != NULL )
                m_pParent->MessageBox( sMsg, sSave,
                                       MB_ICONEXCLAMATION | MB_SYSTEMMODAL | MB_OK );
            sMsg.Empty();

            //throw(ERR_CAI_BAD_FILE);
        }
        AND_CATCH( CArchiveException, theException )
        {
            pFile->Close();
            delete pFile;
            // "Archive Error"
            sMsg = "Archive Error";
            if( m_pParent != NULL )
                m_pParent->MessageBox( sMsg, sSave,
                                       MB_ICONEXCLAMATION | MB_SYSTEMMODAL | MB_OK );
            sMsg.Empty();

            //throw(ERR_CAI_BAD_FILE);
        }
コード例 #8
0
ファイル: NXbrowse.c プロジェクト: ebknudsen/code
/* Dumps requested data */
int NXBdump(NXhandle fileId, NXname dataName, char *fileName)
{
    int dataRank, dataDimensions[NX_MAXRANK], dataType, i;
    FILE *fd = NULL;
    void *dataBuffer;

    /* Check the specified data item exists */
    if (FindData(fileId, dataName) != NX_OK)
        return NX_ERROR;

    /* Open the data and obtain its type and rank details */
    if (NXopendata(fileId, dataName) != NX_OK)
        return NX_ERROR;
    if (NXgetinfo(fileId, &dataRank, dataDimensions, &dataType) != NX_OK)
        return NX_ERROR;

    /* Open the file */
    fd = fopen(fileName, "w");
    if (!fd) {
        printf("ERROR: failed to open--> %s <-- for writing\n",
               fileName);
        return NX_ERROR;
    }

    /* Allocate data space */
    if (NXmalloc(&dataBuffer, dataRank, dataDimensions, dataType) != NX_OK)
        return NX_ERROR;

    /* Read the lot */
    if (NXgetdata(fileId, dataBuffer) != NX_OK)
        return NX_ERROR;

    if (NXclosedata(fileId) != NX_OK)
        return NX_ERROR;

    /* Print a header */
    fprintf(fd, "File : %s, DataSet: %s \n", nxFile, dataName);
    for (i = 0; i < dataRank; i++) {
        fprintf(fd, " %d ", dataDimensions[i]);
    }
    fprintf(fd, "\n");

    /* Dump the data */
    DumpData(fd, dataRank, dataDimensions, dataType, dataBuffer);

    /* Clean up */
    fclose(fd);
    NXfree(&dataBuffer);
    return NX_OK;
}
コード例 #9
0
ファイル: rtest.cpp プロジェクト: wildparky/ptex
void DumpData(Ptex::DataType dt, int nchan, PtexFaceData* dh, std::string prefix)
{
    void* dpixel = malloc(Ptex::DataSize(dt)*nchan);
    float* pixel = (float*) malloc(sizeof(float)*nchan);
    uint8_t* cpixel = (uint8_t*) malloc(sizeof(uint8_t)*nchan);
    Ptex::Res res = dh->res();
    printf("%sdata (%d x %d)", prefix.c_str(), res.u(), res.v());
    if (dh->isTiled()) {
	Ptex::Res tileres = dh->tileRes();
	printf(", tiled (%d x %d):\n", tileres.u(), tileres.v());
	int n = res.ntiles(tileres);
	for (int i = 0; i < n; i++) {
	    PtexFaceData* t = dh->getTile(i);
	    std::cout << prefix << "  tile " << i;
	    if (!t) {
		std::cout << " NULL!" << std::endl;
	    } else {
		DumpData(dt, nchan, t, prefix + "  ");
		t->release();
	    }
	}
    } else {
	int ures, vres;
	if (dh->isConstant()) { ures = vres = 1; std::cout << ", const: "; }
	else { ures = res.u(); vres = res.v(); std::cout << ":\n"; }
	
	int vimax = vres;// if (vimax > 16) vimax = 16;
	for (int vi = 0; vi < vimax; vi++) {
	    if (vi == 8 && vres > 16) { vi = vres-8; std::cout << prefix << "  ..." << std::endl; }
	    std::cout << prefix << "  ";
	    int uimax = ures;// if (uimax > 16) uimax = 16;
	    for (int ui = 0; ui < uimax; ui++) {
		if (ui == 8 && ures > 16) { ui = ures-8; std::cout << "... "; }
		dh->getPixel(ui, vi, dpixel);
		Ptex::ConvertToFloat(pixel, dpixel, dt, nchan);
		Ptex::ConvertFromFloat(cpixel, pixel, Ptex::dt_uint8, nchan);
		for (int c=0; c < nchan; c++) {
		    printf("%02x", cpixel[c]);
		}
		printf(" ");
	    }
	    if (uimax != ures) printf(" ...");
	    printf("\n");
	}
	if (vimax != vres) std::cout << prefix << "  ..." << std::endl;
    }
    free(cpixel);
    free(pixel);
    free(dpixel);
}
コード例 #10
0
ファイル: ipmpx_dump.c プロジェクト: ARSekkat/gpac
GF_Err gf_ipmpx_dump_WatermarkingInit(GF_IPMPX_Data *_p, FILE *trace, u32 indent, Bool XMTDump)
{
	GF_IPMPX_WatermarkingInit*p = (GF_IPMPX_WatermarkingInit*)_p;
	StartElement(trace, (char*)  ( (_p->tag==GF_IPMPX_AUDIO_WM_INIT_TAG) ? "IPMP_AudioWatermarkingInit" : "IPMP_VideoWatermarkingInit"), indent, XMTDump);
	indent++;
	DumpInt(trace, "inputFormat", p->inputFormat, indent, XMTDump);
	DumpInt(trace, "requiredOp", p->requiredOp, indent, XMTDump);
	if (p->inputFormat==0x01) {
		if (_p->tag==GF_IPMPX_AUDIO_WM_INIT_TAG) {
			DumpInt(trace, "nChannels", p->nChannels, indent, XMTDump);
			DumpInt(trace, "bitPerSample", p->bitPerSample, indent, XMTDump);
			DumpInt(trace, "frequency", p->frequency, indent, XMTDump);
		} else {
			DumpInt(trace, "frame_horizontal_size", p->frame_horizontal_size, indent, XMTDump);
			DumpInt(trace, "frame_vertical_size", p->frame_vertical_size, indent, XMTDump);
			DumpInt(trace, "chroma_format", p->chroma_format, indent, XMTDump);
		}
	}
	switch (p->requiredOp) {
	case GF_IPMPX_WM_INSERT:
	case GF_IPMPX_WM_REMARK:
		DumpData(trace, "wmPayload", p->wmPayload, p->wmPayloadLen, indent, XMTDump);
		break;
	case GF_IPMPX_WM_EXTRACT:
	case GF_IPMPX_WM_DETECT_COMPRESSION:
		DumpInt(trace, "wmRecipientId", p->wmRecipientId, indent, XMTDump);
		break;
	}
	if (p->opaqueData) DumpData(trace, "opaqueData", p->opaqueData, p->opaqueDataSize, indent, XMTDump);

	EndAttributes(trace, XMTDump, GF_TRUE);
	gf_ipmpx_dump_BaseData(_p, trace, indent, XMTDump);
	indent--;
	EndElement(trace, (char*) ( (_p->tag==GF_IPMPX_AUDIO_WM_INIT_TAG) ? "IPMP_AudioWatermarkingInit" : "IPMP_VideoWatermarkingInit"), indent, XMTDump);
	return GF_OK;
}
コード例 #11
0
ファイル: wave.cpp プロジェクト: ifapmzadu6/speech-analyzer
int Wave::InputWave(const std::string filename) {
    if (filename.compare(filename.size() - 4, 4, ".wav") == 0) {
        ldata.clear();
        rdata.clear();
        monodata.clear();

        wavename = filename;
        WavHdrRead();
        DumpData();
        SetHeader();
        flag = true;
    } else {
        std::cerr << "error .wav" << std::endl;
        return -1;
    }
    return 0;
}
コード例 #12
0
ファイル: ssltrace.c プロジェクト: Correlsense/libdssl
/* data callback routine that simply dumps the decoded data on the screen */
static void data_callback_proc( NM_PacketDir dir, void* user_data, u_char* pkt_payload,
							  uint32_t pkt_size, DSSL_Pkt* last_packet )
{
	last_packet;
	switch(dir)
	{
	case ePacketDirFromClient:
		printf( "\nC->S:\n" );
		break;
	case ePacketDirFromServer:
		printf( "\nS->C:\n" );
		break;
	default:
		printf( "\nUnknown packet direction!" );
		return;
	}

	DumpData( pkt_payload, pkt_size );
}
コード例 #13
0
void uORB::KraitFastRpcChannel::fastrpc_recv_thread()
{
	// sit in while loop.
	int32_t rc = 0;
	int32_t  data_length = 0;
	uint8_t *data = nullptr;
	unsigned long rpc_min, rpc_max;
	unsigned long orb_min, orb_max;
	double rpc_avg, orb_avg;
	unsigned long count = 0;
	rpc_max = orb_max = 0;
	rpc_min = orb_min = 0xFFFFFFFF;
	rpc_avg = orb_avg = 0.0;

	int32_t num_topics = 0;

	hrt_abstime check_time = 0;

	while (!_ThreadShouldExit) {
		hrt_abstime t1, t2, t3;
		t1 = hrt_absolute_time();
		rc = _KraitWrapper.ReceiveBulkData(&data, &data_length, &num_topics);

		t2 = hrt_absolute_time();

		if (rc == 0) {
			//PX4_DEBUG( "Num of topics Received: %d", num_topics );
			int32_t bytes_processed = 0;

			for (int i = 0; i < num_topics; ++i) {
				uint8_t *new_pkt = &(data[bytes_processed]);
				struct BulkTransferHeader *header = (struct BulkTransferHeader *)new_pkt;
				char *messageName = (char *)(new_pkt + sizeof(struct BulkTransferHeader));
				uint16_t check_msg_len = strlen(messageName);

				if (header->_MsgNameLen != (check_msg_len + 1)) {
					PX4_ERR("Error: Packing error.  Sent Msg Len. of[%d] but strlen returned:[%d]", header->_MsgNameLen , check_msg_len);
					PX4_ERR("Error: NumTopics: %d processing topic: %d msgLen[%d] dataLen[%d] data_len[%d] bytes processed: %d",
						num_topics, i, header->_MsgNameLen, header->_DataLen , data_length, bytes_processed);
					DumpData(data, data_length, num_topics);
					break;
				}

				uint8_t *topic_data = (uint8_t *)(messageName + strlen(messageName) + 1);

				if (_RxHandler != nullptr) {
					_RxHandler->process_received_message(messageName,
									     header->_DataLen, topic_data);
					//PX4_DEBUG( "Received topic data for control message for: [%s] len[%d]\n", name, data_length );
				}

				bytes_processed += header->_MsgNameLen + header->_DataLen + sizeof(struct BulkTransferHeader);
			}

		} else {
			PX4_DEBUG("Error: Getting data over fastRPC channel\n");
			break;
		}

		t3 = hrt_absolute_time();
		count++;

		if ((unsigned long)(t2 - t1) < rpc_min) {
			rpc_min = (unsigned long)(t2 - t1);
		}

		if ((unsigned long)(t2 - t1) > rpc_max) {
			rpc_max = (unsigned long)(t2 - t1);
		}

		if ((unsigned long)(t3 - t2) < orb_min) {
			orb_min = (unsigned long)(t3 - t2);
		}

		if ((unsigned long)(t3 - t2) > orb_max) {
			orb_max = (unsigned long)(t3 - t2);
		}

		rpc_avg = ((double)((rpc_avg * (count - 1)) + (unsigned long)(t2 - t1))) / (double)(count);
		orb_avg = ((double)((orb_avg * (count - 1)) + (unsigned long)(t3 - t2))) / (double)(count);

		if ((unsigned long)(t3 - check_time) >= 10000000) {
			//PX4_DEBUG("Krait RPC Stats     : rpc_min: %lu rpc_max: %lu rpc_avg: %f", rpc_min, rpc_max, rpc_avg);
			//PX4_DEBUG("Krait RPC(orb) Stats: orb_min: %lu orb_max: %lu orb_avg: %f", orb_min, orb_max, orb_avg);
			check_time = t3;
			rpc_max = orb_max = 0;
			rpc_min = orb_min = 0xFFFFFF;
			orb_avg = 0;
			rpc_avg = 0;
			count = 0;
		}

		//PX4_DEBUG("MsgName: %30s, t1: %lu, t2: %lu, t3: %lu, dt1: %lu, dt2: %lu",name, (unsigned long) t1, (unsigned long) t2, (unsigned long) t3,
		//  (unsigned long) (t2-t1), (unsigned long) (t3-t2));
	}

	PX4_DEBUG("[uORB::KraitFastRpcChannel::fastrpc_recv_thread] Exiting fastrpc_recv_thread\n");
}
コード例 #14
0
ファイル: Logging.cpp プロジェクト: JTurpin/sprinklers_pi
bool Logging::GraphZone(FILE* stream_file, time_t start, time_t end, GROUPING grouping)
{
    if (start == 0)
        start = nntpTimeServer.LocalNow();
    end = max(start,end) + 24*3600;  // add 1 day to end time.

    grouping = max(NONE, min(grouping, MONTHLY));
    char sSQL[200];
    uint16_t bins = 0;
    uint32_t bin_offset = 0;
    uint32_t bin_scale = 1;
    switch (grouping)
    {
    case HOURLY:
        snprintf(sSQL, sizeof(sSQL),
                 "SELECT zone, strftime('%%H', date, 'unixepoch') as hour, SUM(duration)"
                 " FROM zonelog WHERE date BETWEEN %lu AND %lu"
                 " GROUP BY zone,hour ORDER BY zone,hour",
                 start, end);
        bins = 24;
        break;
    case DAILY:
        snprintf(sSQL, sizeof(sSQL),
                 "SELECT zone, strftime('%%w', date, 'unixepoch') as bucket, SUM(duration)"
                 " FROM zonelog WHERE date BETWEEN %lu AND %lu"
                 " GROUP BY zone,bucket ORDER BY zone,bucket",
                 start, end);
        bins = 7;
        break;
    case MONTHLY:
        snprintf(sSQL, sizeof(sSQL),
                 "SELECT zone, strftime('%%m', date, 'unixepoch') as bucket, SUM(duration)"
                 " FROM zonelog WHERE date BETWEEN %lu AND %lu"
                 " GROUP BY zone,bucket ORDER BY zone,bucket",
                 start, end);
        bins = 12;
        break;
    case NONE:
        bins = 100;
        bin_offset = start;
        bin_scale = (end-start)/bins;
        snprintf(sSQL, sizeof(sSQL),
                 "SELECT zone, ((date-%lu)/%" PRIu32 ") as bucket, SUM(duration)"
                 " FROM zonelog WHERE date BETWEEN %lu AND %lu"
                 " GROUP BY zone,bucket ORDER BY zone,bucket",
                 start, bin_scale, start, end);
        break;
    }

    // Make sure we've zero terminated this string.
    sSQL[sizeof(sSQL)-1] = 0;

    trace("%s\n", sSQL);

    sqlite3_stmt * statement;
    // Now determine if we're running V1.0 of the schema.
    int res = sqlite3_prepare_v2(m_db, sSQL, -1, &statement, NULL);
    if (res)
    {
        trace("Prepare Failure (%s)\n", sqlite3_errmsg(m_db));
        return false;
    }

    int current_zone = -1;
    bool bFirstZone = true;
    uint32_t bin_data[bins];
    memset(bin_data, 0, bins*sizeof(uint32_t));
    while (sqlite3_step(statement) == SQLITE_ROW)
    {
        int zone = sqlite3_column_int(statement, 0);
        if (current_zone != zone)
        {
            current_zone = zone;
            if (!bFirstZone)
                DumpData(stream_file, bin_data, bins, bin_scale, bin_offset, grouping == NONE);
            fprintf(stream_file, "%s\t\"%d\" : [", bFirstZone?"":"],\n", zone);
            memset(bin_data, 0, bins*sizeof(uint32_t));
            bFirstZone = false;
        }
        uint32_t bin = sqlite3_column_int(statement, 1);
        uint32_t value = sqlite3_column_int(statement, 2);
        bin_data[bin] = value;
    }
    if (!bFirstZone)
    {
        DumpData(stream_file, bin_data, bins, bin_scale, bin_offset, grouping == NONE);
        fprintf(stream_file, "]\n");
    }

    sqlite3_finalize(statement);

    return true;
}
コード例 #15
0
ファイル: benchmark.c プロジェクト: eth-cscs/cscs_io
void mainloop(simulation_data *sim)
{
  int blocking, visitstate, err = 0;
  char Filename[256];

#ifdef VISIT_INSITU
  if(sim->runMode == SIM_STOPPED)
    simulate_one_timestep(sim);
  do
    {
    blocking = (sim->runMode == SIM_RUNNING) ? 0 : 1;

// Get input from VisIt or timeout so the simulation can run.
    if(sim->par_rank == 0)
      visitstate = VisItDetectInput(blocking, -1);
    MPI_Bcast(&visitstate, 1, MPI_INT, 0, sim->comm_cart);

// Do different things depending on the output from VisItDetectInput
    switch(visitstate)
      {
      case 0:
// There was no input from VisIt, return control to sim
        simulate_one_timestep(sim);
      break;
      case 1:
// VisIt is trying to connect to sim.
        if(VisItAttemptToCompleteConnection() == VISIT_OKAY)
          {
          //fprintf(stderr, "VisIt connected\n");
          VisItSetCommandCallback(ControlCommandCallback, (void*)sim);
          VisItSetSlaveProcessCallback2(SlaveProcessCallback, (void*)sim);

          VisItSetGetMetaData(SimGetMetaData, (void*)sim);
          VisItSetGetMesh(SimGetMesh, (void*)sim);
          VisItSetGetVariable(SimGetVariable, (void*)sim);
          VisItSetGetDomainList(SimGetDomainList, (void*)sim);
          }
        else
          {
          char *err = VisItGetLastError();
          fprintf(stderr, "VisIt did not connect: %s\n", err);
          free(err);
          }
      break;
      case 2:
// VisIt wants to tell the engine something
        if(!ProcessVisItCommand(sim))
          {
// Disconnect on an error or closed connection.
           VisItDisconnect();
// Start running again if VisIt closes.
           sim->runMode = SIM_RUNNING;
          }
      break;
      default:
        fprintf(stderr, "Can't recover from error %d!\n", visitstate);
        err = 1;
      break;
      }
    } while(!sim->done && err == 0);
#else
  do
    {
    simulate_one_timestep(sim);
    char postfix[4];
#ifdef ADIOS
    strcpy(postfix, "bp");
    DumpData(sim, sim->filename, sim->saveCounter++, postfix);
#elif NETCDF4
#ifdef PARIO
    strcpy(postfix, "p.nc");
    DumpData(sim, sim->filename, sim->saveCounter++, postfix);
#else
    strcpy(postfix, "s.nc");
    DumpData(sim, sim->filename, sim->saveCounter++, postfix);
#endif
#elif HDF5
    strcpy(postfix, "h5");
    DumpData(sim, sim->filename, sim->saveCounter++, postfix);
#elif BOV
    strcpy(postfix, "bof");
    char name[512];
    char cmd[512];
    int l0 =  strlen(strrchr(sim->filename, '/'));
    int l =  1+strlen(sim->filename) - l0;
    strncpy(name, sim->filename, l);
    sprintf(&name[l], "%05d/", sim->saveCounter);
    sprintf(cmd, "mkdir %s", &name[0]);
    if(!sim->par_rank){
      system(cmd);
    }
    MPI_Barrier(sim->comm_cart);
    strncpy(&name[l+6], &sim->filename[l], l0);
    //fprintf(stderr, "creating a subdirectory %s %d\n",name, l0);
    //fprintf(stderr, "creating a subdirectory %s %d\n",sim->filename, sim->saveCounter);
    DumpData(sim, name, sim->saveCounter++, postfix);
#else
    strcpy(postfix, "bin");
    DumpData(sim, sim->filename, sim->saveCounter++, postfix);
#endif

    //if(sim->par_rank == 0) printf("Saved file %s\n", Filename);

    if(sim->cycle == NUMBER_OF_ITERATIONS)
      {
      sim->done = 1;
      }
    } while(!sim->done && err == 0);
#endif
}
コード例 #16
0
ファイル: EngineDump.cpp プロジェクト: Livit/moonpdf
int main(int argc, char **argv)
{
    setlocale(LC_ALL, "C");
    DisableDataExecution();

    WStrVec argList;
    ParseCmdLine(GetCommandLine(), argList);
    if (argList.Count() < 2) {
Usage:
        ErrOut("%s <filename> [-pwd <password>][-full][-alt][-render <path-%%d.tga>]\n",
            path::GetBaseName(argList.At(0)));
        return 0;
    }

    ScopedMem<WCHAR> filePath;
    WIN32_FIND_DATA fdata;
    HANDLE hfind = FindFirstFile(argList.At(1), &fdata);
    if (INVALID_HANDLE_VALUE != hfind) {
        ScopedMem<WCHAR> dir(path::GetDir(argList.At(1)));
        filePath.Set(path::Join(dir, fdata.cFileName));
        FindClose(hfind);
    }
    else {
        // embedded documents are referred to by an invalid path
        // containing more information after a colon (e.g. "C:\file.pdf:3:0")
        filePath.Set(str::Dup(argList.At(1)));
    }

    bool fullDump = false;
    WCHAR *password = NULL;
    WCHAR *renderPath = NULL;
    bool useAlternateHandlers = false;
    bool loadOnly = false;
    int breakAlloc = 0;

    for (size_t i = 2; i < argList.Count(); i++) {
        if (str::Eq(argList.At(i), L"-full"))
            fullDump = true;
        else if (str::Eq(argList.At(i), L"-pwd") && i + 1 < argList.Count())
            password = argList.At(++i);
        else if (str::Eq(argList.At(i), L"-render") && i + 1 < argList.Count())
            renderPath = argList.At(++i);
        else if (str::Eq(argList.At(i), L"-alt"))
            useAlternateHandlers = true;
        else if (str::Eq(argList.At(i), L"-loadonly"))
            loadOnly = true;
#ifdef DEBUG
        else if (str::Eq(argList.At(i), L"-breakalloc") && i + 1 < argList.Count())
            breakAlloc = _wtoi(argList.At(++i));
#endif
        else
            goto Usage;
    }

#ifdef DEBUG
    if (breakAlloc) {
        _CrtSetBreakAlloc(breakAlloc);
        if (!IsDebuggerPresent())
            MessageBox(NULL, L"Keep your debugger ready for the allocation breakpoint...", L"EngineDump", MB_ICONINFORMATION);
    }
#endif

    // optionally use GDI+ rendering for PDF/XPS and the original ChmEngine for CHM
    DebugGdiPlusDevice(useAlternateHandlers);
    DebugAlternateChmEngine(!useAlternateHandlers);

    ScopedGdiPlus gdiPlus;
    DocType engineType;
    PasswordHolder pwdUI(password);
    BaseEngine *engine = EngineManager::CreateEngine(true, filePath, &pwdUI, &engineType);
    if (!engine) {
        ErrOut("Error: Couldn't create an engine for %s!\n", path::GetBaseName(filePath));
        return 1;
    }
    if (!loadOnly)
        DumpData(engine, fullDump);
    if (renderPath)
        RenderDocument(engine, renderPath);
    delete engine;

#ifdef DEBUG
    // report memory leaks on stderr for engines that shouldn't leak
    if (engineType != Engine_DjVu) {
        _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
        _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
        _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    }
#endif

    return 0;
}
コード例 #17
0
ファイル: test.c プロジェクト: adibacco/yp2seletech
int main()
{
unsigned char  buffer[INPUT_BUFFER];
unsigned char  *TmRegArea,*I2CArea,*TEMAC0Area,*TEMAC1Area,*TEMAC2Area,*BdArea,*ptr,EthControllerState=0;;
int            i,fd,Exit=0;
unsigned       rc,Address,Data,Offset,I2C_slave_address,tmp1;
struct termios oldt, newt;
int            ch;

tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;

newt.c_cc[VMIN] = 0;
newt.c_cc[VTIME] = 1;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );

fd = open("/dev/mem",O_RDWR|O_SYNC);
if(fd < 0){
  printf("Can't open /dev/mem\n");
  return 1;
  }
TmRegArea = (unsigned char *) mmap(0, 0x10000, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x44000000);
if(TmRegArea == NULL){
  printf("Can't mmap\n");
  return 1;
  }
printf("\nTmRegArea %08X",TmRegArea);     //edo

TEMAC0Area = (unsigned char *) mmap(0, 0x10000, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x47000000);
if(TEMAC0Area == NULL){
  printf("Can't mmap\n");
  return 1;
  }
printf("\nTEMAC0Area %08X",TEMAC0Area);     //edo

TEMAC1Area = (unsigned char *) mmap(0, 0x10000, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x48000000);
if(TEMAC1Area == NULL){
  printf("Can't mmap\n");
  return 1;
  }
printf("\nTEMAC1Area %08X",TEMAC1Area);     //edo

TEMAC2Area = (unsigned char *) mmap(0, 0x10000, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x49000000);
if(TEMAC2Area == NULL){
  printf("Can't mmap\n");
  return 1;
  }
printf("\nTEMAC2Area %08X",TEMAC2Area);     //edo

BdArea = (unsigned char *) mmap(0, 0x20000, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x45000000);
if(BdArea == NULL){
  printf("Can't mmap\n");
  return 1;
  }
printf("\nBdArea %08X",BdArea);     //edo

printf("Tm>\n");
i = 0;
do{
/*----------------------------------------------------------------------------*/
/* Ethernet Rx frame management.                                              */
/*----------------------------------------------------------------------------*/
  if (EthControllerState != 0)
    Ethernet_GetRxFrameManagement();

  buffer[i] = getchar();
  if (buffer[i] != 0xFF){
    printf("%c",buffer[i]);
    if (buffer[i] == CHAR_LF){
      printf("\n");
      buffer[i] = 0;
      rc = 0;

      switch (buffer[0]){

/*----------------------------------------------------------------------------*/  
/* I2C                                                                        */
/*----------------------------------------------------------------------------*/ 
		case 'c':
			if (buffer[1]=='1')
			{
				*(unsigned *) (TEMAC0Area+0x0404) = 0xD0000000;
				*(unsigned *) (TEMAC0Area+0x0408) = 0xD0000000;
				*(unsigned *) (TEMAC0Area+0x0500) = 0x58;
				*(unsigned *) (TEMAC0Area+0x0508) = 0x1140;
				*(unsigned *) (TEMAC0Area+0x0504) = 0x4800;
				delay(0x1000000);
				while (( ((*(unsigned *) (TEMAC0Area+0x050C)) & 0x10000) != 0x10000));
				*(unsigned *) (TEMAC0Area+0x0508) = 0x1340;
				*(unsigned *) (TEMAC0Area+0x0504) = 0x4800;
				delay(0x1000000);
				while (( ((*(unsigned *) (TEMAC0Area+0x050C)) & 0x10000) != 0x10000));

				*(unsigned *) (TEMAC0Area+0x0504) = 0x18800;
				delay(0x1000000);
				while (( ((*(unsigned *) (TEMAC0Area+0x050C)) & 0x10000) != 0x10000));
				printf("\n\rStatus register: ");
				printf("%08X",((*(unsigned *) (TEMAC0Area+0x050C)) & 0xFFFF));

				*(unsigned *) (TEMAC0Area+0x0504) = 0x18800;
				delay(0x1000000);
				while (( ((*(unsigned *) (TEMAC0Area+0x050C)) & 0x10000) != 0x10000));
				printf("\n\rStatus register: ");
				printf("%08X",((*(unsigned *) (TEMAC0Area+0x050C)) & 0xFFFF));
				
				*(unsigned *) (TmRegArea+0x1004) = 0x1;
				*(unsigned *) (TmRegArea+0x1204) = 0x1;
				*(unsigned *) (TmRegArea+0x1304) = 0x1;
				*(unsigned *) (TmRegArea+0x0010) = 0x1;

				*(unsigned *) (TmRegArea+0xC000) = 0x00010203;
				*(unsigned *) (TmRegArea+0xC004) = 0x04060000;
				*(unsigned *) (TmRegArea+0xC008) = 0xFFFFFFFF;
				*(unsigned *) (TmRegArea+0xC00C) = 0xFFFF0000;
				*(unsigned *) (TmRegArea+0xC010) = 0x15;

			}
			else if (buffer[1]=='2')
			{
				
			}
			else if (buffer[1]=='3')
			{
				
			}
			else
				rc = ERROR_SYNTAX;
			break;

/*----------------------------------------------------------------------------*/
/* Ethernet statistics command.                                               */
/*----------------------------------------------------------------------------*/
        case 'e':
            break;

/*----------------------------------------------------------------------------*/
/* Ethernet controller initialization command.                                */
/*----------------------------------------------------------------------------*/
        case 'E':
            rc = EthernetControllerInit(TmRegArea,BdArea);
            EthControllerState = 1;
            break;

/*----------------------------------------------------------------------------*/
/* Help panel command.                                                        */
/*----------------------------------------------------------------------------*/
        case 'h':
            PrintHelpPanel();
            rc = 0;
            break;

/*----------------------------------------------------------------------------*/
/* Memory Dump.                                                               */
/*----------------------------------------------------------------------------*/
        case 'm':
          rc = 0;
          if (buffer[1] == 'd'){
            ptr = AsciiToHex(&buffer[2],&Address);
            Data = 0x40;
            if ((ptr != 0)&&(*ptr == ',')){
              ptr = AsciiToHex(++ptr,&Data);
              if (Data == 0)
                Data = 0x40;
              }
            if ((Address & 0xFFF00000) == 0x83C00000){
              Offset = Address - 0x83C00000;
              DumpData(TmRegArea+Offset,Address,Data);
              }
            else if ((Address & 0xFF000000) == 0x84000000){
              Offset = Address - 0x84000000;
              DumpData(BdArea+Offset,Address,Data);
              }
            }
          else if (buffer[1] == 'w'){
            ptr = AsciiToHex(&buffer[2],&Address);
            if ((ptr == 0)||(*ptr != ','))
              rc = ERROR_SYNTAX;
            else{
              ptr = AsciiToHex(++ptr,&Data);
              if ((Address & 0xFFF00000) == 0x83C00000){
                Address = Address - 0x83C00000;
                *(unsigned *)(TmRegArea+Address) = Data;
                }
              else if ((Address & 0xFF000000) == 0x84000000){
                Address = Address - 0x84000000;
                *(unsigned *)(BdArea+Address) = Data;
                }
              }
            }
          else
            rc = ERROR_SYNTAX;
          break;

/*----------------------------------------------------------------------------*/
/* Exit command.                                                              */
/*----------------------------------------------------------------------------*/
        case 'q':
            Exit = 1;
            rc = 0;
            break;

/*----------------------------------------------------------------------------*/
/* Error in case commands are not found.                                      */
/*----------------------------------------------------------------------------*/
        default:
          rc = ERROR_SYNTAX;
          printf("\n\rSyntax Error in last command");
          break;
        }

      i = 0;
      if (rc != 0)
        printf("\n\rERROR: %08X",rc);
      else
        printf("\n\rOK\n\r");
        
      printf("\n\rTm>");
      }
    else
      if (buffer[i] == CHAR_BS){
        if (i > 0)
          i--;
        }
    else
      if (++i > INPUT_BUFFER - 1)
        i = INPUT_BUFFER - 1;
    }
  } while (Exit == 0);

tcsetattr( STDIN_FILENO, TCSANOW, &oldt );

}
コード例 #18
0
ファイル: MPICUDAStencil.cpp プロジェクト: tositrino/shoc
void
MPICUDAStencil<T>::DoPreIterationWork( T* currBuf,  // in device global memory
                                       T* altBuf,  // in device global memory
                                       Matrix2D<T>& mtx,
                                       unsigned int iter )
{
    // do the halo exchange at desired frequency
    // note that we *do not* do the halo exchange here before the
    // first iteration, because we did it already (before we first
    // pushed the data onto the device) in our operator() method.
    unsigned int haloWidth = this->GetNumberIterationsPerHaloExchange();
    if( (iter > 0) && (iter % haloWidth) == 0 )
    {
        unsigned int nRows = mtx.GetNumRows();
        unsigned int nCols = mtx.GetNumColumns();
        unsigned int nPaddedCols = mtx.GetNumPaddedColumns();
        T* flatData = mtx.GetFlatData();

        size_t nsDataItemCount = haloWidth * nPaddedCols;
        size_t ewDataItemCount = haloWidth * nRows;
        size_t nsDataSize = nsDataItemCount * sizeof(T);
        size_t ewDataSize = ewDataItemCount * sizeof(T);

        //
        // read current data off device
        // we only read halo, and only for sides where we have a neighbor
        //
        if( this->HaveNorthNeighbor() )
        {
            // north data is contiguous - copy directly into matrix
            cudaMemcpy( flatData + (haloWidth * nPaddedCols),   // dest
                        currBuf + (haloWidth * nPaddedCols),     // src
                        nsDataSize,                 // amount to transfer
                        cudaMemcpyDeviceToHost );   // direction
        }

        if( this->HaveSouthNeighbor() )
        {
            // south data is contiguous - copy directly into matrix
            cudaMemcpy( flatData + ((nRows - 2*haloWidth)*nPaddedCols),   // dest
                        currBuf + ((nRows - 2*haloWidth)*nPaddedCols),    // src
                        nsDataSize,                 // amount to transfer
                        cudaMemcpyDeviceToHost );   // direction
        }

        if( this->HaveEastNeighbor() )
        {
            // east data is non-contiguous - but CUDA has a strided read
            cudaMemcpy2D( flatData + (nCols - 2*haloWidth), // dest
                          nPaddedCols * sizeof(T),        // dest pitch
                          currBuf + (nCols - 2*haloWidth),    // src
                          nPaddedCols * sizeof(T),        // src pitch
                          haloWidth * sizeof(T),          // width of data to transfer (bytes)
                          nRows,                          // height of data to transfer (rows)
                          cudaMemcpyDeviceToHost );       // transfer direction
        }

        if( this->HaveWestNeighbor() )
        {
            // west data is non-contiguous - but CUDA has a strided read
            cudaMemcpy2D( flatData + haloWidth,         // dest
                          nPaddedCols * sizeof(T),    // dest pitch
                          currBuf + haloWidth,        // src
                          nPaddedCols * sizeof(T),    // src pitch
                          haloWidth * sizeof(T),      // width of data to transfer (bytes)
                          nRows,          // height of data to transfer (rows)
                          cudaMemcpyDeviceToHost );   // transfer direction

        }


        //
        // do the actual halo exchange
        //
        if( dumpData )
        {
            DumpData( ofs, mtx, "before halo exchange" );
        }
        DoHaloExchange( mtx );
        if( dumpData )
        {
            DumpData( ofs, mtx, "after halo exchange" );
        }

        //
        // push updated data back onto device
        // we only write halo, and only for sides where we have a neighbor
        //
        if( this->HaveNorthNeighbor() )
        {
            // north data is contiguous - copy directly from matrix
            cudaMemcpy( currBuf,                    // dest
                        flatData,                   // src
                        nsDataSize,                 // amount to transfer
                        cudaMemcpyHostToDevice );   // direction
        }

        if( this->HaveSouthNeighbor() )
        {
            // south data is contiguous - copy directly from matrix
            cudaMemcpy( currBuf + ((nRows - haloWidth)*nPaddedCols),    // dest
                        flatData + ((nRows - haloWidth)*nPaddedCols),   // src
                        nsDataSize,                 // amount to transfer
                        cudaMemcpyHostToDevice );   // direction
        }

        if( this->HaveEastNeighbor() )
        {
            // east data is non-contiguous - but CUDA has a strided write
            cudaMemcpy2D( currBuf + (nCols - haloWidth),  // dest
                          nPaddedCols * sizeof(T),              // dest pitch
                          flatData + (nCols - haloWidth), // src
                          nPaddedCols * sizeof(T),              // src pitch
                          haloWidth * sizeof(T),          // width of data to transfer (bytes)
                          nRows,                          // height of data to transfer (rows)
                          cudaMemcpyHostToDevice );       // transfer direction
        }

        if( this->HaveWestNeighbor() )
        {
            // west data is non-contiguous - but CUDA has a strided write
            cudaMemcpy2D( currBuf,                      // dest
                          nPaddedCols * sizeof(T),          // dest pitch
                          flatData,                   // src
                          nPaddedCols * sizeof(T),          // src pitch
                          haloWidth * sizeof(T),      // width of data to transfer (bytes)
                          nRows,          // height of data to transfer (rows)
                          cudaMemcpyHostToDevice );   // transfer direction

        }


        // we have changed the local halo values on the device
        // we need to update the local 1-wide halo in the alt buffer
        // note we only need to update the 1-wide halo here, even if
        // our real halo width is larger
        size_t rowExtent = mtx.GetNumPaddedColumns() * sizeof(T);
        cudaMemcpy2D( altBuf,      // destination
                      rowExtent,  // destination pitch
                      currBuf,   // source
                      rowExtent,  // source pitch
                      rowExtent,  // width of data to transfer (bytes)
                      1,          // height of data to transfer (rows)
                      cudaMemcpyDeviceToDevice );
        cudaMemcpy2D( altBuf + (mtx.GetNumRows() - 1) * mtx.GetNumPaddedColumns(),      // destination
                      rowExtent,  // destination pitch
                      currBuf + (mtx.GetNumRows() - 1) * mtx.GetNumPaddedColumns(),   // source
                      rowExtent,  // source pitch
                      rowExtent,  // width of data to transfer (bytes)
                      1,          // height of data to transfer (rows)
                      cudaMemcpyDeviceToDevice );

        // copy the non-contiguous data
        cudaMemcpy2D( altBuf,      // destination
                      rowExtent,  // destination pitch
                      currBuf,   // source
                      rowExtent,  // source pitch
                      sizeof(T),  // width of data to transfer (bytes)
                      mtx.GetNumRows(),      // height of data to transfer (rows)
                      cudaMemcpyDeviceToDevice );
        cudaMemcpy2D( altBuf + (mtx.GetNumColumns() - 1),      // destination
                      rowExtent,  // destination pitch
                      currBuf + (mtx.GetNumColumns() - 1),   // source
                      rowExtent,  // source pitch
                      sizeof(T),  // width of data to transfer (bytes)
                      mtx.GetNumRows(),      // height of data to transfer (rows)
                      cudaMemcpyDeviceToDevice );
    }
}
コード例 #19
0
ファイル: ipmpx_dump.c プロジェクト: ARSekkat/gpac
GF_Err gf_ipmpx_dump_MutualAuthentication(GF_IPMPX_Data *_p, FILE *trace, u32 indent, Bool XMTDump)
{
	u32 i, count;
	GF_IPMPX_MutualAuthentication *p = (GF_IPMPX_MutualAuthentication*)_p;
	StartElement(trace, "IPMP_MutualAuthentication", indent, XMTDump);
	indent++;
	DumpBool(trace, "failedNegotiation", p->failedNegotiation, indent, XMTDump);
	if (gf_list_count(p->certificates)) DumpInt(trace, "certType", p->certType, indent, XMTDump);

	EndAttributes(trace, XMTDump, GF_TRUE);
	gf_ipmpx_dump_BaseData(_p, trace, indent, XMTDump);

	StartList(trace, "candidateAlgorithms", indent, XMTDump);
	count = gf_list_count(p->candidateAlgorithms);
	indent++;
	for (i=0; i<count; i++) {
		GF_IPMPX_Authentication *ip_auth = (GF_IPMPX_Authentication *)gf_list_get(p->candidateAlgorithms, i);
		gf_ipmpx_dump_AUTH(ip_auth, trace, indent, XMTDump);
	}
	indent--;
	EndList(trace, "candidateAlgorithms", indent, XMTDump);

	StartList(trace, "agreedAlgorithms", indent, XMTDump);
	count = gf_list_count(p->agreedAlgorithms);
	indent++;
	for (i=0; i<count; i++) {
		GF_IPMPX_Authentication *ip_auth = (GF_IPMPX_Authentication *)gf_list_get(p->agreedAlgorithms, i);
		gf_ipmpx_dump_AUTH(ip_auth, trace, indent, XMTDump);
	}
	indent--;
	EndList(trace, "agreedAlgorithms", indent, XMTDump);

	if (p->AuthenticationData) gf_ipmpx_dump_ByteArray(p->AuthenticationData, "AuthenticationData", trace, indent, XMTDump);

	count = gf_list_count(p->certificates);
	if (count || p->opaque || p->publicKey) {
		/*type 1*/
		if (count) {
			StartList(trace, "certificates", indent, XMTDump);
			for (i=0; i<count; i++) {
				GF_IPMPX_ByteArray *ipd = (GF_IPMPX_ByteArray *)gf_list_get(p->certificates, i);
				if (XMTDump) {
					gf_ipmpx_dump_ByteArray(ipd, NULL, trace, indent, XMTDump);
				} else {
					StartAttribute(trace, "", indent, GF_FALSE);
					DumpData(trace, NULL, ipd->data, ipd->length, indent, GF_FALSE);
					if (i+1<count) fprintf(trace, ",");
					fprintf(trace, "\n");
				}
			}
			EndList(trace, "certificates", indent, XMTDump);
		}
		/*type 2*/
		else if (p->publicKey) {
			gf_ipmpx_dump_AUTH((GF_IPMPX_Authentication *) p->publicKey, trace, indent, XMTDump);
		}
		/*type 0xFE*/
		else if (p->opaque) {
			gf_ipmpx_dump_ByteArray(p->opaque, "opaque", trace, indent, XMTDump);
		}
		if (!XMTDump) StartAttribute(trace, "trustData", indent, GF_FALSE);
		else {
			StartElement(trace, "trustData", indent, XMTDump);
			EndAttributes(trace, XMTDump, GF_TRUE);
		}
		gf_ipmpx_dump_data((GF_IPMPX_Data *)p->trustData, trace, indent, XMTDump);
		if (XMTDump) EndElement(trace, "trustData", indent, XMTDump);
		gf_ipmpx_dump_ByteArray(p->authCodes, "authCodes", trace, indent, XMTDump);
	}

	indent--;
	EndElement(trace, "IPMP_MutualAuthentication", indent, XMTDump);
	return GF_OK;
}
コード例 #20
0
void __cdecl main(int argc, char **argv)
{
    RPC_STATUS status;

    unsigned char * pbPicklingBuffer = NULL;

    char * pszStyle      = NULL;
    char * pszFileName   = "pickle.dat";
    int i;
    int fEncode = 1;
    int fFixedStyle = 1;

    /* allow the user to override settings with command line switches */
    for (i = 1; i < argc; i++) {
        if ((*argv[i] == '-') || (*argv[i] == '/')) {
            switch (tolower(*(argv[i]+1))) {
            case 'd':
                fEncode = 0;
                break;
            case 'e':
                fEncode = 1;
                break;
            case 'i':
                fFixedStyle = 0;
                break;
            case 'f':
                pszFileName = argv[i] + 2;
                break;
            case 'h':
            case '?':
            default:
                Usage(argv[0]);
            }
        }
        else
            Usage(argv[0]);
    }

    /* Fixed buffer style: the buffer should be big enough.  */
    /* Please note that the buffer has to be aligned at 8.   */

    pbPicklingBuffer = (unsigned char *)
            midl_user_allocate( BUFSIZE * sizeof(unsigned char));

    if ( pbPicklingBuffer == NULL ) {
        printf_s("Cannot allocate the pickling buffer\n");
        exit(1);
        }
    else
        memset( pbPicklingBuffer, 0xdd, BUFSIZE );

    /*
        Set the pickling handle that will be used for data serialization.
        The global ImplicitPicHandle is used, but it has to be set up.
    */

    if ( fEncode ) {

        unsigned char * pszNameId;
        OBJECT1         Object1;
        OBJECT2   *     pObject2;
        unsigned long   ulEncodedSize = 0;

        printf_s("\nEncoding run: use -d for decoding\n\n");

        if ( fFixedStyle ) {

            printf_s("Creating a fixed buffer encoding handle\n");
            status = MesEncodeFixedBufferHandleCreate( pbPicklingBuffer,
                                                       BUFSIZE,
                                                       & ulEncodedSize,
                                                       & ImplicitPicHandle );
            printf_s("MesEncodeFixedBufferHandleCreate returned 0x%x\n", status);
            if (status) {
                exit(status);
            }
        }
        else {

            pUserState->LastSize = 0;
            pUserState->pMemBuffer = (char *)pbPicklingBuffer;
            pUserState->pBufferStart = (char *)pbPicklingBuffer;

            printf_s("Creating an incremental encoding handle\n");
            status = MesEncodeIncrementalHandleCreate( pUserState,
                                                       PicAlloc,
                                                       PicWrite,
                                                       & ImplicitPicHandle );
            printf_s("MesEncodeIncrementalHandleCreate returned 0x%x\n", status);
            if (status) {
                exit(status);
            }
        }

        /* Creating objects to manipulate */

        pszNameId = "Procedure pickling sample";

        for (i = 0; i < ARR_SIZE; i++)
            Object1.al[i] = 0x37370000 + i;
        Object1.s = 0x4646;

        pObject2 = midl_user_allocate( sizeof(OBJECT2) + ARR_SIZE*sizeof(short) );
        if (pObject2 == NULL ) {
            printf_s("Out of memory for Object2\n");
            exit(1);
        }

        pObject2->sSize = ARR_SIZE;
        for (i = 0; i < ARR_SIZE; i++)
            pObject2->as[i] = 0x7700 + i;

        DumpData( "Data to be encoded", pszNameId, &Object1, pObject2 );

        printf_s("\nEncoding all the arguments to the buffer\n\n");
        ProcPickle( pszNameId, & Object1, pObject2 );

        printf_s("Writing the data to the file: %s\n", pszFileName);
        WriteDataToFile( pszFileName,
                         pbPicklingBuffer,
                         fFixedStyle  ? ulEncodedSize
                                      : pUserState->LastSize);

        midl_user_free( pObject2 );
    }
    else {
        char            acNameBuffer[50];
        OBJECT1         Object1;
        OBJECT2   *     pObject2;

        printf_s("\nDecoding run: use -e for encoding\n\n");

        printf_s("Reading the data from the file: %s\n\n", pszFileName );
        ReadDataFromFile( pszFileName,
                          pbPicklingBuffer,
                          BUFSIZE );

        if ( fFixedStyle ) {

            printf_s("Creating a decoding handle\n");
            status = MesDecodeBufferHandleCreate( pbPicklingBuffer,
                                                  BUFSIZE,
                                                  & ImplicitPicHandle );
            printf_s("MesDecodeFixedBufferHandleCreate returned 0x%x\n", status);
            if (status) {
                exit(status);
            }
        }
        else {

            pUserState->LastSize = 0;
            pUserState->pMemBuffer = (char *)pbPicklingBuffer;
            pUserState->pBufferStart = (char *)pbPicklingBuffer;

            printf_s("Creating an incremental decoding handle\n");
            status = MesDecodeIncrementalHandleCreate( pUserState,
                                                       PicRead,
                                                       & ImplicitPicHandle );
            printf_s("MesDecodeIncrementalHandleCreate returned 0x%x\n", status);
            if (status) {
                exit(status);
            }
        }


        /* Creating objects to manipulate */

        pObject2 = midl_user_allocate( sizeof(OBJECT2) + ARR_SIZE*sizeof(short));
        if (pObject2 == NULL ) {
            printf_s("Out of memory for Object2\n");
            exit(1);
        }

        printf_s("\nDecoding all the arguments from the buffer\n");
        ProcPickle( acNameBuffer, & Object1, pObject2 );

        DumpData( "Decoded data", acNameBuffer, &Object1, pObject2 );

        midl_user_free( pObject2 );
    }

    printf_s("\nData serialization done.\n");

    midl_user_free( pbPicklingBuffer );

    printf_s("\nFreeing the serialization handle.\n");
    status = MesHandleFree( ImplicitPicHandle );
    printf_s("MesHandleFree returned 0x%x\n", status);

    exit(0);

}  // end main()
コード例 #21
0
ファイル: EngineDump.cpp プロジェクト: Nargesf/Sumatrapdf
int main(int argc, char **argv)
{
    setlocale(LC_ALL, "C");
    DisableDataExecution();

    WStrVec argList;
    ParseCmdLine(GetCommandLine(), argList);
    if (argList.Count() < 2) {
Usage:
        ErrOut("%s [-pwd <password>][-quick][-render <path-%%d.tga>] <filename>",
            path::GetBaseName(argList.At(0)));
        return 2;
    }

    ScopedMem<WCHAR> filePath;
    WCHAR *password = NULL;
    bool fullDump = true;
    WCHAR *renderPath = NULL;
    float renderZoom = 1.f;
    bool useAlternateHandlers = false;
    bool loadOnly = false, silent = false;
#ifdef DEBUG
    int breakAlloc = 0;
#endif

    for (size_t i = 1; i < argList.Count(); i++) {
        if (str::Eq(argList.At(i), L"-pwd") && i + 1 < argList.Count() && !password)
            password = argList.At(++i);
        else if (str::Eq(argList.At(i), L"-quick"))
            fullDump = false;
        else if (str::Eq(argList.At(i), L"-render") && i + 1 < argList.Count() && !renderPath) {
            // optional zoom argument (e.g. -render 50% file.pdf)
            float zoom;
            if (i + 2 < argList.Count() && str::Parse(argList.At(i + 1), L"%f%%%$", &zoom) && zoom > 0.f) {
                renderZoom = zoom / 100.f;
                i++;
            }
            renderPath = argList.At(++i);
        }
        // -alt is for debugging alternate rendering methods
        else if (str::Eq(argList.At(i), L"-alt"))
            useAlternateHandlers = true;
        // -loadonly and -silent are only meant for profiling
        else if (str::Eq(argList.At(i), L"-loadonly"))
            loadOnly = true;
        else if (str::Eq(argList.At(i), L"-silent"))
            silent = true;
        // -full is for backward compatibility
        else if (str::Eq(argList.At(i), L"-full"))
            fullDump = true;
#ifdef DEBUG
        else if (str::Eq(argList.At(i), L"-breakalloc") && i + 1 < argList.Count())
            breakAlloc = _wtoi(argList.At(++i));
#endif
        else if (!filePath)
            filePath.Set(str::Dup(argList.At(i)));
        else
            goto Usage;
    }
    if (!filePath)
        goto Usage;

#ifdef DEBUG
    if (breakAlloc) {
        _CrtSetBreakAlloc(breakAlloc);
        if (!IsDebuggerPresent())
            MessageBox(NULL, L"Keep your debugger ready for the allocation breakpoint...", L"EngineDump", MB_ICONINFORMATION);
    }
#endif
    if (silent) {
        FILE *nul;
        freopen_s(&nul, "NUL", "w", stdout);
        freopen_s(&nul, "NUL", "w", stderr);
    }

    // optionally use GDI+ rendering for PDF/XPS
    DebugGdiPlusDevice(useAlternateHandlers);

    ScopedGdiPlus gdiPlus;
    ScopedMiniMui miniMui;

    WIN32_FIND_DATA fdata;
    HANDLE hfind = FindFirstFile(filePath, &fdata);
    // embedded documents are referred to by an invalid path
    // containing more information after a colon (e.g. "C:\file.pdf:3:0")
    if (INVALID_HANDLE_VALUE != hfind) {
        ScopedMem<WCHAR> dir(path::GetDir(filePath));
        filePath.Set(path::Join(dir, fdata.cFileName));
        FindClose(hfind);
    }

    EngineType engineType;
    PasswordHolder pwdUI(password);
    BaseEngine *engine = EngineManager::CreateEngine(filePath, &pwdUI, &engineType);
    if (!engine) {
        ErrOut("Error: Couldn't create an engine for %s!", path::GetBaseName(filePath));
        return 1;
    }
    Vec<PageAnnotation> *userAnnots = LoadFileModifications(engine->FileName());
    engine->UpdateUserAnnotations(userAnnots);
    delete userAnnots;
    if (!loadOnly)
        DumpData(engine, fullDump);
    if (renderPath)
        RenderDocument(engine, renderPath, renderZoom, silent);
    delete engine;

#ifdef DEBUG
    // report memory leaks on stderr for engines that shouldn't leak
    if (engineType != Engine_DjVu) {
        _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
        _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
        _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    }
#endif

    return 0;
}