///Seeks to the specified seekTime
void CTsReaderFilter::Seek(CRefTime& seekTime, bool seekInfile)
{
  //are we playing a rtsp:// stream?
  if (m_fileDuration != NULL)
  {
    //no, do a seek in the local file
    double startTime = m_seekTime.Millisecs();
    double duration = m_duration.Duration().Millisecs();

    startTime /= 1000.0f;
    duration /= 1000.0f;

    LogDebug("CTsReaderFilter::  Seek-> %f/%f", startTime, duration);
    //if (seekTime >= m_duration.Duration())
    //  seekTime = m_duration.Duration();
    CTsFileSeek seek(m_duration);
    seek.SetFileReader(m_fileReader);
    seek.Seek(seekTime);
  }
  else
  {
    //yes, we're playing a RTSP stream
    //stop the RTSP steam
    LogDebug("CTsReaderFilter::  Seek->stop rtsp");
    m_rtspClient.Stop();
    double startTime = m_seekTime.Millisecs();
    startTime /= 1000.0;
    double milli = m_duration.Duration().Millisecs();
    milli /= 1000.0;

    if (m_bLiveTv) startTime += 10.0; // If liveTv, it's a seek to end, force end of buffer.

    LogDebug("CTsReaderFilter::  Seek->start client from %f/ %f",startTime,milli);
    //clear the buffers
//    m_demultiplexer.Flush();
    m_buffer.Clear();
    m_buffer.Run(true);
    //start rtsp stream from the seek-time

  long Old_rtspDuration = m_rtspClient.Duration();
	if (m_rtspClient.Play(startTime, m_duration.Duration().Millisecs()/1000.0))
	{
      int loop = 0;
      while (m_buffer.Size() == 0 && loop++ <= 50 ) // lets exit the loop if no data received for 5 secs.
      {
        LogDebug("CTsReaderFilter:: Seek-->buffer empty, sleep(100ms)");
        Sleep(100);
      }
     
	  if (loop >=50)
	  {
        LogDebug("CTsReaderFilter::  Seek->start aborted");
		return ;
	  }

    //update the duration of the stream
    CPcr pcrStart, pcrEnd, pcrMax ;
    double duration = m_rtspClient.Duration() / 1000.0f ;

    if (m_bTimeShifting)
    {
      // EndPcr is continuously increasing ( until ~26 hours for rollover that will fail ! )
      // So, we refer duration to End, and just update start.
      pcrEnd   = m_duration.EndPcr() ;
      double start  = pcrEnd.ToClock() - duration;
      if (start<0) start=0 ;
      pcrStart.FromClock(start) ;
      m_duration.Set( pcrStart, pcrEnd, pcrMax) ;     // Seek()-RTSP
    }
    else
    {
      // It's a record, eventually end can increase if recording is in progress, let the end virtually updated by ThreadProc()
      //m_bRecording = (Old_rtspDuration != m_rtspClient.Duration()) ;
      m_bRecording = true; // duration may have not increased in such a short time
    }
    LogDebug("CTsReaderFilter:: Rtsp seek :Timeshift %d, Recording %d, StartPCR %f, EndPcr %f, Duration %f",m_bTimeShifting,m_bRecording,m_duration.StartPcr().ToClock(),m_duration.EndPcr().ToClock(),(float)m_duration.Duration().Millisecs()/1000.0f) ;
	}
	else
	{
      LogDebug("CTsReaderFilter::  Seek->start aborted");
	}
  }
}
int AudioDecoderCoreAudio::open() {
    std::cerr << "AudioDecoderCoreAudio::open()" << std::endl;

    //Open the audio file.
    OSStatus err;

    /** This code blocks works with OS X 10.5+ only. DO NOT DELETE IT for now. */
    /*CFStringRef urlStr = CFStringCreateWithCharacters(0,
   				reinterpret_cast<const UniChar *>(
                //qurlStr.unicode()), qurlStr.size());
                m_filename.data()), m_filename.size());
                */
    CFStringRef urlStr = CFStringCreateWithCString(kCFAllocatorDefault, 
                                                   m_filename.c_str(), 
                                                   kCFStringEncodingUTF8);
                                                   //CFStringGetSystemEncoding());

    CFURLRef urlRef = CFURLCreateWithFileSystemPath(NULL, urlStr, kCFURLPOSIXPathStyle, false);
    err = ExtAudioFileOpenURL(urlRef, &m_audioFile);
    CFRelease(urlStr);
    CFRelease(urlRef);

    /** TODO: Use FSRef for compatibility with 10.4 Tiger. 
        Note that ExtAudioFileOpen() is deprecated above Tiger, so we must maintain
        both code paths if someone finishes this part of the code.
    FSRef fsRef;
    CFURLGetFSRef(reinterpret_cast<CFURLRef>(url.get()), &fsRef);
    err = ExtAudioFileOpen(&fsRef, &m_audioFile);
    */

	if (err != noErr)
	{
        std::cerr << "AudioDecoderCoreAudio: Error opening file." << std::endl;
		return AUDIODECODER_ERROR;
	}

    // get the input file format
    CAStreamBasicDescription inputFormat;
    UInt32 size = sizeof(inputFormat);
    err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_FileDataFormat, &size, &inputFormat);
	if (err != noErr)
	{
        std::cerr << "AudioDecoderCoreAudio: Error getting file format." << std::endl;
		return AUDIODECODER_ERROR;
	}    
    m_inputFormat = inputFormat;
    
	// create the output format
	CAStreamBasicDescription outputFormat;
    bzero(&outputFormat, sizeof(AudioStreamBasicDescription));
	outputFormat.mFormatID = kAudioFormatLinearPCM;
	outputFormat.mSampleRate = inputFormat.mSampleRate;
	outputFormat.mChannelsPerFrame = 2;
    outputFormat.mFormatFlags = kAudioFormatFlagsCanonical;  
    //kAudioFormatFlagsCanonical means Native endian, float, packed on Mac OS X, 
    //but signed int for iOS instead.

    //Note iPhone/iOS only supports signed integers supposedly:
    //outputFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger;
	
    //Debugging:
    //printf ("Source File format: "); inputFormat.Print();
    //printf ("Dest File format: "); outputFormat.Print();


	/*
	switch(inputFormat.mBitsPerChannel) {
		case 16:
			outputFormat.mFormatFlags =  kAppleLosslessFormatFlag_16BitSourceData;
			break;
		case 20:
			outputFormat.mFormatFlags =  kAppleLosslessFormatFlag_20BitSourceData;
			break;
		case 24:
			outputFormat.mFormatFlags =  kAppleLosslessFormatFlag_24BitSourceData;
			break;
		case 32:
			outputFormat.mFormatFlags =  kAppleLosslessFormatFlag_32BitSourceData;
			break;
	}*/

    // get and set the client format - it should be lpcm
    CAStreamBasicDescription clientFormat = outputFormat; //We're always telling the OS to do the conversion to floats for us now
	clientFormat.mChannelsPerFrame = 2;
	clientFormat.mBytesPerFrame = sizeof(SAMPLE)*clientFormat.mChannelsPerFrame;
	clientFormat.mBitsPerChannel = sizeof(SAMPLE)*8; //16 for signed int, 32 for float;
	clientFormat.mFramesPerPacket = 1;
	clientFormat.mBytesPerPacket = clientFormat.mBytesPerFrame*clientFormat.mFramesPerPacket;
	clientFormat.mReserved = 0;
	m_clientFormat = clientFormat;
    size = sizeof(clientFormat);
    
    err = ExtAudioFileSetProperty(m_audioFile, kExtAudioFileProperty_ClientDataFormat, size, &clientFormat);
	if (err != noErr)
	{
		//qDebug() << "SSCA: Error setting file property";
        std::cerr << "AudioDecoderCoreAudio: Error setting file property." << std::endl;
		return AUDIODECODER_ERROR;
	}
	
	//Set m_iChannels and m_iNumSamples;
	m_iChannels = clientFormat.NumberChannels();

	//get the total length in frames of the audio file - copypasta: http://discussions.apple.com/thread.jspa?threadID=2364583&tstart=47
	UInt32		dataSize;
	SInt64		totalFrameCount;		
	dataSize	= sizeof(totalFrameCount); //XXX: This looks sketchy to me - Albert
	err			= ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_FileLengthFrames, &dataSize, &totalFrameCount);
	if (err != noErr)
	{
        std::cerr << "AudioDecoderCoreAudio: Error getting number of frames." << std::endl;
		return AUDIODECODER_ERROR;
	}

      //
      // WORKAROUND for bug in ExtFileAudio
      //
      
      AudioConverterRef acRef;
      UInt32 acrsize=sizeof(AudioConverterRef);
      err = ExtAudioFileGetProperty(m_audioFile, kExtAudioFileProperty_AudioConverter, &acrsize, &acRef);
      //_ThrowExceptionIfErr(@"kExtAudioFileProperty_AudioConverter", err);

      AudioConverterPrimeInfo primeInfo;
      UInt32 piSize=sizeof(AudioConverterPrimeInfo);
      memset(&primeInfo, 0, piSize);
      err = AudioConverterGetProperty(acRef, kAudioConverterPrimeInfo, &piSize, &primeInfo);
      if(err != kAudioConverterErr_PropertyNotSupported) // Only if decompressing
      {
         //_ThrowExceptionIfErr(@"kAudioConverterPrimeInfo", err);
         
         m_headerFrames=primeInfo.leadingFrames;
      }
	
	m_iNumSamples = (totalFrameCount/*-m_headerFrames*/)*m_iChannels;
	m_iSampleRate = inputFormat.mSampleRate;
	m_fDuration = m_iNumSamples / static_cast<float>(m_iSampleRate * m_iChannels);
	
    //Convert mono files into stereo
    if (inputFormat.NumberChannels() == 1)
    {
        SInt32 channelMap[2] = {0, 0}; // array size should match the number of output channels
        AudioConverterSetProperty(acRef, kAudioConverterChannelMap, 
                                    sizeof(channelMap), channelMap);
    }

	//Seek to position 0, which forces us to skip over all the header frames.
	//This makes sure we're ready to just let the Analyser rip and it'll
	//get the number of samples it expects (ie. no header frames).
	seek(0);

    return AUDIODECODER_OK;
}
Beispiel #3
0
void
asmb(void)
{
	Prog *p;
	long t, magic;
	Optab *o;
	vlong vl;

	if(debug['v'])
		Bprint(&bso, "%5.2f asm\n", cputime());
	Bflush(&bso);
	seek(cout, HEADR, 0);
	pc = INITTEXT;
	for(p = firstp; p != P; p = p->link) {
		if(p->as == ATEXT) {
			curtext = p;
			autosize = p->to.offset + 8;
			if(p->from3.type == D_CONST) {
				for(; pc < p->pc; pc++)
					CPUT(0);
			}
		}
		if(p->pc != pc) {
			diag("phase error %llux sb %llux",
				p->pc, pc);
			if(!debug['a'])
				prasm(curp);
			pc = p->pc;
		}
		curp = p;
		o = oplook(p);	/* could probably avoid this call */
		if(asmout(p, o, 0)) {
			p = p->link;
			pc += 4;
		}
		pc += o->size;
	}
	if(debug['a'])
		Bprint(&bso, "\n");
	Bflush(&bso);
	cflush();

	curtext = P;
	switch(HEADTYPE) {
	case 0:
	case 1:
	case 2:
	case 5:
	case 9:
	case 10:
		seek(cout, HEADR+textsize, 0);
		break;
	case 3:
		seek(cout, rnd(HEADR+textsize, 4), 0);
		break;
	}

	if(dlm){
		char buf[8];

		write(cout, buf, INITDAT-textsize);
		textsize = INITDAT;
	}

	for(t = 0; t < datsize; t += sizeof(buf)-100) {
		if(datsize-t > sizeof(buf)-100)
			datblk(t, sizeof(buf)-100);
		else
			datblk(t, datsize-t);
	}

	symsize = 0;
	lcsize = 0;
	if(!debug['s']) {
		if(debug['v'])
			Bprint(&bso, "%5.2f sym\n", cputime());
		Bflush(&bso);
		switch(HEADTYPE) {
		case 0:
		case 1:
		case 2:
		case 5:
		case 9:
		case 10:
			seek(cout, HEADR+textsize+datsize, 0);
			break;
		case 3:
			seek(cout, rnd(HEADR+textsize, 4)+datsize, 0);
			break;
		}
		if(!debug['s'])
			asmsym();
		if(debug['v'])
			Bprint(&bso, "%5.2f sp\n", cputime());
		Bflush(&bso);
		if(!debug['s'])
			asmlc();
		if(dlm)
			asmdyn();
		if(HEADTYPE == 0 || HEADTYPE == 1)	/* round up file length for boot image */
			if((symsize+lcsize) & 1)
				CPUT(0);
		cflush();
	}
	else if(dlm){
		asmdyn();
		cflush();
	}

	seek(cout, 0L, 0);
	switch(HEADTYPE) {
	case 0:
		lput(0x1030107);		/* magic and sections */
		lput(textsize);			/* sizes */
		lput(datsize);
		lput(bsssize);
		lput(symsize);			/* nsyms */
		lput(entryvalue());		/* va of entry */
		lput(0L);
		lput(lcsize);
		break;
	case 1:
		if(dlm)
			lput(0x80000000 | (4*21*21+7));		/* q.out magic */
		else
			lput(4*21*21+7);	/* q.out magic */
		lput(textsize);			/* sizes */
		lput(datsize);
		lput(bsssize);
		lput(symsize);			/* nsyms */
		lput(entryvalue());		/* va of entry */
		lput(0L);
		lput(lcsize);
		break;
	case 2:	/* plan9 */
		magic = 4*27*27+7;
		magic |= 0x00008000;		/* fat header */
		if(dlm)
			magic |= 0x80000000;	/* dlm */
		lput(magic);
		lput(textsize);			/* sizes */
		lput(datsize);
		lput(bsssize);
		lput(symsize);			/* nsyms */
		vl = entryvalue();
		lput(PADDR(vl));		/* va of entry (real mode on boot) */
		lput(0L);
		lput(lcsize);
		llput(vl);			/* va of entry */
		break;
	case 3:
		break;
	case 5:
		elf32(POWER, ELFDATA2MSB, 0, nil);
		break;
	case 9:					/* ELF64 Header */
	case 10:				/* A2 weirdness */
		elf64(POWER64, ELFDATA2MSB, 0, nil);
		break;
	}
	cflush();
}
size_t BlockFileInputStream::seekAndRead(offset_t pos, void* buffer, size_t bufSize)
{
    seek(pos);
    return read(buffer, bufSize);
}
Beispiel #5
0
bool DhQIODevice::Dvhseek(qint64 x1) {
  return seek(x1);
}
Beispiel #6
0
// (virtual)
int64_t IStream::skip(
    int count)
{
    return seek(count, StreamSeekOrigin::current);
}
Beispiel #7
0
// (virtual)
bool IStream::set_position(
    int64_t position)
{
    return seek(position, StreamSeekOrigin::begin) >= 0;
}
Beispiel #8
0
static int
machdotout(int fd, Fhdr *fp, ExecHdr *hp)
{
	uvlong (*swav)(uvlong);
	uint32 (*swal)(uint32);
	ushort (*swab)(ushort);
	Machhdr *mp;
	MachCmd **cmd;
	MachSymSeg *symtab;
	MachSymSeg *pclntab;
	MachSeg64 *seg;
	MachSect64 *sect;
	MachSeg32 *seg32;
	MachSect32 *sect32;
	uvlong textsize, datasize, bsssize;
	uchar *cmdbuf;
	uchar *cmdp;
	int i, hdrsize;
	uint32 textva, textoff, datava, dataoff;

	mp = &hp->e.machhdr;
	if (leswal(mp->filetype) != MACH_EXECUTABLE_TYPE) {
		werrstr("bad MACH executable type %#ux", leswal(mp->filetype));
		return 0;
	}

	swab = leswab;
	swal = leswal;
	swav = leswav;

	mp->magic = swal(mp->magic);
	mp->cputype = swal(mp->cputype);
	mp->cpusubtype = swal(mp->cpusubtype);
	mp->filetype = swal(mp->filetype);
	mp->ncmds = swal(mp->ncmds);
	mp->sizeofcmds = swal(mp->sizeofcmds);
	mp->flags = swal(mp->flags);
	mp->reserved = swal(mp->reserved);
	hdrsize = 0;

	switch(mp->magic) {
	case 0xFEEDFACE:	// 32-bit mach
		if (mp->cputype != MACH_CPU_TYPE_X86) {
			werrstr("bad MACH cpu type - not 386");
			return 0;
		}
		if (mp->cpusubtype != MACH_CPU_SUBTYPE_X86) {
			werrstr("bad MACH cpu subtype - not 386");
			return 0;
		}
		if (mp->filetype != MACH_EXECUTABLE_TYPE) {
			werrstr("bad MACH executable type");
			return 0;
		}
		mach = &mi386;
		fp->type = FI386;
		hdrsize = 28;
		break;

	case 0xFEEDFACF:	// 64-bit mach
		if (mp->cputype != MACH_CPU_TYPE_X86_64) {
			werrstr("bad MACH cpu type - not amd64");
			return 0;
		}

		if (mp->cpusubtype != MACH_CPU_SUBTYPE_X86) {
			werrstr("bad MACH cpu subtype - not amd64");
			return 0;
		}
		mach = &mamd64;
		fp->type = FAMD64;
		hdrsize = 32;
		break;

	default:
		werrstr("not mach %#ux", mp->magic);
		return 0;
	}

	cmdbuf = malloc(mp->sizeofcmds);
	seek(fd, hdrsize, 0);
	if(read(fd, cmdbuf, mp->sizeofcmds) != mp->sizeofcmds) {
		free(cmdbuf);
		return 0;
	}
	cmd = malloc(mp->ncmds * sizeof(MachCmd*));
	cmdp = cmdbuf;
	textva = 0;
	textoff = 0;
	dataoff = 0;
	datava = 0;
	symtab = 0;
	pclntab = 0;
	textsize = datasize = bsssize = 0;
	for (i = 0; i < mp->ncmds; i++) {
		MachCmd *c;

		cmd[i] = (MachCmd*)cmdp;
		c = cmd[i];
		c->type = swal(c->type);
		c->size = swal(c->size);
		switch(c->type) {
		case MACH_SEGMENT_32:
			if(mp->magic != 0xFEEDFACE) {
				werrstr("segment 32 in mach 64");
				goto bad;
			}
			seg32 = (MachSeg32*)c;
			seg32->vmaddr = swav(seg32->vmaddr);
			seg32->vmsize = swav(seg32->vmsize);
			seg32->fileoff = swav(seg32->fileoff);
			seg32->filesize = swav(seg32->filesize);
			seg32->maxprot = swal(seg32->maxprot);
			seg32->initprot = swal(seg32->initprot);
			seg32->nsects = swal(seg32->nsects);
			seg32->flags = swal(seg32->flags);
			if (strcmp(seg32->segname, "__TEXT") == 0) {
				textva = seg32->vmaddr;
				textoff = seg32->fileoff;
				sect32 = (MachSect32*)(cmdp + sizeof(MachSeg32));
				if (strcmp(sect32->sectname, "__text") == 0) {
					textsize = swal(sect32->size);
				} else {
					werrstr("no text section");
					goto bad;
				}
			}
			if (strcmp(seg32->segname, "__DATA") == 0) {
				datava = seg32->vmaddr;
				dataoff = seg32->fileoff;
				sect32 = (MachSect32*)(cmdp + sizeof(MachSeg32));
				if (strcmp(sect32->sectname, "__data") == 0) {
					datasize = swal(sect32->size);
				} else {
					werrstr("no data section");
					goto bad;
				}
				sect32++;
				if (strcmp(sect32->sectname, "__nl_symbol_ptr") == 0)
					sect32++;
				if (strcmp(sect32->sectname, "__bss") == 0) {
					bsssize = swal(sect32->size);
				} else {
					werrstr("no bss section");
					goto bad;
				}
			}
			break;

		case MACH_SEGMENT_64:
			if(mp->magic != 0xFEEDFACF) {
				werrstr("segment 32 in mach 64");
				goto bad;
			}
			seg = (MachSeg64*)c;
			seg->vmaddr = swav(seg->vmaddr);
			seg->vmsize = swav(seg->vmsize);
			seg->fileoff = swav(seg->fileoff);
			seg->filesize = swav(seg->filesize);
			seg->maxprot = swal(seg->maxprot);
			seg->initprot = swal(seg->initprot);
			seg->nsects = swal(seg->nsects);
			seg->flags = swal(seg->flags);
			if (strcmp(seg->segname, "__TEXT") == 0) {
				textva = seg->vmaddr;
				textoff = seg->fileoff;
				sect = (MachSect64*)(cmdp + sizeof(MachSeg64));
				if (strcmp(sect->sectname, "__text") == 0) {
					textsize = swav(sect->size);
				} else {
					werrstr("no text section");
					goto bad;
				}
			}
			if (strcmp(seg->segname, "__DATA") == 0) {
				datava = seg->vmaddr;
				dataoff = seg->fileoff;
				sect = (MachSect64*)(cmdp + sizeof(MachSeg64));
				if (strcmp(sect->sectname, "__data") == 0) {
					datasize = swav(sect->size);
				} else {
					werrstr("no data section");
					goto bad;
				}
				sect++;
				if (strcmp(sect->sectname, "__bss") == 0) {
					bsssize = swav(sect->size);
				} else {
					werrstr("no bss section");
					goto bad;
				}
			}
			break;
		case MACH_UNIXTHREAD:
			break;
		case MACH_SYMSEG:
			if (symtab == 0)
				symtab = (MachSymSeg*)c;
			else if (pclntab == 0)
				pclntab = (MachSymSeg*)c;
			break;
		}
		cmdp += c->size;
	}
	if (textva == 0 || datava == 0) {
		free(cmd);
		free(cmdbuf);
		return 0;
	}
	/* compute entry by taking address after header - weird - BUG? */
	settext(fp, textva+sizeof(Machhdr) + mp->sizeofcmds, textva, textsize, textoff);
	setdata(fp, datava, datasize, dataoff, bsssize);
	if(symtab != 0)
		setsym(fp, symtab->filesize, 0, pclntab? pclntab->filesize : 0, symtab->fileoff);
	free(cmd);
	free(cmdbuf);
	return 1;
bad:
	free(cmd);
	free(cmdbuf);
	return 0;
}
Beispiel #9
0
void
asmb(void)
{
	Prog *p;
	long v;
	int a;
	short *op1;

	if(debug['v'])
		Bprint(&bso, "%5.2f asmb\n", cputime());
	Bflush(&bso);

	seek(cout, HEADR, 0);
	pc = INITTEXT;
	curp = firstp;
	for(p = firstp; p != P; p = p->link) {
		if(p->as == ATEXT)
			curtext = p;
		if(p->pc != pc) {
			if(!debug['a'])
				print("%P\n", curp);
			diag("phase error %.4lux sb %.4lux in %s", p->pc, pc, TNAME);
			pc = p->pc;
		}
		curp = p;
		if(debug['a'])
			Bprint(&bso, "%lux:%P\n", pc, curp);
		asmins(p);
		if(cbc < sizeof(opa))
			cflush();
		for(op1 = opa; op1 < op; op1++) {
			a = *op1;
			*cbp++ = a >> 8;
			*cbp++ = a;
		}
		a = 2*(op - opa);
		pc += a;
		cbc -= a;
		if(debug['a']) {
			for(op1 = opa; op1 < op; op1++)
				if(op1 == opa)
					Bprint(&bso, "\t\t%4ux", *op1 & 0xffff);
				else
					Bprint(&bso, " %4ux", *op1 & 0xffff);
			if(op != opa)
				Bprint(&bso, "\n");
		}
	}
	cflush();
	switch(HEADTYPE) {
	case 0:	/* this is garbage */
		seek(cout, rnd(HEADR+textsize, 8192), 0);
		break;
	case 1:	/* plan9 boot data goes into text */
		seek(cout, rnd(HEADR+textsize, INITRND), 0);
		break;
	case 2:	/* plan 9 */
		seek(cout, HEADR+textsize, 0);
		break;
	case 3:	/* next boot */
		seek(cout, HEADR+rnd(textsize, INITRND), 0);
		break;
	case 4:	/* preprocess pilot */
		seek(cout, HEADR+textsize, 0);
		break;
	}

	if(debug['v'])
		Bprint(&bso, "%5.2f datblk\n", cputime());
	Bflush(&bso);

	for(v = 0; v < datsize; v += sizeof(buf)-100) {
		if(datsize-v > sizeof(buf)-100)
			datblk(v, sizeof(buf)-100);
		else
			datblk(v, datsize-v);
	}

	symsize = 0;
	spsize = 0;
	lcsize = 0;
	relocsize = 0;

	Bflush(&bso);

	switch(HEADTYPE) {
	default:
		seek(cout, rnd(HEADR+textsize, 8192)+datsize, 0);
		break;
	case 1:	/* plan9 boot data goes into text */
		seek(cout, rnd(HEADR+textsize, INITRND)+datsize, 0);
		break;
	case 2:	/* plan 9 */
		seek(cout, HEADR+textsize+datsize, 0);
		break;
	case 3:	/* next boot */
		seek(cout, HEADR+rnd(textsize, INITRND)+datsize, 0);
		break;
	case 4:	/* preprocess pilot */
		seek(cout, HEADR+textsize+datsize, 0);
		break;
	}
	if(!debug['s']) {
		if(debug['v'])
			Bprint(&bso, "%5.2f sym\n", cputime());
		asmsym();
	}
	Bflush(&bso);
	if(!debug['s']) {
		if(debug['v'])
			Bprint(&bso, "%5.2f sp\n", cputime());
		asmsp();
	}
	Bflush(&bso);
	if(!debug['s']) {
		if(debug['v'])
			Bprint(&bso, "%5.2f pc\n", cputime());
		asmlc();
	}
	Bflush(&bso);
	if(!debug['s']) {
		if(debug['v'])
			Bprint(&bso, "%5.2f reloc\n", cputime());
		asmreloc();
	}
	cflush();

	if(debug['v'])
		Bprint(&bso, "%5.2f headr\n", cputime());
	Bflush(&bso);
	seek(cout, 0L, 0);
	switch(HEADTYPE) {
	default:
		lput(0x160L<<16);		/* magic and sections */
		lput(0L);			/* time and date */
		lput(rnd(HEADR+textsize, 4096)+datsize);
		lput(symsize);			/* nsyms */
		lput((0x38L<<16)|7L);		/* size of optional hdr and flags */
		lput((0413<<16)|0437L);		/* magic and version */
		lput(rnd(HEADR+textsize, 4096));	/* sizes */
		lput(datsize);
		lput(bsssize);
		lput(entryvalue());		/* va of entry */
		lput(INITTEXT-HEADR);		/* va of base of text */
		lput(INITDAT);			/* va of base of data */
		lput(INITDAT+datsize);		/* va of base of bss */
		lput(~0L);			/* gp reg mask */
		lput(0L);
		lput(0L);
		lput(0L);
		lput(0L);
		lput(~0L);			/* gp value ?? */
		break;
	case 1:	/* plan9 boot data goes into text */
		lput(0407);			/* magic */
		lput(rnd(HEADR+textsize, INITRND)-HEADR+datsize);		/* sizes */
		lput(0);
		lput(bsssize);
		lput(symsize);			/* nsyms */
		lput(entryvalue());		/* va of entry */
		lput(spsize);			/* sp offsets */
		lput(lcsize);			/* line offsets */
		break;
	case 2:	/* plan 9 */
		lput(0407);			/* magic */
		lput(textsize);			/* sizes */
		lput(datsize);
		lput(bsssize);
		lput(symsize);			/* nsyms */
		lput(entryvalue());		/* va of entry */
		lput(spsize);			/* sp offsets */
		lput(lcsize);			/* line offsets */
		break;
	case 3:	/* next boot */
		/* header */
		lput(0xfeedfaceL);			/* magic */
		lput(6);				/* 68040 */
		lput(1);				/* more 68040 */
		lput(5);				/* file type 'boot' */
		lput(HEADTYPE);				/* number commands */
		lput(HEADR-7*4);			/* sizeof commands */
		lput(1);				/* no undefineds */
		/* command 1 text */
		lput(1);				/* command = 'segment' */
		lput(124);				/* command size */
		s16put("__TEXT");
			/* botch?? entryvalue() */
		lput(INITTEXT);				/* va of start */
		lput(rnd(textsize, 8192));		/* va size */
		lput(HEADR);				/* file offset */
		lput(rnd(textsize, 8192));		/* file size */
		lput(7);				/* max prot */
		lput(7);				/* init prot */
		lput(1);				/* number of sections */
		lput(0);				/* flags */
		/* text section */
		s16put("__text");
		s16put("__TEXT");
			/* botch?? entryvalue() */
		lput(INITTEXT);				/* va of start */
		lput(textsize);				/* va size */
		lput(HEADR);				/* file offset */
		lput(2);				/* align */
		lput(0);				/* reloff */
		lput(0);				/* nreloc */
		lput(0);				/* flags */
		lput(0);				/* reserved1 */
		lput(0);				/* reserved2 */
		/* command 1 data */
		lput(1);				/* command = 'segment' */
		lput(192);				/* command size */
		s16put("__DATA");
		lput(INITDAT);				/* va of start */
		lput(rnd(datsize, 8192));		/* va size */
		lput(HEADR+rnd(textsize, 8192));	/* file offset */
		lput(rnd(datsize, 8192));		/* file size */
		lput(7);				/* max prot */
		lput(7);				/* init prot */
		lput(2);				/* number of sections */
		lput(0);				/* flags */
		/* data section */
		s16put("__data");
		s16put("__DATA");
		lput(INITDAT);				/* va of start */
		lput(datsize);				/* va size */
		lput(HEADR+rnd(textsize, 8192));	/* file offset */
		lput(2);				/* align */
		lput(0);				/* reloff */
		lput(0);				/* nreloc */
		lput(0);				/* flags */
		lput(0);				/* reserved1 */
		lput(0);				/* reserved2 */
		/* bss section */
		s16put("__bss");
		s16put("__DATA");
		lput(INITDAT+datsize);			/* va of start */
		lput(bsssize);				/* va size */
		lput(0);				/* file offset */
		lput(2);				/* align */
		lput(0);				/* reloff */
		lput(0);				/* nreloc */
		lput(1);				/* flags = zero fill */
		lput(0);				/* reserved1 */
		lput(0);				/* reserved2 */
		/* command 2 symbol */
		lput(2);				/* command = 'symbol' */
		lput(24);				/* command size */
		lput(HEADR+rnd(textsize, INITRND)
			+datsize);			/* symoff */
		lput(symsize);				/* nsyms */
		lput(spsize);				/* sp offsets */
		lput(lcsize);				/* line offsets */
		break;
	case 4:	/* preprocess pilot */
		lput(0407);			/* magic */
		lput(textsize);			/* sizes */
		lput(datsize);
		lput(bsssize);
		lput(symsize);			/* nsyms */
		lput(entryvalue());		/* va of entry */
		lput(spsize);			/* sp offsets */
		lput(lcsize);			/* line offsets */
		lput(relocsize);		/* relocation */
		break;
	}
	cflush();
}
Beispiel #10
0
int
crackhdr(int fd, Fhdr *fp)
{
	ExecTable *mp;
	ExecHdr d;
	int nb, ret;
	uint32 magic;

	fp->type = FNONE;
	nb = read(fd, (char *)&d.e, sizeof(d.e));
	if (nb <= 0)
		return 0;

	ret = 0;
	magic = beswal(d.e.exechdr.magic);		/* big-endian */
	for (mp = exectab; mp->magic; mp++) {
		if (nb < mp->hsize)
			continue;

		/*
		 * The magic number has morphed into something
		 * with fields (the straw was DYN_MAGIC) so now
		 * a flag is needed in Fhdr to distinguish _MAGIC()
		 * magic numbers from foreign magic numbers.
		 *
		 * This code is creaking a bit and if it has to
		 * be modified/extended much more it's probably
		 * time to step back and redo it all.
		 */
		if(mp->_magic){
			if(mp->magic != (magic & ~DYN_MAGIC))
				continue;

			if(mp->magic == V_MAGIC)
				mp = couldbe4k(mp);

			if ((magic & DYN_MAGIC) && mp->dlmname != nil)
				fp->name = mp->dlmname;
			else
				fp->name = mp->name;
		}
		else{
			if(mp->magic != magic)
				continue;
			fp->name = mp->name;
		}
		fp->type = mp->type;
		fp->hdrsz = mp->hsize;		/* will be zero on bootables */
		fp->_magic = mp->_magic;
		fp->magic = magic;

		mach = mp->mach;
		if(mp->swal != nil)
			hswal(&d, sizeof(d.e)/sizeof(uint32), mp->swal);
		ret = mp->hparse(fd, fp, &d);
		seek(fd, mp->hsize, 0);		/* seek to end of header */
		break;
	}
	if(mp->magic == 0)
		werrstr("unknown header type");
	return ret;
}
Beispiel #11
0
static int
elfdotout(int fd, Fhdr *fp, ExecHdr *hp)
{

	uint32 (*swal)(uint32);
	ushort (*swab)(ushort);
	Ehdr32 *ep;
	Phdr32 *ph;
	int i, it, id, is, phsz, shsz;
	Shdr32 *sh;

	/* bitswap the header according to the DATA format */
	ep = &hp->e.elfhdr32;
	if(ep->ident[CLASS] != ELFCLASS32) {
		return elf64dotout(fd, fp, hp);
	}
	if(ep->ident[DATA] == ELFDATA2LSB) {
		swab = leswab;
		swal = leswal;
	} else if(ep->ident[DATA] == ELFDATA2MSB) {
		swab = beswab;
		swal = beswal;
	} else {
		werrstr("bad ELF encoding - not big or little endian");
		return 0;
	}

	ep->type = swab(ep->type);
	ep->machine = swab(ep->machine);
	ep->version = swal(ep->version);
	ep->elfentry = swal(ep->elfentry);
	ep->phoff = swal(ep->phoff);
	ep->shoff = swal(ep->shoff);
	ep->flags = swal(ep->flags);
	ep->ehsize = swab(ep->ehsize);
	ep->phentsize = swab(ep->phentsize);
	ep->phnum = swab(ep->phnum);
	ep->shentsize = swab(ep->shentsize);
	ep->shnum = swab(ep->shnum);
	ep->shstrndx = swab(ep->shstrndx);
	if(ep->type != EXEC || ep->version != CURRENT)
		return 0;

	/* we could definitely support a lot more machines here */
	fp->magic = ELF_MAG;
	fp->hdrsz = (ep->ehsize+ep->phnum*ep->phentsize+16)&~15;
	switch(ep->machine) {
	case I386:
		mach = &mi386;
		fp->type = FI386;
		break;
	case MIPS:
		mach = &mmips;
		fp->type = FMIPS;
		break;
	case SPARC64:
		mach = &msparc64;
		fp->type = FSPARC64;
		break;
	case POWER:
		mach = &mpower;
		fp->type = FPOWER;
		break;
	case ARM:
		mach = &marm;
		fp->type = FARM;
		break;
	default:
		return 0;
	}

	if(ep->phentsize != sizeof(Phdr32)) {
		werrstr("bad ELF header size");
		return 0;
	}
	phsz = sizeof(Phdr32)*ep->phnum;
	ph = malloc(phsz);
	if(!ph)
		return 0;
	seek(fd, ep->phoff, 0);
	if(read(fd, ph, phsz) < 0) {
		free(ph);
		return 0;
	}
	hswal(ph, phsz/sizeof(uint32), swal);

	shsz = sizeof(Shdr32)*ep->shnum;
	sh = malloc(shsz);
	if(sh) {
		seek(fd, ep->shoff, 0);
		if(read(fd, sh, shsz) < 0) {
			free(sh);
			sh = 0;
		} else
			hswal(sh, shsz/sizeof(uint32), swal);
	}

	/* find text, data and symbols and install them */
	it = id = is = -1;
	for(i = 0; i < ep->phnum; i++) {
		if(ph[i].type == LOAD
		&& (ph[i].flags & (R|X)) == (R|X) && it == -1)
			it = i;
		else if(ph[i].type == LOAD
		&& (ph[i].flags & (R|W)) == (R|W) && id == -1)
			id = i;
		else if(ph[i].type == NOPTYPE && is == -1)
			is = i;
	}
	if(it == -1 || id == -1) {
		/*
		 * The SPARC64 boot image is something of an ELF hack.
		 * Text+Data+BSS are represented by ph[0].  Symbols
		 * are represented by ph[1]:
		 *
		 *		filesz, memsz, vaddr, paddr, off
		 * ph[0] : txtsz+datsz, txtsz+datsz+bsssz, txtaddr-KZERO, datasize, txtoff
		 * ph[1] : symsz, lcsz, 0, 0, symoff
		 */
		if(ep->machine == SPARC64 && ep->phnum == 2) {
			uint32 txtaddr, txtsz, dataddr, bsssz;

			txtaddr = ph[0].vaddr | 0x80000000;
			txtsz = ph[0].filesz - ph[0].paddr;
			dataddr = txtaddr + txtsz;
			bsssz = ph[0].memsz - ph[0].filesz;
			settext(fp, ep->elfentry | 0x80000000, txtaddr, txtsz, ph[0].offset);
			setdata(fp, dataddr, ph[0].paddr, ph[0].offset + txtsz, bsssz);
			setsym(fp, ph[1].filesz, 0, ph[1].memsz, ph[1].offset);
			free(ph);
			return 1;
		}

		werrstr("No TEXT or DATA sections");
error:
		free(sh);
		free(ph);
		return 0;
	}

	settext(fp, ep->elfentry, ph[it].vaddr, ph[it].memsz, ph[it].offset);
	setdata(fp, ph[id].vaddr, ph[id].filesz, ph[id].offset, ph[id].memsz - ph[id].filesz);
	if(is != -1)
		setsym(fp, ph[is].filesz, 0, ph[is].memsz, ph[is].offset);
	else if(sh != 0){
		char *buf;
		uvlong symsize = 0;
		uvlong symoff = 0;
		uvlong pclnsz = 0;

		/* load shstrtab names */
		buf = malloc(sh[ep->shstrndx].size);
		if (buf == 0)
			goto done;
		memset(buf, 0, sizeof buf);
		seek(fd, sh[ep->shstrndx].offset, 0);
		read(fd, buf, sh[ep->shstrndx].size);

		for(i = 0; i < ep->shnum; i++) {
			if (strcmp(&buf[sh[i].name], ".gosymtab") == 0) {
				symsize = sh[i].size;
				symoff = sh[i].offset;
			}
			if (strcmp(&buf[sh[i].name], ".gopclntab") == 0) {
				if (sh[i].offset != symoff+symsize) {
					werrstr("pc line table not contiguous with symbol table");
					free(buf);
					goto error;
				}
				pclnsz = sh[i].size;
			}
		}
		setsym(fp, symsize, 0, pclnsz, symoff);
		free(buf);
	}
done:
	free(sh);
	free(ph);
	return 1;
}
Beispiel #12
0
        void initFileObject(lua_State* L)
        {
            luaL_newmetatable(L, meta<File>());
            // Duplicate the metatable on the stack.
            lua_pushvalue(L, -1);
            // metatable.__index = metatable
            lua_setfield(L, -2, "__index");

            // Put the members into the metatable.
            const luaL_Reg functions[] = {
                {"__gc", [](lua_State* L) { return script::wrapped<File>(L, 1)->gc(L); }},
                {"__index", [](lua_State* L) { return script::wrapped<File>(L, 1)->index(L); }},
                {"__newindex", [](lua_State* L) { return script::wrapped<File>(L, 1)->newindex(L); }},
                {"__tostring", [](lua_State* L) { return script::wrapped<File>(L, 1)->tostring(L); }},
                {"__pairs", [](lua_State* L) { return script::wrapped<File>(L, 1)->pairs(L); }},
                {"close", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    file->close();
                    return 0;
                }},
                {"readUnsigned8", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    uint8_t value;
                    if(file->readUnsigned8(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readUnsigned16", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    uint16_t value;
                    if(file->readUnsigned16(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readUnsigned32", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    uint32_t value;
                    if(file->readUnsigned32(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readInt8", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    int8_t value;
                    if(file->readInt8(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readInt16", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    int16_t value;
                    if(file->readInt16(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readInt32", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    int32_t value;
                    if(file->readInt32(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readFloat", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    float value;
                    if(file->readFloat(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readDouble", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    double value;
                    if(file->readDouble(value))
                    {
                        script::push(L, value);
                        return 1;
                    }
                    return 0;
                }},
                {"readString", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto blockSize = script::get<int>(L, 2);

                    std::string buffer(blockSize, 0);
                    if(file->readString(buffer))
                    {
                        lua_pushlstring(L, buffer.data(), buffer.size());
                        return 1;
                    }
                    return 0;
                }},
                {"readLine", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    std::string value;
                    if(file->readLine(value))
                    {
                        script::push(L, value.c_str());
                        return 1;
                    }
                    return 0;
                }},
                {"readFully", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);

                    // Get current position.
                    auto pos = file->tell();
                    if(pos == -1)
                    {
                        return 0;
                    }

                    // Length to read = position of end - current.
                    auto length = 0;
                    if(!file->seek(pos, FileSeekMode::End))
                    {
                        return 0;
                    }
                    length = file->tell() - pos;
                    if(!file->seek(pos, FileSeekMode::Start))
                    {
                        return 0;
                    }

                    // Read the entire file into a string.
                    std::string buf(length, 0);
                    if(file->readString(buf))
                    {
                        lua_pushlstring(L, buf.data(), buf.size());
                        return 1;
                    }
                    return 0;
                }},
                {"writeUnsigned8", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeUnsigned8(value));
                    return 1;
                }},
                {"writeUnsigned16", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeUnsigned16(value));
                    return 1;
                }},
                {"writeUnsigned32", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeUnsigned32(value));
                    return 1;
                }},
                {"writeInt8", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeInt8(value));
                    return 1;
                }},
                {"writeInt16", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeInt16(value));
                    return 1;
                }},
                {"writeInt32", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<int>(L, 2);

                    script::push(L, file->writeInt32(value));
                    return 1;
                }},
                {"writeFloat", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<double>(L, 2);

                    script::push(L, file->writeFloat((float) value));
                    return 1;
                }},
                {"writeDouble", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto value = script::get<double>(L, 2);

                    script::push(L, file->writeDouble(value));
                    return 1;
                }},
                {"writeString", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    size_t length = 0;
                    const char* buffer = luaL_checklstring(L, 2, &length);
                    std::string value(buffer, buffer + length);
                    script::push(L, file->writeString(value));
                    return 1;
                }},
                {"writeLine", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    size_t length = 0;
                    const char* buffer = luaL_checklstring(L, 2, &length);
                    std::string value(buffer, buffer + length);
                    script::push(L, file->writeLine(value));
                    return 1;
                }},
                {"tell", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    script::push(L, int(file->tell()));
                    return 1;
                }},
                {"seek", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    auto position = script::get<int>(L, 2);
                    auto mode = FileSeekMode(script::get<int>(L, 3));
                    script::push(L, file->seek(position, mode));
                    return 1;
                }},
                {"flush", [](lua_State* L)
                {
                    auto file = script::ptr<File>(L, 1);
                    file->flush();
                    return 0;
                }},
                {nullptr, nullptr},
            };
            luaL_setfuncs(L, functions, 0);

            lua_pop(L, 1);
                
            // Push plum namespace.
            lua_getglobal(L, "plum");

            // plum.File = <function create>
            script::push(L, "File");
            lua_pushcfunction(L, [](lua_State* L)
            {
                auto filename = script::get<const char*>(L, 1);
                auto mode = FileOpenMode(script::get<int>(L, 2));
                auto f = new File(filename, mode);
                // Failure.
                if(!f->isActive())
                {    
                    delete f;
                    return 0;
                }

                script::push(L, f, LUA_NOREF);
                return 1;
            });
            lua_settable(L, -3);

            // Pop plum namespace.
            lua_pop(L, 1);
        }
Beispiel #13
0
void ServerNetworkHandler::inMessage(std::string pMessage, int pSocket){
	pMessage = Tokenizer::cleanEntry(pMessage);
	std::string command = Tokenizer::getCommandSpace(pMessage, 1);
	if (_sessionID == -1 && command != "connect" && command != "adduser"){
		outMessage("?Error: No se ha inciado sesión\n", pSocket);
	} else {

		std::string param = Tokenizer::getParameters(pMessage);
		std::cout<<param<<std::endl;
		if (command == "get"){
			get(param, pSocket);

		} else if (command == "cd"){
			cd(param, pSocket);
		
		} else if (command == "rm"){
			rm(param, pSocket);

		} else if (command == "touch"){
			touch(param, pSocket);

		} else if (command == "connect"){
			connect(param, pSocket);

		} else if (command == "mkdir"){
			mkdir(param, pSocket);

		} else if (command == "adduser"){
			adduser(param, pSocket);

		} else if (command == "openfile"){
			openfile(param, pSocket);

		} else if (command == "appendReg"){
			appendReg(param, pSocket);

		} else if (command == "delReg"){

			if (param == ""){
				delActualReg(pSocket);
			} else {
				delReg(param, pSocket);
			}
		
		} else if (command == "write"){
			write(param, pSocket);
		
		} else if (command == "seek"){
			seek(param, pSocket);
		
		} else if (command == "addReg"){
			addReg(param, pSocket);
		
		} else if (command == "read"){

			if (param == ""){
				readActual(pSocket);
			} else {
				readRegister(param, pSocket);
			}

		} else if (command == "close"){
			close(pSocket);
		} else if (command == "consoleMode"){
			consoleMode(param, pSocket);
		} else {
			outMessage("?Error: No se ha encontrado la instrucción " + command + '\n', pSocket);
		}
		consoleUI(pSocket);
	}
}
Beispiel #14
0
BOOL LASreaderQFIT::open(ByteStreamIn* stream)
{
  U32 i;

  if (stream == 0)
  {
    fprintf(stderr,"ERROR: ByteStreamIn* pointer is zero\n");
    return FALSE;
  }

  this->stream = stream;

  // read the QFIT header

  try { stream->get32bitsLE((U8*)&version); } catch(...)
  {
    fprintf(stderr,"ERROR: reading QFIT header\n");
    return FALSE;
  }

  // is QFIT file little-endian

  if (version == 40 || version == 48 || version == 56)
  {
    little_endian = TRUE;
    endian_swap = (IS_LITTLE_ENDIAN() == FALSE);
  }
  else
  {
    ENDIAN_SWAP_32((U8*)&version);
    if (version == 40 || version == 48 || version == 56)
    {
      little_endian = FALSE;
      endian_swap = (IS_LITTLE_ENDIAN() == TRUE);
    }
    else
    {
      fprintf(stderr,"ERROR: corrupt QFIT header.\n");
      return FALSE;
    }
  }

  // read version bytes until point start offset

  try { stream->getBytes((U8*)buffer, version); } catch(...)
  {
    fprintf(stderr,"ERROR: reading %d bytes until point start offset from QFIT header\n", version);
    return FALSE;
  }

  // read point start offset

  try { if (little_endian) stream->get32bitsLE((U8*)&offset); else stream->get32bitsBE((U8*)&offset); } catch(...)
  {
    fprintf(stderr,"ERROR: reading point start offset from QFIT header\n");
    return FALSE;
  }

  // seek to end of file find out number of points

  stream->seekEnd();
  npoints = (stream->tell() - offset) / version;

  // seek back to start of points

  stream->seek(offset);

  // populate the header as much as possible

  sprintf(header.system_identifier, "LAStools (c) by Martin Isenburg");
  sprintf(header.generating_software, "via LASreaderQFIT (%d)", LAS_TOOLS_VERSION);

  header.number_of_point_records = (U32)npoints;
  header.number_of_points_by_return[0] = header.number_of_point_records;

  header.extended_number_of_point_records = npoints;
  header.extended_number_of_points_by_return[0] = npoints;

  header.x_scale_factor = 0.000001;
  header.y_scale_factor = 0.000001;
  header.z_scale_factor = 0.001;
  header.x_offset = 0;
  header.y_offset = 0;
  header.z_offset = 0;

  try { 
    LASattribute scan_azimuth(LAS_ATTRIBUTE_I32, "scan azimuth", "Scan Azimuth (degrees X 1,000)");
    scan_azimuth.set_scale(0.001);
    scan_azimuth.set_min(0);
    scan_azimuth.set_max(360000);
    header.add_extra_attribute(scan_azimuth);
  }
  catch(...) {
    fprintf(stderr,"ERROR: initializing attribute scan_azimuth\n");
    return FALSE;
  }


  try { 
    LASattribute pitch(LAS_ATTRIBUTE_I32, "pitch", "Pitch (degrees X 1,000)");
    pitch.set_scale(0.001);
    pitch.set_min(-90000);
    pitch.set_max(90000);
    header.add_extra_attribute(pitch);
  }
  catch(...) {
    fprintf(stderr,"ERROR: initializing attribute pitch\n");
    return FALSE;
  }


  try { 
    LASattribute roll(LAS_ATTRIBUTE_I32, "roll", "Roll (degrees X 1,000)");
    roll.set_scale(0.001);
    roll.set_min(-90000);
    roll.set_max(90000);
    header.add_extra_attribute(roll);
  }
  catch(...) {
    fprintf(stderr,"ERROR: initializing attribute roll\n");
    return FALSE;
  }

  if (version == 48)
  {
    try { 
      LASattribute pulse_width(LAS_ATTRIBUTE_U8, "pulse width", "Pulse Width (digitizer samples)");
      header.add_extra_attribute(pulse_width);
    }
    catch(...) {
      fprintf(stderr,"ERROR: initializing attribute pulse width\n");
      return FALSE;
    }
  }

  header.update_extra_bytes_vlr();

  // set point type

  header.point_data_format = 1;
  header.point_data_record_length = 28 + header.get_total_extra_attributes_size();

  // initialize point

  point.init(&header, header.point_data_format, header.point_data_record_length, &header);

  // initialize extra attribute offsets

  scan_azimuth_array_offset = point.attributer->get_extra_attribute_array_offset("scan azimuth");
  pitch_array_offset = point.attributer->get_extra_attribute_array_offset("pitch");
  roll_array_offset = point.attributer->get_extra_attribute_array_offset("roll");
  if (version == 48)
  {
    pulse_width_array_offset = point.attributer->get_extra_attribute_array_offset("pulse width");
  }

  // set point count to zero

  p_count = 0;

  // approximate bounding box init

  populated_header = FALSE;

  if (!read_point()) return FALSE;

  header.min_x = header.max_x = point.get_x();
  header.min_y = header.max_y = point.get_y();
  header.min_z = header.max_z = point.get_z();

  for (i = header.number_of_point_records/50; i < header.number_of_point_records; i += header.number_of_point_records/50)
  {
    if (!seek(i)) return FALSE;
    if (!read_point()) return FALSE;
  }

  return seek(0);
}
Beispiel #15
0
	virtual void writeat(uint64_t pos, const uint8_t* buf, size_t n) {
		seek(pos);
		write(buf, n);
	}
Beispiel #16
0
void GMAudioPlayer::setPosition(FXuint position) {
  if (time.length>0) {
    seek(FXMIN(1.0,(position/(double)time.length)));
    }
  }
Beispiel #17
0
bool
FFmpegInput::open (const std::string &name, ImageSpec &spec)
{
    // Temporary workaround: refuse to open a file whose name does not
    // indicate that it's a movie file. This avoids the problem that ffmpeg
    // is willing to open tiff and other files better handled by other
    // plugins. The better long-term solution is to replace av_register_all
    // with our own function that registers only the formats that we want
    // this reader to handle. At some point, we will institute that superior
    // approach, but in the mean time, this is a quick solution that 90%
    // does the job.
    bool valid_extension = false;
    for (int i = 0; ffmpeg_input_extensions[i]; ++i)
        if (Strutil::ends_with (name, ffmpeg_input_extensions[i])) {
            valid_extension = true;
            break;
        }
    if (! valid_extension) {
        error ("\"%s\" could not open input", name);
        return false;
    }

    static boost::once_flag init_flag = BOOST_ONCE_INIT;
    boost::call_once (&av_register_all, init_flag);
    const char *file_name = name.c_str();
    av_log_set_level (AV_LOG_FATAL);
    if (avformat_open_input (&m_format_context, file_name, NULL, NULL) != 0) // avformat_open_input allocs format_context
    {
        error ("\"%s\" could not open input", file_name);
        return false;
    }
    if (avformat_find_stream_info (m_format_context, NULL) < 0)
    {
        error ("\"%s\" could not find stream info", file_name);
        return false;
    }
    m_video_stream = -1;
    for (unsigned int i=0; i<m_format_context->nb_streams; i++) {
        if (m_format_context->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
            if (m_video_stream < 0) {
                m_video_stream=i;
            }
            m_video_indexes.push_back (i); // needed for later use
            break;
        }
    }  
    if (m_video_stream == -1) {
        error ("\"%s\" could not find a valid videostream", file_name);
        return false;
    }
    m_codec_context = m_format_context->streams[m_video_stream]->codec; // codec context for videostream
    m_codec = avcodec_find_decoder (m_codec_context->codec_id);
    if (!m_codec) {
        error ("\"%s\" unsupported codec", file_name);
        return false;
    }
    if (avcodec_open2 (m_codec_context, m_codec, NULL) < 0) {
        error ("\"%s\" could not open codec", file_name);
        return false;
    }
    if (!strcmp (m_codec_context->codec->name, "mjpeg") ||
        !strcmp (m_codec_context->codec->name, "dvvideo")) {
        m_offset_time = false;
    }
    m_codec_cap_delay = m_codec_context->codec->capabilities & CODEC_CAP_DELAY ;

    AVStream *stream = m_format_context->streams[m_video_stream];
    if (stream->r_frame_rate.num != 0 && stream->r_frame_rate.den != 0) {
        m_frame_rate = stream->r_frame_rate;
    }

    m_frames = stream->nb_frames;
    m_start_time = stream->start_time;
    if (!m_frames) {
        seek (0);
        AVPacket pkt;
        av_init_packet (&pkt);
        av_read_frame (m_format_context, &pkt);
        int64_t first_pts = pkt.pts;
        int64_t max_pts = 0 ;
        av_free_packet (&pkt); //because seek(int) uses m_format_context
        seek (1 << 29);
        av_init_packet (&pkt); //Is this needed?
        while (stream && av_read_frame (m_format_context, &pkt) >= 0) {
            int64_t current_pts = static_cast<int64_t> (av_q2d(stream->time_base) * (pkt.pts - first_pts) * fps());
            if (current_pts > max_pts) {
                max_pts = current_pts +1;
            }
            av_free_packet (&pkt); //Always free before format_context usage
        }
        m_frames = max_pts;
    }
    m_frame = av_frame_alloc();
    m_rgb_frame = av_frame_alloc();
    m_rgb_buffer.resize(
        avpicture_get_size (AV_PIX_FMT_RGB24,
        m_codec_context->width,
        m_codec_context->height),
        0
    );
    AVPixelFormat pixFormat;
    switch (m_codec_context->pix_fmt) { // deprecation warning for YUV formats
        case AV_PIX_FMT_YUVJ420P:
            pixFormat = AV_PIX_FMT_YUV420P;
            break;
        case AV_PIX_FMT_YUVJ422P:
            pixFormat = AV_PIX_FMT_YUV422P;
            break;
        case AV_PIX_FMT_YUVJ444P:
            pixFormat = AV_PIX_FMT_YUV444P;
            break;
        case AV_PIX_FMT_YUVJ440P:
            pixFormat = AV_PIX_FMT_YUV440P;
        default:
            pixFormat = m_codec_context->pix_fmt;
            break;
    }
    m_sws_rgb_context = sws_getContext(
        m_codec_context->width,
        m_codec_context->height,
        pixFormat,
        m_codec_context->width,
        m_codec_context->height,
        AV_PIX_FMT_RGB24,
        SWS_AREA,
        NULL,
        NULL,
        NULL
    );
    m_spec = ImageSpec (m_codec_context->width, m_codec_context->height, 3, TypeDesc::UINT8);
    AVDictionaryEntry *tag = NULL;
    while ((tag = av_dict_get (m_format_context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
        m_spec.attribute (tag->key, tag->value);
    }
    m_spec.attribute ("FramesPerSecond", m_frame_rate.num / static_cast<float> (m_frame_rate.den));
    m_spec.attribute ("oiio:Movie", true);
    m_nsubimages = m_frames;
    spec = m_spec;
    return true;
}
static void
safe_seek(int fd, off_t pos, int whence) {
    int ret = seek(fd, pos, whence);
    assert(ret == 0);
}
Beispiel #19
0
// (virtual)
int64_t IStream::get_position()
{
    return seek(0, StreamSeekOrigin::current);
}
Beispiel #20
0
DbDataReader::SEEK_RESULT DbSqlCeDataReader::read()
{
	return seek( 1 );
}
Beispiel #21
0
PlayerWidget::PlayerWidget( int index, Database *database,
                            ControlWidget *controlWidget, Qt::WindowFlags flags )
: QWidget( controlWidget, flags )
, mPlayer( index )
, mpDatabase( database )
, mpControlWidget( controlWidget )
, mpScrollLine( new ScrollLine( this ) )
, mpStatusDisplay( new QLabel( this ) )
, mpTimeDisplay( new QLabel( this ) )
, mpPlayPosition( new TimeSlider( Qt::Horizontal, this ) )
, mpSocket( new QTcpSocket( this ) )
, mpFSM( new PlayerFSM( this ) )
, mStartOther( false )
, mAutoPlay( false )
, mTotalTime( 0 )
, mFrequency( 44100 )
, mSamples( 0 )
, mHeadStart( 10 )
, mUpdateSlider( true )
, mKioskMode( false )
, mDisplayPattern()
, mTrackInfo()
{
   QVBoxLayout *mainLayout = new QVBoxLayout( this );

   mainLayout->setContentsMargins( 0, 0, 0, 0 );
   mainLayout->setSpacing( 5 );
   mainLayout->addWidget( mpScrollLine );
   mainLayout->addWidget( mpTimeDisplay );
   mainLayout->addWidget( mpStatusDisplay );
   mainLayout->addWidget( mpPlayPosition );
   setLayout( mainLayout );

   mpStatusDisplay->setAlignment( Qt::AlignLeft );
   mpStatusDisplay->setFrameShape( QFrame::Box );
   mpStatusDisplay->setContextMenuPolicy( Qt::CustomContextMenu );
   mpStatusDisplay->setObjectName( QString("StatusLabel") );
   mpTimeDisplay->setAlignment( Qt::AlignRight );
   mpTimeDisplay->setFrameShape( QFrame::Box );
   mpTimeDisplay->setObjectName( QString("TimeLabel") );
   mpPlayPosition->setTickPosition( QSlider::TicksBelow );
   mpPlayPosition->setTickInterval( 60 );
   mpPlayPosition->setMaximum( 1 );

   connect( mpSocket, SIGNAL(connected()),
            this, SLOT(handleConnect()) );
   connect( mpSocket, SIGNAL(disconnected()),
            this, SLOT(handleDisconnect()) );
   connect( mpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(handleError(QAbstractSocket::SocketError)) );
   connect( mpSocket, SIGNAL(readyRead()),
            this, SLOT(handleResponse()) );

   connect( mpPlayPosition, SIGNAL(sliderPressed()),
            this, SLOT(lock()) );
   connect( mpPlayPosition, SIGNAL(sliderReleased()),
            this, SLOT(seek()) );
   connect( mpPlayPosition, SIGNAL(actionTriggered(int)),
            this, SLOT(playPosChange(int)) );
   connect( mpStatusDisplay, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(unload()) );

   mpFSM->changeState( PlayerFSM::disconnected );
}
Beispiel #22
0
DbDataReader::SEEK_RESULT DbSqlCeDataReader::prev_read()
{
	return seek( -1 );
}
Beispiel #23
0
void Seq::rewindStart()
      {
      seek(0);
      }
    TEST_FIXTURE(append_blob_test_base, append_block)
    {
        const size_t buffer_size = 16 * 1024;
        std::vector<uint8_t> buffer;
        buffer.resize(buffer_size);
        azure::storage::blob_request_options options;

        utility::string_t md5_header;
        m_context.set_sending_request([&md5_header](web::http::http_request& request, azure::storage::operation_context)
        {
            if (!request.headers().match(web::http::header_names::content_md5, md5_header))
            {
                md5_header.clear();
            }
        });

        m_blob.create_or_replace(azure::storage::access_condition(), options, m_context);

        options.set_use_transactional_md5(false);
        for (uint16_t i = 0; i < 3; ++i)
        {
            fill_buffer_and_get_md5(buffer);
            auto stream = concurrency::streams::bytestream::open_istream(buffer);
            int64_t offset = m_blob.append_block(stream, utility::string_t(), azure::storage::access_condition(), options, m_context);
            CHECK_UTF8_EQUAL(utility::string_t(), md5_header);
            CHECK_EQUAL(i * buffer_size, offset);
            CHECK_EQUAL(i + 1, m_blob.properties().append_blob_committed_block_count());
        }

        options.set_use_transactional_md5(false);
        for (uint16_t i = 3; i < 6; ++i)
        {
            auto md5 = fill_buffer_and_get_md5(buffer);
            auto stream = concurrency::streams::bytestream::open_istream(buffer);
            int64_t offset = m_blob.append_block(stream, md5, azure::storage::access_condition(), options, m_context);
            CHECK_UTF8_EQUAL(md5, md5_header);
            CHECK_EQUAL(i * buffer_size, offset);
            CHECK_EQUAL(i + 1, m_blob.properties().append_blob_committed_block_count());
        }

        options.set_use_transactional_md5(true);
        for (uint16_t i = 6; i < 9; ++i)
        {
            auto md5 = fill_buffer_and_get_md5(buffer);
            auto stream = concurrency::streams::bytestream::open_istream(buffer);
            int64_t offset = m_blob.append_block(stream, utility::string_t(), azure::storage::access_condition(), options, m_context);
            CHECK_UTF8_EQUAL(md5, md5_header);
            CHECK_EQUAL(i * buffer_size, offset);
            CHECK_EQUAL(i + 1, m_blob.properties().append_blob_committed_block_count());
        }

        // block stream with length = 0
        options.set_use_transactional_md5(true);
        fill_buffer_and_get_md5(buffer);
        auto stream1 = concurrency::streams::bytestream::open_istream(buffer);
        stream1.seek(buffer.size());
        CHECK_THROW(m_blob.append_block(stream1, utility::string_t(), azure::storage::access_condition(), options, m_context), azure::storage::storage_exception);

        options.set_use_transactional_md5(true);
        fill_buffer_and_get_md5(buffer);
        auto stream = concurrency::streams::bytestream::open_istream(buffer);
        CHECK_THROW(m_blob.append_block(stream, dummy_md5, azure::storage::access_condition(), options, m_context), azure::storage::storage_exception);
        CHECK_UTF8_EQUAL(dummy_md5, md5_header);

        m_context.set_sending_request(std::function<void(web::http::http_request &, azure::storage::operation_context)>());
    }
Beispiel #25
0
bool Dataset::goto_rec(int pos) {
  if (ds_state == dsSelect) {
    return seek(pos - 1);
  }
  return false;
}
Beispiel #26
0
void SequenceHandle::update(float position, float frame, float fps)
{
	if(m_sound_status != m_entry->m_sound_status)
	{
		// if a new sound has been set, it's possible to get valid again!
		m_sound_status = m_entry->m_sound_status;
		m_valid = true;

		// stop whatever sound has been playing
		stop();

		// seek starts and seeks to the correct position
		if(!seek(position))
			// no handle, aborting
			return;
	}
	else
	{
		if(!m_valid)
			// invalid, aborting
			return;

		if(m_handle.get())
		{
			// we have a handle, let's update the position
			if(!updatePosition(position))
				// lost handle, aborting
				return;
		}
		else
		{
			// we don't have a handle, let's see if we can start
			if(!seek(position))
				return;
		}
	}

	std::lock_guard<ILockable> lock(*m_entry);
	if(m_pos_status != m_entry->m_pos_status)
	{
		m_pos_status = m_entry->m_pos_status;

		// position changed, need to seek
		if(!seek(position))
			// lost handle, aborting
			return;
	}

	// so far everything alright and handle is there, let's keep going

	if(m_status != m_entry->m_status)
	{
		m_3dhandle->setRelative(m_entry->m_relative);
		m_3dhandle->setVolumeMaximum(m_entry->m_volume_max);
		m_3dhandle->setVolumeMinimum(m_entry->m_volume_min);
		m_3dhandle->setDistanceMaximum(m_entry->m_distance_max);
		m_3dhandle->setDistanceReference(m_entry->m_distance_reference);
		m_3dhandle->setAttenuation(m_entry->m_attenuation);
		m_3dhandle->setConeAngleOuter(m_entry->m_cone_angle_outer);
		m_3dhandle->setConeAngleInner(m_entry->m_cone_angle_inner);
		m_3dhandle->setConeVolumeOuter(m_entry->m_cone_volume_outer);

		m_status = m_entry->m_status;
	}

	float value;

	m_entry->m_volume.read(frame, &value);
	m_handle->setVolume(value);
	m_entry->m_pitch.read(frame, &value);
	m_handle->setPitch(value);
	m_entry->m_panning.read(frame, &value);
	SoftwareDevice::setPanning(m_handle.get(), value);

	Vector3 v, v2;
	Quaternion q;

	m_entry->m_orientation.read(frame, q.get());
	m_3dhandle->setOrientation(q);
	m_entry->m_location.read(frame, v.get());
	m_3dhandle->setLocation(v);
	m_entry->m_location.read(frame + 1, v2.get());
	v2 -= v;
	m_3dhandle->setVelocity(v2 * fps);

	if(m_entry->m_muted)
		m_handle->setVolume(0);
}
Beispiel #27
0
void
playlistproc(void*)
{
	int fd, m, n, nf;
	static char buf[8192+1];
	char *p, *q, *fields[4];

	threadsetname("playlistproc");
	fd = open(playlistfile, OREAD);
	if(fd < 0)
		sysfatal("%s: %r", playlistfile);
	p = buf;
	n = 0;
	if(debug & DBGPLAY)
		fprint(2, "playlistproc: starting\n");
	for(;;){
		m = read(fd, buf+n, sizeof buf - 1 - n);
		if(m == 0){
			if(debug & DBGPLAY)
				fprint(2, "playlistproc: empty read\n");
			continue;
		}
		if(m < 0){
			rerrstr(buf, sizeof(buf));
			if(strcmp(buf, "reading past eof"))
				sysfatal("%s: %r", playlistfile);
			for(n = 0; n < playlist.nentries; n++){
				free(playlist.entry[n].file);
				free(playlist.entry[n].onum);
			}
			if(debug & DBGPLAY)
				fprint(2, "playlistproc: trunc\n");
			playlist.nentries = 0;
			free(playlist.entry);
			playlist.entry = nil;
			updateplaylist(1);
			seek(fd, 0, 0);
			p = buf;
			n = 0;
			continue;
		}
		if(debug & DBGPLAY)
			fprint(2, "playlistproc: read %d bytes\n", m);
		n += m;
		p[n] = '\0';
		while(q = strchr(p, '\n')){
			*q = 0;
			nf = tokenize(p, fields, nelem(fields));
			if(nf){
				playlist.entry = realloc(playlist.entry, (playlist.nentries+1)*sizeof playlist.entry[0]);
				if(playlist.entry == nil)
					sysfatal("realloc %r");
				playlist.entry[playlist.nentries].file = strdup(fields[0]);
				if(nf > 1){
					playlist.entry[playlist.nentries].onum = strdup(fields[1]);
					if(debug & DBGPLAY)
						fprint(2, "playlistproc: [%d]: %q %q\n", playlist.nentries,
							playlist.entry[playlist.nentries].file,
							playlist.entry[playlist.nentries].onum);
				}else{
					playlist.entry[playlist.nentries].onum = nil;
					if(debug & DBGPLAY)
						fprint(2, "playlistproc: [%d]: %q nil\n", playlist.nentries,
							playlist.entry[playlist.nentries].file);
				}
				updateplaylist(0);	// this will also update nentries
			}
			q++;
			n -= q-p;
			p = q;
		}
		if(n)
			memmove(buf, p, n);
		p = buf;
	}
}
Beispiel #28
0
	// Not thread safe by default.
	virtual size_t readat(uint64_t pos, uint8_t* buf, size_t n) {
		seek(pos);
		return read(buf, n);
	}
Beispiel #29
0
void InputSoundFile::seek(Time timeOffset)
{
    seek(static_cast<Uint64>(timeOffset.asSeconds() * m_sampleRate * m_channelCount));
}
Beispiel #30
0
void
asmb(void)
{
	Prog *p;
	long t;
	Optab *o;
	long prevpc;

	if(debug['v'])
		Bprint(&bso, "%5.2f asm\n", cputime());
	Bflush(&bso);

	/* emit text segment */
	seek(cout, HEADR, 0);
	prevpc = pc = INITTEXT;
	for(p = firstp; p != P; p = p->link) {
		if(p->as == ATEXT) {
			curtext = p;
			autosize = p->to.offset + 4;
			if(p->from3.type == D_CONST) {
				for(; pc < p->pc; pc++)
					CPUT(0);
			}
		}
		if(p->pc != pc) {
			diag("phase error %lux sb %lux",
				p->pc, pc);
			if(!debug['a'])
				prasm(curp);
			pc = p->pc;
		}
		curp = p;
		o = oplook(p);	/* could probably avoid this call */
		if(asmout(p, o, 0)) {
			p = p->link;
			pc += 4;
		}
		pc += o->size;
		if (prevpc & (1<<31) && (pc & (1<<31)) == 0) {
			char *tn;

			tn = "?none?";
			if(curtext != P && curtext->from.sym != S)
				tn = curtext->from.sym->name;
			Bprint(&bso, "%s: warning: text segment wrapped past 0\n", tn);
		}
		prevpc = pc;
	}
	/* for virtex 4, inject a jmp instruction after other text */
	if(HEADTYPE == 6)
		/* branch to absolute entry address (0xfffe2100) */
		lput((18 << 26) | (0x03FFFFFC & entryvalue()) | 2);

	if(debug['a'])
		Bprint(&bso, "\n");
	Bflush(&bso);
	cflush();

	/* emit data segment */
	curtext = P;
	switch(HEADTYPE) {
	case 6:
		textsize += JMPSZ;
		/* fall through */
	case 0:
	case 1:
	case 2:
	case 5:
		seek(cout, HEADR+textsize, 0);
		break;
	case 3:
		seek(cout, rnd(HEADR+textsize, 4), 0);
		break;
	case 4:
		seek(cout, rnd(HEADR+textsize, 4096), 0);
		break;
	}

	if(dlm){
		char buf[8];

		write(cout, buf, INITDAT-textsize);
		textsize = INITDAT;
	}

	for(t = 0; t < datsize; t += sizeof(buf)-100) {
		if(datsize-t > sizeof(buf)-100)
			datblk(t, sizeof(buf)-100);
		else
			datblk(t, datsize-t);
	}

	symsize = 0;
	lcsize = 0;
	if(!debug['s']) {
		if(debug['v'])
			Bprint(&bso, "%5.2f sym\n", cputime());
		Bflush(&bso);
		switch(HEADTYPE) {
		case 0:
		case 1:
		case 2:
		case 5:
		case 6:
			seek(cout, HEADR+textsize+datsize, 0);
			break;
		case 3:
			seek(cout, rnd(HEADR+textsize, 4)+datsize, 0);
			break;
		case 4:
			seek(cout, rnd(HEADR+textsize, 4096)+datsize, 0);
			break;
		}
		if(!debug['s'])
			asmsym();
		if(debug['v'])
			Bprint(&bso, "%5.2f sp\n", cputime());
		Bflush(&bso);
		if(!debug['s'])
			asmlc();
		if(dlm)
			asmdyn();
		if(HEADTYPE == 0 || HEADTYPE == 1)	/* round up file length for boot image */
			if((symsize+lcsize) & 1)
				CPUT(0);
		cflush();
	}
	else if(dlm){
		asmdyn();
		cflush();
	}

	/* back up and write the header */
	seek(cout, 0L, 0);
	switch(HEADTYPE) {
	case 0:
		lput(0x1030107);		/* magic and sections */
		lput(textsize);			/* sizes */
		lput(datsize);
		lput(bsssize);
		lput(symsize);			/* nsyms */
		lput(entryvalue());		/* va of entry */
		lput(0L);
		lput(lcsize);
		break;
	case 1:
		lput(0x4a6f7921);		/* Joy! */
		lput(0x70656666);		/* peff */
		lput(0x70777063);		/* pwpc */
		lput(1);
		lput(0);
		lput(0);
		lput(0);
		lput(0);
		lput(0x30002);			/*YY*/
		lput(0);
		lput(~0);
		lput(0);
		lput(textsize+datsize);
		lput(textsize+datsize);
		lput(textsize+datsize);
		lput(0xd0);			/* header size */
		lput(0x10400);
		lput(~0);
		lput(0);
		lput(0xc);
		lput(0xc);
		lput(0xc);
		lput(0xc0);
		lput(0x01010400);
		lput(~0);
		lput(0);
		lput(0x38);
		lput(0x38);
		lput(0x38);
		lput(0x80);
		lput(0x04040400);
		lput(0);
		lput(1);
		lput(0);
		lput(~0);
		lput(0);
		lput(~0);
		lput(0);
		lput(0);
		lput(0);
		lput(0);
		lput(0);
		lput(0);
		lput(0);
		lput(0);
		lput(0);
		lput(0);
		lput(0);
		lput(0x3100);			/* load address */
		lput(0);
		lput(0);
		lput(0);			/* whew! */
		break;
	case 2:
		if(dlm)
			lput(0x80000000 | (4*21*21+7));		/* magic */
		else
			lput(4*21*21+7);	/* magic */
		lput(textsize);			/* sizes */
		lput(datsize);
		lput(bsssize);
		lput(symsize);			/* nsyms */
		lput(entryvalue());		/* va of entry */
		lput(0L);
		lput(lcsize);
		break;
	case 3:
		break;
	case 4:
		lput((0x1DFL<<16)|3L);		/* magic and sections */
		lput(time(0));			/* time and date */
		lput(rnd(HEADR+textsize, 4096)+datsize);
		lput(symsize);			/* nsyms */
		lput((0x48L<<16)|15L);		/* size of optional hdr and flags */

		lput((0413<<16)|01L);		/* magic and version */
		lput(textsize);			/* sizes */
		lput(datsize);
		lput(bsssize);
		lput(entryvalue());		/* va of entry */
		lput(INITTEXT);			/* va of base of text */
		lput(INITDAT);			/* va of base of data */
		lput(INITDAT);			/* address of TOC */
		lput((1L<<16)|1);		/* sn(entry) | sn(text) */
		lput((2L<<16)|1);		/* sn(data) | sn(toc) */
		lput((0L<<16)|3);		/* sn(loader) | sn(bss) */
		lput((3L<<16)|3);		/* maxalign(text) | maxalign(data) */
		lput(('1'<<24)|('L'<<16)|0);	/* type field, and reserved */
		lput(0);			/* max stack allowed */
		lput(0);			/* max data allowed */
		lput(0); lput(0); lput(0);	/* reserved */

		strnput(".text", 8);		/* text segment */
		lput(INITTEXT);			/* address */
		lput(INITTEXT);
		lput(textsize);
		lput(HEADR);
		lput(0L);
		lput(HEADR+textsize+datsize+symsize);
		lput(lcsize);			/* line number size */
		lput(0x20L);			/* flags */

		strnput(".data", 8);		/* data segment */
		lput(INITDAT);			/* address */
		lput(INITDAT);
		lput(datsize);
		lput(rnd(HEADR+textsize, 4096));/* sizes */
		lput(0L);
		lput(0L);
		lput(0L);
		lput(0x40L);			/* flags */

		strnput(".bss", 8);		/* bss segment */
		lput(INITDAT+datsize);		/* address */
		lput(INITDAT+datsize);
		lput(bsssize);
		lput(0L);
		lput(0L);
		lput(0L);
		lput(0L);
		lput(0x80L);			/* flags */
		break;
	case 5:
		/*
		 * customised for blue/gene,
		 * notably the alignment and KMASK masking.
		 */
		strnput("\177ELF", 4);		/* e_ident */
		CPUT(1);			/* class = 32 bit */
		CPUT(2);			/* data = MSB */
		CPUT(1);			/* version = CURRENT */
		strnput("", 9);
		lput((2L<<16)|20L);		/* type = EXEC; machine = PowerPC */
		lput(1L);			/* version = CURRENT */
		lput(entryvalue() & ~KMASK);	/* entry vaddr */
		lput(52L);			/* offset to first phdr */

		if(debug['S']){
			lput(HEADR+textsize+datsize+symsize);	/* offset to first shdr */
			lput(0L);		/* flags = PPC */
			lput((52L<<16)|32L);	/* Ehdr & Phdr sizes*/
			lput((3L<<16)|40L);	/* # Phdrs & Shdr size */
			lput((3L<<16)|2L);	/* # Shdrs & shdr string size */
		}
		else{
			lput(0L);
			lput(0L);		/* flags = PPC */
			lput((52L<<16)|32L);	/* Ehdr & Phdr sizes*/
			lput((3L<<16)|0L);	/* # Phdrs & Shdr size */
			lput((3L<<16)|0L);	/* # Shdrs & shdr string size */
		}

		lput(1L);			/* text - type = PT_LOAD */
		lput(HEADR);			/* file offset */
		lput(INITTEXT & ~KMASK);	/* vaddr */
		lput(INITTEXT);			/* paddr */
		lput(textsize);			/* file size */
		lput(textsize);			/* memory size */
		lput(0x05L);			/* protections = RX */
		lput(0x10000L);			/* alignment */

		lput(1L);			/* data - type = PT_LOAD */
		lput(HEADR+textsize);		/* file offset */
		lput(INITDAT & ~KMASK);		/* vaddr */
		lput(INITDAT);			/* paddr */
		lput(datsize);			/* file size */
		lput(datsize);			/* memory size */
		lput(0x07L);			/* protections = RWX */
		lput(0x10000L);			/* alignment */

		lput(0L);			/* data - type = PT_NULL */
		lput(HEADR+textsize+datsize);	/* file offset */
		lput(0L);			/* vaddr */
		lput(0L);			/* paddr */
		lput(symsize);			/* symbol table size */
		lput(lcsize);			/* line number size */
		lput(0x04L);			/* protections = R */
		lput(0x04L);			/* alignment code?? */
		cflush();

		if(!debug['S'])
			break;

		seek(cout, HEADR+textsize+datsize+symsize, 0);
		lput(1);			/* Section name (string tbl index) */
		lput(1);			/* Section type */
		lput(2|4);			/* Section flags */
		lput(INITTEXT & ~KMASK);	/* Section virtual addr at execution */
		lput(HEADR);			/* Section file offset */
		lput(textsize);			/* Section size in bytes */
		lput(0);			/* Link to another section */
		lput(0);			/* Additional section information */
		lput(0x10000L);			/* Section alignment */
		lput(0);			/* Entry size if section holds table */

		lput(7);			/* Section name (string tbl index) */
		lput(1);			/* Section type */
		lput(2|1);			/* Section flags */
		lput(INITDAT & ~KMASK);		/* Section virtual addr at execution */
		lput(HEADR+textsize);		/* Section file offset */
		lput(datsize);			/* Section size in bytes */
		lput(0);			/* Link to another section */
		lput(0);			/* Additional section information */
		lput(0x10000L);			/* Section alignment */
		lput(0);			/* Entry size if section holds table */

		/* string section header */
		lput(12);			/* Section name (string tbl index) */
		lput(3);			/* Section type */
		lput(1 << 5);			/* Section flags */
		lput(0);			/* Section virtual addr at execution */
		lput(HEADR+textsize+datsize+symsize+3*40);	/* Section file offset */
		lput(14);			/* Section size in bytes */
		lput(0);			/* Link to another section */
		lput(0);			/* Additional section information */
		lput(1);			/* Section alignment */
		lput(0);			/* Entry size if section holds table */

		/* string table */
		cput(0);
		strnput(".text", 5);
		cput(0);
		strnput(".data", 5);
		cput(0);
		strnput(".strtab", 7);
		cput(0);
		cput(0);

		break;
	case 6:
		/*
		 * customised for virtex 4 boot,
		 * notably the alignment and KMASK masking.
		 */
		strnput("\177ELF", 4);		/* e_ident */
		CPUT(1);			/* class = 32 bit */
		CPUT(2);			/* data = MSB */
		CPUT(1);			/* version = CURRENT */
		strnput("", 9);
		lput((2L<<16)|20L);		/* type = EXEC; machine = PowerPC */
		lput(1L);			/* version = CURRENT */
		lput(entryvalue());		/* entry vaddr */
		lput(52L);			/* offset to first phdr */

		debug['S'] = 1;			/* no symbol table */
		if(debug['S']){
			lput(HEADR+textsize+datsize+symsize);	/* offset to first shdr */
			lput(0L);		/* flags = PPC */
			lput((52L<<16)|32L);	/* Ehdr & Phdr sizes*/
			lput((4L<<16)|40L);	/* # Phdrs & Shdr size */
			lput((4L<<16)|2L);	/* # Shdrs & shdr string size */
		}
		else{
			lput(0L);
			lput(0L);		/* flags = PPC */
			lput((52L<<16)|32L);	/* Ehdr & Phdr sizes*/
			lput((4L<<16)|0L);	/* # Phdrs & Shdr size */
			lput((4L<<16)|0L);	/* # Shdrs & shdr string size */
		}

		lput(1L);			/* text - type = PT_LOAD */
		lput(HEADR);			/* file offset */
		lput(INITTEXT);			/* vaddr */
		lput(INITTEXT);			/* paddr */
		lput(textsize-JMPSZ);		/* file size */
		lput(textsize-JMPSZ);		/* memory size */
		lput(0x05L);			/* protections = RX */
		lput(0);			/* alignment */

		lput(1L);			/* data - type = PT_LOAD */
		lput(HEADR+textsize);		/* file offset */
		lput(INITDAT);			/* vaddr */
		lput(INITDAT);			/* paddr */
		lput(datsize);			/* file size */
		lput(datsize+bsssize);		/* memory size */
		lput(0x07L);			/* protections = RWX */
		lput(0);			/* alignment */

		lput(0L);			/* data - type = PT_NULL */
		lput(HEADR+textsize+datsize);	/* file offset */
		lput(0L);			/* vaddr */
		lput(0L);			/* paddr */
		lput(symsize);			/* symbol table size */
		lput(lcsize);			/* line number size */
		lput(0x04L);			/* protections = R */
		lput(0x04L);			/* alignment code?? */

		/* add tiny text section at end with jmp to start */
		lput(1L);			/* text - type = PT_LOAD */
		lput(HEADR+textsize-JMPSZ);	/* file offset */
		lput(0xFFFFFFFC);		/* vaddr */
		lput(0xFFFFFFFC);		/* paddr */
		lput(JMPSZ);			/* file size */
		lput(JMPSZ);			/* memory size */
		lput(0x05L);			/* protections = RX */
		lput(0);			/* disable alignment */

		cflush();
		break;
	}
	cflush();
}