Example #1
0
File: c80.c Project: adamsch1/scc
main()
  {
  glbptr=startglb;  /* clear global symbols */
  locptr=startloc;  /* clear local symbols */
  wqptr=wq;    /* clear while queue */
  macptr=    /* clear the macro pool */
  litptr=    /* clear literal pool */
    sp =    /* stack ptr (relative) */
  errcnt=    /* no errors */
  eof=    /* not eof yet */
  input=    /* no input file */
  input2=    /* or include file */
  output=    /* no open units */
  ncmp=    /* no open compound states */
  lastst=    /* no last statement yet */
  quote[1]=
  0;    /*  ...all set to zero.... */
  quote[0]='"';    /* fake a quote literal */
  cmode=1;  /* enable preprocessing */
  /*        */
  /*  compiler body    */
  /*        */
  ask();      /* get user options */
  openout();    /* get an output file */
  openin();    /* and initial input file */
  header();    /* intro code */
  parse();     /* process ALL input */
  dumplits();    /* then dump literal pool */
  dumpglbs();    /* and all static memory */
  errorsummary();    /* summarize errors */
  trailer();    /* follow-up code */
  closeout();    /* close the output (if any) */
  return;      /* then exit to system */
  }
Example #2
0
static void
reverse(void)

{

/*
 *
 * Begins by looking for the ENDPROLOG comment in the input file. Everything up to
 * that comment is copied to the output file. If the comment isn't found the entire
 * input file is copied and moreprolog() returns FALSE. Otherwise readpages() reads
 * the rest of the input file and remembers (in pages[]) where each page starts and
 * ends. In addition everything bracketed by %%BeginGlobal and %%EndGlobal comments
 * is immediately added to the new prologue (or setup section) and ends up being
 * removed from the individual pages. When readpages() finds the TRAILER comment
 * or gets to the end of the input file we go back to the pages[] array and use
 * the saved offsets to write the pages out in reverse order. Finally everything
 * from the TRAILER comment to the end of the input file is copied to the output
 * file.
 *
 */

    if ( moreprolog(ENDPROLOG) == TRUE )  {
	readpages();
	writepages();
	trailer();
    }	/* End if */

}   /* End of reverse */
Example #3
0
void PdfParser::ReadNextTrailer()
{
    // ReadXRefcontents has read the first 't' from "trailer" so just check for "railer"
    if( this->IsNextToken( "trailer" ) )
    //if( strcmp( m_buffer.GetBuffer(), "railer" ) == 0 )
    {
        PdfParserObject trailer( m_vecObjects, m_device, m_buffer );
        try {
            // Ignore the encryption in the trailer as the trailer may not be encrypted
            trailer.ParseFile( NULL, true );
        } catch( PdfError & e ) {
            e.AddToCallstack( __FILE__, __LINE__, "The linearized trailer was found in the file, but contains errors." );
            throw e;
        }

        // now merge the information of this trailer with the main documents trailer
        MergeTrailer( &trailer );

        if( trailer.GetDictionary().HasKey( "Prev" ) )
        {
            try {
                ReadXRefContents( static_cast<pdf_long>(trailer.GetDictionary().GetKeyAsLong( "Prev", 0 )) );
            } catch( PdfError & e ) {
                e.AddToCallstack( __FILE__, __LINE__, "Unable to load /Prev xref entries." );
                throw e;
            }
        }
        else
        {
            PODOFO_RAISE_ERROR( ePdfError_NoTrailer );
        }
    }
}
Example #4
0
/**
 * compile one file if filename is NULL redirect do to stdin/stdout
 * @param file filename
 * @return 
 */
void compile(char *file) {
    if (file == NULL || filename_typeof(file) == 'c') {
        global_table_index = 0;
        local_table_index = NUMBER_OF_GLOBALS;
        while_table_index = 0;
        tag_table_index = 0;
        inclsp =
        iflevel =
        skiplevel =
        swstp =
        litptr =
        stkp =
        errcnt =
        ncmp =
        lastst =
        //quote[1] =
        0;
        input2 = -1;
        //quote[0] = '"';
        cmode = 1;
        glbflag = 1;
        nxtlab = 0;
        litlab = getlabel();
        defmac("end\tmemory");
        //add_global("memory", ARRAY, CCHAR, 0, EXTERN);
        //add_global("stack", ARRAY, CCHAR, 0, EXTERN);
        rglobal_table_index = global_table_index; //rglbptr = glbptr;
        //add_global("etext", ARRAY, CCHAR, 0, EXTERN);
        //add_global("edata", ARRAY, CCHAR, 0, EXTERN);
        defmac("short\tint");
        initmac();
        // compiler body
        if (file == NULL) {
            input = 0;
        } else if (!openin(file))
            return;
        if (file == NULL) {
            output = 1;
        } else if (!openout())
            return;
        header();
        code_segment_gtext();
        parse();
        close(input);
        data_segment_gdata();
        dumplits();
        dumpglbs();
        errorsummary();
        trailer();
        oflush();
        close(output);
        pl("");
        errs = errs || errfile;
    } else {
        writee("Don't understand file ");
        writee(file);
        errs = 1;
    }
}
Example #5
0
 //! Dumps a description of the finite state machine expressed in
 //! the DOT language to the given output stream.
 static void dump (const char_state_machine &csm_, rules &rules_,
     ostream &stream_)
 {
     header (stream_);
     for (std::size_t dfa_ = 0, dfas_ = csm_.size (); dfa_ < dfas_; ++dfa_)
     {
         dump_ex (dfa_, csm_._sm_deque[dfa_], rules_, stream_);
     }
     trailer (stream_);
 }
CString CompPinStruct::getSortableReference(const CString& reference)
{
   const char* p = reference;
   CString alpha;
   CString numeric;
   CString suffix;

   while (*p != '\0')
   {
      if (isdigit(*p))
      {
         break;
      }

      alpha += *(p++);
   }

   while (*p != '\0')
   {
      if (!isdigit(*p))
      {
         break;
      }

      numeric += *(p++);
   }

   suffix = p;

   CString leader("00000000");
   CString trailer("        ");

   alpha   += trailer;
   numeric  = leader + numeric;
   suffix  += trailer;

   CString sortableReference = alpha.Left(8) + numeric.Right(8) + suffix.Left(8);

   // Case dts0100408077 - The general construction of sortableRefDes as above causes 
   // collisions for refnames like C3 and C03, they both result in the same value.
   // Some features build component maps based on the sortableRefDes, and they are dropping entities when
   // such name collisions occur. So here we tack the original refname onto the end, thus making them
   // unique again. This keeps intact the basic overall "numerical" sorting portion of the game.
   sortableReference += "|" + reference;

   return sortableReference;
}
Example #7
0
static int
gunzip(int ofd, char *ofile, Biobuf *bin)
{
	Dir *d;
	GZHead h;
	int err;

	h.file = nil;
	gzok = 0;
	for(;;){
		if(Bgetc(bin) < 0)
			return 1;
		Bungetc(bin);

		if(setjmp(zjmp))
			return 0;
		header(bin, &h);
		gzok = 0;

		wlen = 0;
		crc = 0;

		if(!table && verbose)
			fprint(2, "extracting %s to %s\n", h.file, ofile);

		err = inflate((void*)ofd, crcwrite, bin, (int(*)(void*))Bgetc);
		if(err != FlateOk)
			error("inflate failed: %s", flateerr(err));

		trailer(bin, wlen);

		if(table){
			if(verbose)
				print("%-32s %10ld %s", h.file, wlen, ctime(h.mtime));
			else
				print("%s\n", h.file);
		}else if(settimes && h.mtime && (d=dirfstat(ofd)) != nil){
			d->mtime = h.mtime;
			dirfwstat(ofd, d);
			free(d);
		}

		free(h.file);
		h.file = nil;
		gzok = Boffset(bin);
	}
}
Example #8
0
int
main(int argc, char *argv[])
{
	int i;
	Biobuf in, *inp;
	Rune r;

	for(i=0; i<nelem(htmlchars); i++){
		chartorune(&r, htmlchars[i].utf);
		htmlchars[i].value = r;
	}
	qsort(htmlchars, nelem(htmlchars), sizeof(htmlchars[0]), hccmp);

	ARGBEGIN{
	case 't':
		title = ARGF();
		if(title == nil)
			usage();
		break;
	case 'd':
		debug++;
		break;
	default:
		usage();
	}ARGEND

	Binit(&bout, 1, OWRITE);
	if(argc == 0){
		header(title);
		Binit(&in, 0, OREAD);
		process(&in, "<stdin>");
	}else{
		header(title);
		for(i=0; i<argc; i++){
			inp = Bopen(argv[i], OREAD);
			if(inp == nil)
				sysfatal("can't open %s: %r", argv[i]);
			process(inp, argv[i]);
			Bterm(&(inp->Biobufhdr));
		}
	}
	flush();
	trailer();
	exits(nil);
}
Example #9
0
int
image2psfile(int fd, Memimage *im, int dpi) {
	Rectangle r;
	Rectangle bbox;
	int e;
	int xmargin = 36;
	int ymargin = 36;
	double paperaspectratio;
	double imageaspectratio;
	Biobuf ioutb;
	Memimage *tmp;

	if(im->depth >= 8 && im->chan != CMAP8 && im->chan != GREY8){
		/*
		 * the postscript libraries can only handle [1248]-bit grey, 8-bit cmap,
		 * and 24-bit color, so convert.
		 */
		tmp = allocmemimage(im->r, strtochan("b8g8r8"));
		if(tmp == nil)
			return 1;
		memimagedraw(tmp, tmp->r, im, im->r.min, nil, ZP, S);
		freememimage(im);
		im = tmp;
	}

	Binit(&ioutb, fd, OWRITE);
 	r = im->r;
	width = Dx(r);
	height = Dy(r);
	imageaspectratio = (double) width / (double) height;
	if (landscape) {
		paperaspectratio = ((double)paperlength - (ymargin * 2)) / ((double)paperwidth - (xmargin * 2));
		if (dpi > 0) {
			iwidth = width * 72 / dpi;
			iheight = height * 72 / dpi;
		} else if (imageaspectratio > paperaspectratio) {
			iwidth = paperlength - (ymargin * 2);
			iheight = iwidth / imageaspectratio;
		} else {
			iheight = paperwidth - (xmargin * 2);
			iwidth  = iheight * imageaspectratio;
		}
		xstart = paperwidth - xmargin - (iheight * ymagnification);
		ystart = paperlength - ymargin;
		rotation = -90;
	} else {
		paperaspectratio = ((double)paperwidth - (xmargin * 2)) / ((double)paperlength - (ymargin * 2));
		if (dpi > 0) {
			iwidth = width * 72 / dpi;
			iheight = height * 72 / dpi;
		} else if (imageaspectratio > paperaspectratio) {
			iwidth = paperwidth - (xmargin * 2);
			iheight = iwidth / imageaspectratio;
		} else {
			iheight = paperlength - (ymargin * 2);
			iwidth  = iheight * imageaspectratio;
		}
		xstart = xmargin;
		ystart = paperlength - ymargin - (iheight * ymagnification);
		rotation = 0;
	}
	bbox = Rect(xstart,ystart,xstart+iwidth,ystart+iheight);
	e = preamble(&ioutb, bbox);
	if(e != 0)
		return e;
	Bprint(&ioutb, "%%%%Page: 1\n%%%%BeginPageSetup\n");
	Bprint(&ioutb, "/pgsave save def\n");
	Bprint(&ioutb, "%%%%EndPageSetup\n");
	bps = im->depth;
	Bprint(&ioutb, "%d 0 %d %d %d %d %d %d %s doimage\n", iheight, iwidth, ystart, xstart, height, width, bps, im->flags&Fgrey ? "true" : "false");
 	imagebits(&ioutb, im);
	Bprint(&ioutb, "pgsave restore\nshowpage\n");
	e = trailer(&ioutb, 1);
	if(e != 0)
		return e;
	Bterm(&ioutb);
	return 0;
}
Example #10
0
//---------------------------------------------------------------------------
void File_Pdf::Read_Buffer_Continue()
{
    switch (State)
    {
        case State_Parsing_xref         : xref(); if (!Element_IsWaitingForMoreData()) trailer(); break;
        case State_Parsing_startxref    : eof(); startxref(); break;
        case State_Parsing_object       : break; //Using elements
        default                         : Finish();
    }
}
Example #11
0
/*
 *      Compiler begins execution here
 */
int main(int argc, char **argv)
{
        int     n;      /* Loop counter */
		int     i;
        gargc = argc ;
        gargv = argv ;
/*
 * Empty our mem ptrs
 */

        litq=dubq=tempq=glbq=0;
        symtab=loctab=0;
        wqueue=0;membptr=0;tagptr=0;swnext=0;stage=0;
        gotoq=0;

        /* allocate space for arrays */
        litq = mymalloc(FNLITQ) ;         /* literals, these 2 dumped end */
        dubq = mymalloc(FNLITQ) ;         /* Doubles */
        tempq = mymalloc(LITABSZ) ;        /* Temp strings... */
        glbq  = mymalloc(LITABSZ) ;        /* Used for glb lits, dumped now */
        symtab = SYM_CAST mymalloc(NUMGLBS*sizeof(SYMBOL)) ;
        loctab = SYM_CAST mymalloc(NUMLOC*sizeof(SYMBOL)) ;
        wqueue = WQ_CAST mymalloc(NUMWHILE*sizeof(WHILE_TAB)) ;
        gotoq= (GOTO_TAB *)calloc(NUMGOTO,sizeof(GOTO_TAB));
   if (gotoq==NULL) OutOfMem();

        tagptr = tagtab = TAG_CAST mymalloc(NUMTAG*sizeof(TAG_SYMBOL)) ;
        membptr = membtab = SYM_CAST mymalloc(NUMMEMB*sizeof(SYMBOL)) ;

        swnext = SW_CAST mymalloc(NUMCASE*sizeof(SW_TAB)) ;
        swend = swnext + (NUMCASE-1) ;

        stage = mymalloc(STAGESIZE) ;
        stagelast = stage+STAGELIMIT ;

        /* empty symbol table */
        glbptr = STARTGLB;
        while ( glbptr < ENDGLB ) {
                glbptr->name[0] = 0 ;
                ++glbptr ;
        }

        glbcnt = 0 ;                    /* clear global symbols */
        locptr = STARTLOC ;             /* clear local symbols */
        wqptr = wqueue ;                /* clear while queue */
        gltptr=dubptr=0 ;               /* clear literal pools */
        *litq=0;         /* First entry in literal queue is zero */
        litptr=1;       /* So miniprintf search works */

        Zsp =                   /* stack ptr (relative) */
        errcnt =                /* no errors */
        errstop =               /* keep going after an error */
        eof =                   /* not eof yet */
        swactive =              /* not in switch */
        skiplevel =             /* #if not encountered */
        iflevel =               /* #if nesting level = 0 */
        ncmp =                  /* no open compound states */
        lastst =                /* not first file to asm */
        fnstart =               /* current "function" started at line 0 */
        lineno =                /* no lines read from file */
        infunc =                /* not in function now */
                        0 ;             /*  ...all set to zero.... */

        stagenext = NULL_CHAR ; /* direct output mode */

        input =                                 /* no input file */
        inpt2 =                                 /* or include file */
        saveout =                               /* no diverted output */
        output = NULL_FD ;              /* no open units */

        currfn = NULL_SYM ;             /* no function yet */
        macptr = cmode = 1 ;    /* clear macro pool and enable preprocessing */
        ncomp=doinline=mathz88 = incfloat= compactcode =0;
        intuition=zorg=lpointer=cppcom=appz88=0;
        dosigned=NO;
        makelib=useshare=makeshare=sharedfile=NO;
        smartprintf=expanded=YES;
        startup=0;                      /* Which startup do we want? */
        nxtlab =                        /* start numbers at lowest possible */
        ctext =                         /* don't include the C text as comments */
        errstop =                       /* don't stop after errors */
        verbose = 0;
        gotocnt=0;
   defdenums=0;
   doublestrings = 0;
   noaltreg = NO;
        safedata=reqpag = -1;
   shareoffset=SHAREOFFSET;   /* Offset for shared libs */
   debuglevel=NO;
   farheapsz=-1;         /* Size of far heap */
    assemtype = ASM_Z80ASM;
   printflevel=0;
#ifdef USEFRAME
   indexix=YES;
   useframe=NO;
#endif

        /*
         *      compiler body
         */
        setup_sym() ;   /* define some symbols */
/* Parse the command line options */
        atexit(MemCleanup);     /* To free everything */
        clear();
        filenum=0;
        for (n=1;n<argc;n++) {
                if (argv[n][0]=='-') ParseArgs(1+argv[n]);
                else {filenum=n; break;}
        }
        clear();

        if (filenum == 0)
        {
                info();
                exit(1);
        }
        litlab=getlabel();              /* Get labels for function lits*/
        dublab=getlabel();              /* and fn doubles*/
        openout();              /* get the output file */
        openin();               /* and initial input file */
        header();               /* intro code */
        parse();                /* process ALL input */
        /* dump literal queues, with label */
        /* litq starts from 1, so literp has to be -1 */
        dumplits(0, YES,litptr-1,litlab,litq+1) ;
        dumplits(1, YES,dubptr,dublab,dubq) ;
        dumpvars();
        dumpfns();
        trailer();              /* follow-up code */
        closeout();
        errsummary();   /* summarize errors */
        if (errcnt) exit(1);
        exit(0);
}
Example #12
0
blargg_err_t Spc_Emu::track_info_( track_info_t* out, int ) const
{
	get_spc_info( header(), trailer(), trailer_size(), out );
	return 0;
}
Example #13
0
File: unzip.c Project: aahud/harvey
/*
 * extracts a single entry from a zip file
 * czh is the optional corresponding central directory entry
 */
static int
unzipEntry(Biobuf *bin, ZipHead *czh)
{
	Dir *d;
	ZipHead zh;
	char *p;
	int64_t off;
	int fd, isdir, ok, err;

	zh.file = nil;
	if(setjmp(zjmp)){
		delfile = nil;
		free(zh.file);
		return -1;
	}

	memset(&zh, 0, sizeof(zh));
	if(!header(bin, &zh))
		return 0;

	ok = 1;
	isdir = 0;

	fd = -1;
	if(wantFile(zh.file)){
		if(verbose)
			fprint(2, "extracting %s\n", zh.file);

		if(czh != nil && czh->extos == ZDos){
			isdir = czh->eattr & ZDDir;
			if(isdir && zh.uncsize != 0)
				fprint(2, "unzip: ignoring directory data for %s\n", zh.file);
		}
		if(zh.meth == 0 && zh.uncsize == 0){
			p = strchr(zh.file, '\0');
			if(p > zh.file && p[-1] == '/')
				isdir = 1;
		}

		if(stdout){
			if(ok && !isdir)
				fd = 1;
		}else if(isdir){
			fd = create(zh.file, OREAD, DMDIR | 0775);
			if(fd < 0){
				d = dirstat(zh.file);
				if(d == nil || (d->mode & DMDIR) != DMDIR){
					fprint(2, "unzip: can't create directory %s: %r\n", zh.file);
					ok = 0;
				}
				free(d);
			}
		}else if(ok){
			if(autodir)
				mkpdirs(zh.file);
			fd = create(zh.file, OWRITE, 0664);
			if(fd < 0){
				fprint(2, "unzip: can't create %s: %r\n", zh.file);
				ok = 0;
			}else
				delfile = zh.file;
		}
	}

	wlen = 0;
	rlen = 0;
	crc = 0;
	wbad = 0;

	if(zh.meth == 0){
		if(!copyout(fd, bin, zh.csize))
			error("copying data for %s failed: %r", zh.file);
	}else if(zh.meth == 8){
		off = Boffset(bin);
		err = inflate((void*)fd, crcwrite, bin, (int(*)(void*))Bgetc);
		if(err != FlateOk)
			error("inflate failed: %s", flateerr(err));
		rlen = Boffset(bin) - off;
	}else
		error("can't handle compression method %d for %s", zh.meth, zh.file);

	trailer(bin, &zh);

	if(zh.crc != crc)
		error("crc mismatch for %s", zh.file);
	if(zh.uncsize != wlen)
		error("output size mismatch for %s", zh.file);
	if(zh.csize != rlen)
		error("input size mismatch for %s", zh.file);

	delfile = nil;
	free(zh.file);

	if(fd >= 0 && !stdout){
		if(settimes){
			d = dirfstat(fd);
			if(d != nil){
				d->mtime = msdos2time(zh.modtime, zh.moddate);
				if(d->mtime)
					dirfwstat(fd, d);
			}
		}
		close(fd);
	}

	return ok;
}
Example #14
0
File: unzip.c Project: aahud/harvey
/*
 * print the "local file header" table of contents
 */
static int
sunztable(Biobuf *bin)
{
	ZipHead zh;
	int64_t off;
	uint32_t hcrc, hcsize, huncsize;
	int ok, err;

	ok = 1;
	for(;;){
		if(setjmp(zjmp)){
			free(zh.file);
			return 0;
		}

		memset(&zh, 0, sizeof(zh));
		if(!header(bin, &zh))
			return ok;

		hcrc = zh.crc;
		hcsize = zh.csize;
		huncsize = zh.uncsize;

		wlen = 0;
		rlen = 0;
		crc = 0;
		wbad = 0;

		if(zh.meth == 0){
			if(!copyout(-1, bin, zh.csize))
				error("reading data for %s failed: %r", zh.file);
		}else if(zh.meth == 8){
			off = Boffset(bin);
			err = inflate((void*)-1, crcwrite, bin, (int(*)(void*))Bgetc);
			if(err != FlateOk)
				error("inflate %s failed: %s", zh.file, flateerr(err));
			rlen = Boffset(bin) - off;
		}else
			error("can't handle compression method %d for %s", zh.meth, zh.file);

		trailer(bin, &zh);

		if(wantFile(zh.file)){
			if(verbose)
				print("%-32s %10lu %s", zh.file, zh.uncsize, ctime(msdos2time(zh.modtime, zh.moddate)));
			else
				print("%s\n", zh.file);

			if(verbose > 1){
				print("\textract by os %d vers %d.%d\n", zh.extos, zh.extvers / 10, zh.extvers % 10);
				print("\tflags %x\n", zh.flags);
				print("\tmethod %d\n", zh.meth);
				print("\tmod time %d\n", zh.modtime);
				print("\tmod date %d\n", zh.moddate);
				print("\tcrc %lx\n", zh.crc);
				print("\tcompressed size %lu\n", zh.csize);
				print("\tuncompressed size %lu\n", zh.uncsize);
				if((zh.flags & ZTrailInfo) && (hcrc || hcsize || huncsize)){
					print("\theader crc %lx\n", zh.crc);
					print("\theader compressed size %lu\n", zh.csize);
					print("\theader uncompressed size %lu\n", zh.uncsize);
				}
			}
		}

		if(zh.crc != crc)
			error("crc mismatch for %s", zh.file);
		if(zh.uncsize != wlen)
			error("output size mismatch for %s", zh.file);
		if(zh.csize != rlen)
			error("input size mismatch for %s", zh.file);


		free(zh.file);
		zh.file = nil;
	}
}
Example #15
0
static void SubstrateHookFunctionThumb(SubstrateProcessRef process, void *symbol, void *replace, void **result) {
    if (symbol == NULL)
        return;

    uint16_t *area(reinterpret_cast<uint16_t *>(symbol));

    unsigned align((reinterpret_cast<uintptr_t>(area) & 0x2) == 0 ? 0 : 1);
    uint16_t *thumb(area + align);

    uint32_t *arm(reinterpret_cast<uint32_t *>(thumb + 2));
    uint16_t *trail(reinterpret_cast<uint16_t *>(arm + 2));

    if (
        (align == 0 || area[0] == T$nop) &&
        thumb[0] == T$bx(A$pc) &&
        thumb[1] == T$nop &&
        arm[0] == A$ldr_rd_$rn_im$(A$pc, A$pc, 4 - 8)
    ) {
        if (result != NULL)
            *result = reinterpret_cast<void *>(arm[1]);

        SubstrateHookMemory code(process, arm + 1, sizeof(uint32_t) * 1);

        arm[1] = reinterpret_cast<uint32_t>(replace);

        return;
    }

    size_t required((trail - area) * sizeof(uint16_t));

    size_t used(0);
    while (used < required)
        used += MSGetInstructionWidthThumb(reinterpret_cast<uint8_t *>(area) + used);
    used = (used + sizeof(uint16_t) - 1) / sizeof(uint16_t) * sizeof(uint16_t);

    size_t blank((used - required) / sizeof(uint16_t));

    uint16_t backup[used / sizeof(uint16_t)];
    memcpy(backup, area, used);

    if (MSDebug) {
        char name[16];
        sprintf(name, "%p", area);
        MSLogHexEx(area, used + sizeof(uint16_t), 2, name);
    }

    if (result != NULL) {

    size_t length(used);
    for (unsigned offset(0); offset != used / sizeof(uint16_t); ++offset)
        if (T$pcrel$ldr(backup[offset]))
            length += 3 * sizeof(uint16_t);
        else if (T$pcrel$b(backup[offset]))
            length += 6 * sizeof(uint16_t);
        else if (T2$pcrel$b(backup + offset)) {
            length += 5 * sizeof(uint16_t);
            ++offset;
        } else if (T$pcrel$bl(backup + offset)) {
            length += 5 * sizeof(uint16_t);
            ++offset;
        } else if (T$pcrel$cbz(backup[offset])) {
            length += 16 * sizeof(uint16_t);
        } else if (T$pcrel$ldrw(backup[offset])) {
            length += 4 * sizeof(uint16_t);
            ++offset;
        } else if (T$pcrel$add(backup[offset]))
            length += 6 * sizeof(uint16_t);
        else if (T$32bit$i(backup[offset]))
            ++offset;

    unsigned pad((length & 0x2) == 0 ? 0 : 1);
    length += (pad + 2) * sizeof(uint16_t) + 2 * sizeof(uint32_t);

    uint16_t *buffer(reinterpret_cast<uint16_t *>(mmap(
        NULL, length, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0
    )));

    if (buffer == MAP_FAILED) {
        MSLog(MSLogLevelError, "MS:Error:mmap() = %d", errno);
        *result = NULL;
        return;
    }

    if (false) fail: {
        munmap(buffer, length);
        *result = NULL;
        return;
    }

    size_t start(pad), end(length / sizeof(uint16_t));
    uint32_t *trailer(reinterpret_cast<uint32_t *>(buffer + end));
    for (unsigned offset(0); offset != used / sizeof(uint16_t); ++offset) {
        if (T$pcrel$ldr(backup[offset])) {
            union {
                uint16_t value;

                struct {
                    uint16_t immediate : 8;
                    uint16_t rd : 3;
                    uint16_t : 5;
                };
            } bits = {backup[offset+0]};

            buffer[start+0] = T$ldr_rd_$pc_im_4$(bits.rd, T$Label(start+0, end-2) / 4);
            buffer[start+1] = T$ldr_rd_$rn_im_4$(bits.rd, bits.rd, 0);

            // XXX: this code "works", but is "wrong": the mechanism is more complex than this
            *--trailer = ((reinterpret_cast<uint32_t>(area + offset) + 4) & ~0x2) + bits.immediate * 4;

            start += 2;
            end -= 2;
        } else if (T$pcrel$b(backup[offset])) {
            union {
                uint16_t value;

                struct {
                    uint16_t imm8 : 8;
                    uint16_t cond : 4;
                    uint16_t /*1101*/ : 4;
                };
            } bits = {backup[offset+0]};

            intptr_t jump(bits.imm8 << 1);
            jump |= 1;
            jump <<= 23;
            jump >>= 23;

            buffer[start+0] = T$b$_$im(bits.cond, (end-6 - (start+0)) * 2 - 4);

            *--trailer = reinterpret_cast<uint32_t>(area + offset) + 4 + jump;
            *--trailer = A$ldr_rd_$rn_im$(A$pc, A$pc, 4 - 8);
            *--trailer = T$nop << 16 | T$bx(A$pc);

            start += 1;
            end -= 6;
        } else if (T2$pcrel$b(backup + offset)) {
            union {
                uint16_t value;

                struct {
                    uint16_t imm6 : 6;
                    uint16_t cond : 4;
                    uint16_t s : 1;
                    uint16_t : 5;
                };
            } bits = {backup[offset+0]};

            union {
                uint16_t value;

                struct {
                    uint16_t imm11 : 11;
                    uint16_t j2 : 1;
                    uint16_t a : 1;
                    uint16_t j1 : 1;
                    uint16_t : 2;
                };
            } exts = {backup[offset+1]};

            intptr_t jump(1);
            jump |= exts.imm11 << 1;
            jump |= bits.imm6 << 12;

            if (exts.a) {
                jump |= bits.s << 24;
                jump |= (~(bits.s ^ exts.j1) & 0x1) << 23;
                jump |= (~(bits.s ^ exts.j2) & 0x1) << 22;
                jump |= bits.cond << 18;
                jump <<= 7;
                jump >>= 7;
            } else {
Example #16
0
void Renamer::renameMovies(QList<Movie*> movies, const QString &filePattern, const QString &filePatternMulti,
                           const QString &directoryPattern, const bool &renameFiles, const bool &renameDirectories, const bool &dryRun)
{
    if ((renameFiles && filePattern.isEmpty()) || (renameDirectories && directoryPattern.isEmpty()))
        return;

    foreach (Movie *movie, movies) {
        if (movie->files().isEmpty() || (movie->files().count() > 1 && filePatternMulti.isEmpty()) || movie->hasChanged())
            continue;

        qApp->processEvents();
        QFileInfo fi(movie->files().first());
        QString fiCanonicalPath = fi.canonicalPath();
        QDir dir(fi.canonicalPath());
        QString newFolderName = directoryPattern;
        QString newFileName;
        QString nfo = Manager::instance()->mediaCenterInterface()->nfoFilePath(movie);
        QString poster = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MoviePoster);
        QString fanart = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieBackdrop);
        QString banner = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieBanner);
        QString thumb = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieThumb);
        QString logo = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieLogo);
        QString clearArt = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieClearArt);
        QString cdArt = Manager::instance()->mediaCenterInterface()->imageFileName(movie, ImageType::MovieCdArt);

        QDir chkDir(fi.canonicalPath());
        chkDir.cdUp();

        bool isBluRay = Helper::instance()->isBluRay(chkDir.path());
        bool isDvd = Helper::instance()->isDvd(chkDir.path());

        if (isBluRay || isDvd)
            dir.cdUp();

        if (!isBluRay && !isDvd && renameFiles) {
            int partNo = 0;
            foreach (const QString &file, movie->files()) {
                newFileName = (movie->files().count() == 1) ? filePattern : filePatternMulti;
                QFileInfo fi(file);
                QString baseName = fi.completeBaseName();
                QDir currentDir = fi.dir();
                Renamer::replace(newFileName, "title", movie->name());
                Renamer::replace(newFileName, "originalTitle", movie->originalName());
                Renamer::replace(newFileName, "sortTitle", movie->sortTitle());
                Renamer::replace(newFileName, "year", movie->released().toString("yyyy"));
                Renamer::replace(newFileName, "extension", fi.suffix());
                Renamer::replace(newFileName, "partNo", QString::number(++partNo));
                Renamer::replace(newFileName, "resolution", Helper::instance()->matchResolution(movie->streamDetails()->videoDetails().value("width").toInt(),
                                                                                                movie->streamDetails()->videoDetails().value("height").toInt()));
                Renamer::replaceCondition(newFileName, "imdbId", movie->id());
                Renamer::replaceCondition(newFileName, "movieset", movie->set());
                Renamer::replaceCondition(newFileName, "3D", movie->streamDetails()->videoDetails().value("stereomode") != "");
                Helper::instance()->sanitizeFileName(newFileName);
                if (fi.fileName() != newFileName) {
                    ui->results->append(tr("<b>Rename File</b> \"%1\" to \"%2\"").arg(fi.fileName()).arg(newFileName));
                    if (!dryRun) {
                        if (!rename(file, fi.canonicalPath() + "/" + newFileName))
                            ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                    }

                    foreach (const QString &trailerFile, currentDir.entryList(QStringList() << fi.completeBaseName() + "-trailer.*", QDir::Files | QDir::NoDotAndDotDot)) {
                        QFileInfo trailer(fi.canonicalPath() + "/" + trailerFile);
                        QString newTrailerFileName = newFileName;
                        newTrailerFileName = newTrailerFileName.left(newTrailerFileName.lastIndexOf(".")) + "-trailer." + trailer.suffix();
                        if (trailer.fileName() != newTrailerFileName) {
                            ui->results->append(tr("<b>Rename File</b> \"%1\" to \"%2\"").arg(trailer.fileName()).arg(newTrailerFileName));
                            if (!dryRun) {
                                if (!rename(fi.canonicalPath() + "/" + trailerFile, fi.canonicalPath() + "/" + newTrailerFileName))
                                    ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                            }
                        }
                    }

                    QStringList filters;
                    foreach (const QString &extra, m_extraFiles)
                        filters << baseName + extra;
                    foreach (const QString &subFileName, currentDir.entryList(filters, QDir::Files | QDir::NoDotAndDotDot)) {
                        QString subSuffix = subFileName.mid(baseName.length());
                        QString newBaseName = newFileName.left(newFileName.lastIndexOf("."));
                        QString newSubName = newBaseName + subSuffix;
                        ui->results->append(tr("<b>Rename File</b> \"%1\" to \"%2\"").arg(subFileName).arg(newSubName));
                        if (!dryRun) {
                            if (!rename(currentDir.canonicalPath() + "/" + subFileName, currentDir.canonicalPath() + "/" + newSubName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename nfo
            if (!nfo.isEmpty()) {
                QString nfoFileName = QFileInfo(nfo).fileName();
                QList<DataFile> nfoFiles = Settings::instance()->dataFiles(DataFileType::MovieNfo);
                if (!nfoFiles.isEmpty()) {
                    QString newNfoFileName = nfoFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newNfoFileName);
                    if (newNfoFileName != nfoFileName) {
                        ui->results->append(tr("<b>Rename NFO</b> \"%1\" to \"%2\"").arg(nfoFileName).arg(newNfoFileName));
                        if (!dryRun) {
                            if (!rename(nfo, fiCanonicalPath + "/" + newNfoFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Poster
            if (!poster.isEmpty()) {
                QString posterFileName = QFileInfo(poster).fileName();
                QList<DataFile> posterFiles = Settings::instance()->dataFiles(DataFileType::MoviePoster);
                if (!posterFiles.isEmpty()) {
                    QString newPosterFileName = posterFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newPosterFileName);
                    if (newPosterFileName != posterFileName) {
                        ui->results->append(tr("<b>Rename Poster</b> \"%1\" to \"%2\"").arg(posterFileName).arg(newPosterFileName));
                        if (!dryRun) {
                            if (!rename(poster, fiCanonicalPath + "/" + newPosterFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Fanart
            if (!fanart.isEmpty()) {
                QString fanartFileName = QFileInfo(fanart).fileName();
                QList<DataFile> fanartFiles = Settings::instance()->dataFiles(DataFileType::MovieBackdrop);
                if (!fanartFiles.isEmpty()) {
                    QString newFanartFileName = fanartFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newFanartFileName);
                    if (newFanartFileName != fanartFileName) {
                        ui->results->append(tr("<b>Rename Fanart</b> \"%1\" to \"%2\"").arg(fanartFileName).arg(newFanartFileName));
                        if (!dryRun) {
                            if (!rename(fanart, fiCanonicalPath + "/" + newFanartFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Banner
            if (!banner.isEmpty()) {
                QString bannerFileName = QFileInfo(banner).fileName();
                QList<DataFile> bannerFiles = Settings::instance()->dataFiles(DataFileType::MovieBanner);
                if (!bannerFiles.isEmpty()) {
                    QString newBannerFileName = bannerFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newBannerFileName);
                    if (newBannerFileName != bannerFileName) {
                        ui->results->append(tr("<b>Rename Banner</b> \"%1\" to \"%2\"").arg(bannerFileName).arg(newBannerFileName));
                        if (!dryRun) {
                            if (!rename(banner, fiCanonicalPath + "/" + newBannerFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Thumb
            if (!thumb.isEmpty()) {
                QString thumbFileName = QFileInfo(thumb).fileName();
                QList<DataFile> thumbFiles = Settings::instance()->dataFiles(DataFileType::MovieThumb);
                if (!thumbFiles.isEmpty()) {
                    QString newThumbFileName = thumbFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newThumbFileName);
                    if (newThumbFileName != thumbFileName) {
                        ui->results->append(tr("<b>Rename Thumb</b> \"%1\" to \"%2\"").arg(thumbFileName).arg(newThumbFileName));
                        if (!dryRun) {
                            if (!rename(thumb, fiCanonicalPath + "/" + newThumbFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename Logo
            if (!logo.isEmpty()) {
                QString logoFileName = QFileInfo(logo).fileName();
                QList<DataFile> logoFiles = Settings::instance()->dataFiles(DataFileType::MovieLogo);
                if (!logoFiles.isEmpty()) {
                    QString newLogoFileName = logoFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newLogoFileName);
                    if (newLogoFileName != logoFileName) {
                        ui->results->append(tr("<b>Rename Logo</b> \"%1\" to \"%2\"").arg(logoFileName).arg(newLogoFileName));
                        if (!dryRun) {
                            if (!rename(logo, fiCanonicalPath + "/" + newLogoFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename ClearArt
            if (!clearArt.isEmpty()) {
                QString clearArtFileName = QFileInfo(clearArt).fileName();
                QList<DataFile> clearArtFiles = Settings::instance()->dataFiles(DataFileType::MovieClearArt);
                if (!clearArtFiles.isEmpty()) {
                    QString newClearArtFileName = clearArtFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newClearArtFileName);
                    if (newClearArtFileName != clearArtFileName) {
                        ui->results->append(tr("<b>Rename Clear Art</b> \"%1\" to \"%2\"").arg(clearArtFileName).arg(newClearArtFileName));
                        if (!dryRun) {
                            if (!rename(clearArt, fiCanonicalPath + "/" + newClearArtFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }

            // Rename CdArt
            if (!cdArt.isEmpty()) {
                QString cdArtFileName = QFileInfo(cdArt).fileName();
                QList<DataFile> cdArtFiles = Settings::instance()->dataFiles(DataFileType::MovieCdArt);
                if (!cdArtFiles.isEmpty()) {
                    QString newCdArtFileName = cdArtFiles.first().saveFileName(newFileName, -1, movie->files().count() > 1);
                    Helper::instance()->sanitizeFileName(newCdArtFileName);
                    if (newCdArtFileName != cdArtFileName) {
                        ui->results->append(tr("<b>Rename CD Art</b> \"%1\" to \"%2\"").arg(cdArtFileName).arg(newCdArtFileName));
                        if (!dryRun) {
                            if (!rename(cdArt, fiCanonicalPath + "/" + newCdArtFileName))
                                ui->results->append("&nbsp;&nbsp;<span style=\"color:#ff0000;\"><b>" + tr("Failed") + "</b></span>");
                        }
                    }
                }
            }
        }