idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
300
public static byte [ ] toByteArray ( final ZipFile zipFile , final String path ) throws IOException { final InputStream in = findInputStreamForResource ( zipFile , path ) ; byte [ ] result = null ; if ( in != null ) { try { result = IOUtils . toByteArray ( in ) ; } finally { IOUtils . closeQuietly ( in ) ; } } return r...
Read who ; e zip item into byte array .
301
public static Document loadXmlDocument ( final InputStream inStream , final String charset , final boolean autoClose ) throws SAXException , IOException , ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; try { factory . setFeature ( XMLConstants . FEATURE_...
Load and parse XML document from input stream .
302
public static Element findFirstElement ( final Element node , final String elementName ) { Element result = null ; for ( final Element l : Utils . findDirectChildrenForName ( node , elementName ) ) { result = l ; break ; } return result ; }
Get first direct child for name .
303
public static List < Element > findDirectChildrenForName ( final Element element , final String childElementname ) { final List < Element > resultList = new ArrayList < Element > ( ) ; final NodeList list = element . getChildNodes ( ) ; for ( int i = 0 ; i < list . getLength ( ) ; i ++ ) { final Node node = list . item...
Find all direct children with defined name .
304
public static int getMaxImageSize ( ) { int result = MAX_IMAGE_SIDE_SIZE_IN_PIXELS ; try { final String defined = System . getProperty ( PROPERTY_MAX_EMBEDDED_IMAGE_SIDE_SIZE ) ; if ( defined != null ) { LOGGER . info ( "Detected redefined max size for embedded image side : " + defined ) ; result = Math . max ( 8 , Int...
Get max image size .
305
public static String rescaleImageAndEncodeAsBase64 ( final InputStream in , final int maxSize ) throws IOException { final Image image = ImageIO . read ( in ) ; String result = null ; if ( image != null ) { result = rescaleImageAndEncodeAsBase64 ( image , maxSize ) ; } return result ; }
Load and encode image into Base64 .
306
public static String rescaleImageAndEncodeAsBase64 ( final File file , final int maxSize ) throws IOException { final Image image = ImageIO . read ( file ) ; if ( image == null ) { throw new IllegalArgumentException ( "Can't load image file : " + file ) ; } return rescaleImageAndEncodeAsBase64 ( image , maxSize ) ; }
Load and encode image into Base64 from file .
307
public static RenderQuality getDefaultRenderQialityForOs ( ) { RenderQuality result = RenderQuality . DEFAULT ; if ( SystemUtils . IS_OS_MAC || SystemUtils . IS_OS_WINDOWS ) { result = RenderQuality . QUALITY ; } return result ; }
Get default render quality for host OS .
308
public MMDPrintOptions setScaleType ( final ScaleType scaleOption ) { this . scaleOption = Assertions . assertNotNull ( scaleOption ) ; return this ; }
Set the selected scale option .
309
public < T > T getSessionObject ( final String key , final Class < T > klazz , final T def ) { this . lock ( ) ; try { T result = klazz . cast ( this . sessionObjects . get ( key ) ) ; return result == null ? def : result ; } finally { this . unlock ( ) ; } }
Get saved session object . Object is presented and saved only for the current panel and only in memory .
310
public void putSessionObject ( final String key , final Object obj ) { this . lock ( ) ; try { if ( obj == null ) { this . sessionObjects . remove ( key ) ; } else { this . sessionObjects . put ( key , obj ) ; } } finally { this . unlock ( ) ; } }
Put session object for key .
311
public void executeModelJobs ( final ModelJob ... jobs ) { Utils . safeSwingCall ( new Runnable ( ) { public void run ( ) { for ( final ModelJob j : jobs ) { try { if ( ! j . doChangeModel ( model ) ) { break ; } } catch ( Exception ex ) { LOGGER . error ( "Errot during job execution" , ex ) ; } } fireNotificationMindM...
Safe Swing thread execution sequence of some jobs over model with model changed notification in the end
312
public void setModel ( final MindMap model , final boolean notifyModelChangeListeners ) { this . lock ( ) ; try { if ( this . elementUnderEdit != null ) { Utils . safeSwingBlockingCall ( new Runnable ( ) { public void run ( ) { endEdit ( false ) ; } } ) ; } final List < int [ ] > selectedPaths = new ArrayList < int [ ]...
Set model for the panel allows to notify listeners optionally .
313
public boolean lockIfNotDisposed ( ) { boolean result = false ; if ( this . panelLocker != null ) { this . panelLocker . lock ( ) ; if ( this . disposed . get ( ) ) { this . panelLocker . unlock ( ) ; } else { result = true ; } } return result ; }
Try lock the panel if it is not disposed .
314
public MindMapPanel lock ( ) { if ( this . panelLocker != null ) { this . panelLocker . lock ( ) ; if ( this . isDisposed ( ) ) { this . panelLocker . unlock ( ) ; throw new IllegalStateException ( "Mind map has been already disposed!" ) ; } } return this ; }
Lock the panel .
315
public boolean copyTopicsToClipboard ( final boolean cut , final Topic ... topics ) { boolean result = false ; if ( this . lockIfNotDisposed ( ) ) { try { if ( topics . length > 0 ) { final Clipboard clipboard = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) ; clipboard . setContents ( new MMDTopicsTransferab...
Create transferable topic list in system clipboard .
316
public boolean pasteTopicsFromClipboard ( ) { boolean result = false ; if ( this . lockIfNotDisposed ( ) ) { try { final Clipboard clipboard = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) ; if ( Utils . isDataFlavorAvailable ( clipboard , MMDTopicsTransferable . MMD_DATA_FLAVOR ) ) { try { final NBMindMapTo...
Paste topics from clipboard to currently selected ones .
317
public static Topic [ ] removeSuccessorsAndDuplications ( final Topic ... topics ) { final List < Topic > result = new ArrayList < Topic > ( ) ; for ( final Topic t : topics ) { final Iterator < Topic > iterator = result . iterator ( ) ; while ( iterator . hasNext ( ) ) { final Topic listed = iterator . next ( ) ; if (...
Remove duplications and successors for presented topics in array .
318
public static Pattern string2pattern ( final String text , final int patternFlags ) { final StringBuilder result = new StringBuilder ( ) ; for ( final char c : text . toCharArray ( ) ) { result . append ( "\\u" ) ; final String code = Integer . toHexString ( c ) . toUpperCase ( Locale . ENGLISH ) ; result . append ( "0...
Create pattern from string .
319
private static String lookupApiKey ( Properties props ) { String apiKey = null ; if ( props . containsKey ( Config . TD_LOGGER_API_KEY ) ) { apiKey = props . getProperty ( Config . TD_LOGGER_API_KEY ) ; props . setProperty ( Config . TD_API_KEY , apiKey ) ; } return apiKey ; }
Define order for API key lookup . 1 . lookup props s td . logger . api . key
320
private static String lookupHost ( Properties props ) { String host = null ; if ( props . containsKey ( Config . TD_LOGGER_API_SERVER_HOST ) ) { host = props . getProperty ( Config . TD_LOGGER_API_SERVER_HOST ) ; } if ( host == null ) { host = Config . TD_LOGGER_API_SERVER_HOST_DEFAULT ; } props . setProperty ( Config ...
Define order for hostname lookup . 1 . lookup props s td . logger . api . server . host
321
private static String lookupPort ( Properties props ) { String port = null ; if ( props . containsKey ( Config . TD_LOGGER_API_SERVER_PORT ) ) { port = props . getProperty ( Config . TD_LOGGER_API_SERVER_PORT ) ; } if ( port == null ) { port = Config . TD_LOGGER_API_SERVER_PORT_DEFAULT ; } props . setProperty ( Config ...
Define order for port num lookup . 1 . lookup props s td . logger . api . server . port
322
private static String lookupScheme ( Properties props ) { String scheme = null ; if ( props . containsKey ( Config . TD_LOGGER_API_SERVER_SCHEME ) ) { scheme = props . getProperty ( Config . TD_LOGGER_API_SERVER_SCHEME ) ; } if ( scheme == null ) { scheme = Config . TD_LOGGER_API_SERVER_SCHEME_DEFAULT ; } props . setPr...
Define order for scheme lookup . 1 . lookup props s td . logger . api . server . scheme
323
public static OptionalHeader newInstance ( byte [ ] headerbytes , long offset ) throws IOException { OptionalHeader header = new OptionalHeader ( headerbytes , offset ) ; header . read ( ) ; return header ; }
Creates and returns a new instance of the optional header .
324
public Optional < DataDirEntry > maybeGetDataDirEntry ( DataDirectoryKey key ) { return Optional . fromNullable ( dataDirectory . get ( key ) ) ; }
Returns the optional data directory entry for the given key or absent if entry doesn t exist .
325
public Optional < StandardField > maybeGetStandardFieldEntry ( StandardFieldEntryKey key ) { return Optional . fromNullable ( standardFields . get ( key ) ) ; }
Returns maybe the standard field entry for the given key .
326
public StandardField getStandardFieldEntry ( StandardFieldEntryKey key ) { if ( ! standardFields . containsKey ( key ) ) { throw new IllegalArgumentException ( "standard field " + key + " does not exist!" ) ; } return standardFields . get ( key ) ; }
Returns the standard field entry for the given key .
327
public String getDataDirInfo ( ) { StringBuilder b = new StringBuilder ( ) ; for ( DataDirEntry entry : dataDirectory . values ( ) ) { b . append ( entry . getKey ( ) + ": " + entry . getVirtualAddress ( ) + "(0x" + Long . toHexString ( entry . getVirtualAddress ( ) ) + ")/" + entry . getDirectorySize ( ) + "(0x" + Lon...
Returns a description of all data directories .
328
public String getWindowsSpecificInfo ( ) { StringBuilder b = new StringBuilder ( ) ; for ( StandardField entry : windowsFields . values ( ) ) { long value = entry . getValue ( ) ; HeaderKey key = entry . getKey ( ) ; String description = entry . getDescription ( ) ; if ( key . equals ( IMAGE_BASE ) ) { b . append ( des...
Returns a string with description of the windows specific header fields . Magic number must be set .
329
public long getRelocatedImageBase ( ) { long imageBase = get ( WindowsEntryKey . IMAGE_BASE ) ; long sizeOfImage = get ( WindowsEntryKey . SIZE_OF_IMAGE ) ; if ( imageBase + sizeOfImage >= 0x80000000L || imageBase == 0L ) { return 0x10000L ; } return imageBase ; }
Checks if image base is too large or zero and relocates it accordingly . Otherwise the usual image base is returned .
330
public List < DllCharacteristic > getDllCharacteristics ( ) { long value = get ( DLL_CHARACTERISTICS ) ; List < DllCharacteristic > dllChs = DllCharacteristic . getAllFor ( value ) ; return dllChs ; }
Returns a list of the DllCharacteristics that are set in the file .
331
public long getAdjustedFileAlignment ( ) { long fileAlign = get ( FILE_ALIGNMENT ) ; if ( isLowAlignmentMode ( ) ) { return 1 ; } if ( fileAlign < 512 ) { fileAlign = 512 ; } if ( fileAlign % 512 != 0 ) { long rest = fileAlign % 512 ; fileAlign += ( 512 - rest ) ; } return fileAlign ; }
Adjusts the file alignment to low alignment mode if necessary .
332
public boolean isLowAlignmentMode ( ) { long fileAlign = get ( FILE_ALIGNMENT ) ; long sectionAlign = get ( SECTION_ALIGNMENT ) ; return 1 <= fileAlign && fileAlign == sectionAlign && fileAlign <= 0x800 ; }
Determines if the file is in low alignment mode .
333
public boolean isStandardAlignmentMode ( ) { long fileAlign = get ( FILE_ALIGNMENT ) ; long sectionAlign = get ( SECTION_ALIGNMENT ) ; return 0x200 <= fileAlign && fileAlign <= sectionAlign && 0x1000 <= sectionAlign ; }
Determines if the file is in standard alignment mode .
334
private void read ( ) { final int key = 0 ; final int description = 1 ; final int offset = 2 ; final int length = 3 ; SpecificationFormat format = new SpecificationFormat ( key , description , offset , length ) ; try { data = IOUtil . readHeaderEntries ( COFFHeaderKey . class , format , COFF_SPEC_FILE , headerbytes , g...
Reads the header s fields .
335
public MachineType getMachineType ( ) { long value = get ( MACHINE ) ; try { return MachineType . getForValue ( value ) ; } catch ( IllegalArgumentException e ) { logger . error ( "Unable to resolve machine type for value: " + value ) ; return MachineType . UNKNOWN ; } }
Returns the enum that denotes the machine type .
336
public static COFFFileHeader newInstance ( byte [ ] headerbytes , long offset ) { COFFFileHeader header = new COFFFileHeader ( headerbytes , offset ) ; header . read ( ) ; return header ; }
Creates an instance of the COFF File Header based on headerbytes and offset .
337
public byte [ ] getBytes ( ) throws IOException { if ( sectionbytes . isPresent ( ) ) { return sectionbytes . get ( ) . clone ( ) ; } loadSectionBytes ( ) ; byte [ ] result = sectionbytes . get ( ) ; assert result != null ; return result ; }
Returns the section bytes . The file is read if the bytes aren t already loaded .
338
private void loadSectionBytes ( ) throws IOException { Preconditions . checkState ( size == ( int ) size , "section is too large to dump into byte array" ) ; try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { raf . seek ( offset ) ; byte [ ] bytes = new byte [ ( int ) size ] ; raf . read ( bytes ) ; s...
Loads the section bytes from the file using offset and size .
339
public VisualizerBuilder setColor ( ColorableItem key , Color color ) { settings . colorMap . put ( key , color ) ; return this ; }
Sets the color for a colorable item .
340
public static void dumpLocationToFile ( PhysicalLocation loc , File inFile , File outFile ) throws IOException { Preconditions . checkArgument ( ! outFile . exists ( ) ) ; Preconditions . checkArgument ( inFile . exists ( ) , inFile . isFile ( ) ) ; final int BUFFER_SIZE = 2048 ; try ( RandomAccessFile raf = new Random...
Dumps the given part of the inFile to outFile . The part to dump is represented by loc . This will read safely from inFile which means locations outside of inFile are written as zero bytes to outFile .
341
public static byte [ ] loadBytesSafely ( long offset , int length , RandomAccessFile raf ) throws IOException { Preconditions . checkArgument ( length >= 0 ) ; if ( offset < 0 ) return new byte [ 0 ] ; raf . seek ( offset ) ; int readsize = length ; if ( readsize + offset > raf . length ( ) ) { readsize = ( int ) ( raf...
Loads the bytes at the offset into a byte array with the given length using the raf . If EOF the byte array is zero padded . If offset < 0 it will return a zero sized array .
342
private static byte [ ] padBytes ( byte [ ] bytes , int length ) { byte [ ] padded = new byte [ length ] ; for ( int i = 0 ; i < bytes . length ; i ++ ) { padded [ i ] = bytes [ i ] ; } return padded ; }
Return array with length size if length is greater than the previous size the array is zero - padded at the end .
343
public static byte [ ] loadBytes ( long offset , int length , RandomAccessFile raf ) throws IOException { if ( length < 0 ) { length = 0 ; logger . error ( "Negative length: " + length ) ; } if ( offset < 0 ) { offset = 0 ; logger . error ( "Negative offset: " + offset ) ; } offset = Math . min ( offset , raf . length ...
Loads the bytes at the offset into a byte array with the given length using the raf .
344
public static List < SymbolDescription > readSymbolDescriptions ( ) throws IOException { String filename = "importcategories.txt" ; List < SymbolDescription > list = new ArrayList < > ( ) ; List < String [ ] > lines = readArray ( filename ) ; String category = "" ; String subCategory = null ; for ( String [ ] array : l...
Reads a list of symbol descriptions
345
public static MSDOSHeader newInstance ( byte [ ] headerbytes , long peSigOffset ) throws IOException { MSDOSHeader header = new MSDOSHeader ( headerbytes , peSigOffset ) ; header . read ( ) ; return header ; }
Creates and returns an instance of the MSDOSHeader with the given bytes and the file offset of the PE signature .
346
public void read ( ) throws IOException { try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { throwIf ( file . length ( ) < PE_OFFSET_LOCATION ) ; byte [ ] offsetBytes = loadBytesSafely ( PE_OFFSET_LOCATION , PE_OFFSET_LOCATION_SIZE , raf ) ; peOffset = Optional . of ( ( long ) bytesToInt ( offsetBytes...
Reads the PE signature and sets the peOffset .
347
public boolean exists ( ) { try { read ( ) ; return true ; } catch ( FileFormatException e ) { return false ; } catch ( IOException e ) { logger . error ( e ) ; return false ; } }
Tries to read the PE signature of the current file and returns true iff it was successfull .
348
public String getInfo ( ) { if ( ! peOffset . isPresent ( ) ) { return "No PE signature found" ; } return "-------------" + NL + "PE Signature" + NL + "-------------" + NL + "pe offset: " + peOffset . get ( ) + NL ; }
Returns a description string .
349
public long getOffset ( ) throws IOException { if ( offset == null ) { read ( ) ; SectionTable table = data . getSectionTable ( ) ; SectionLoader loader = new SectionLoader ( data ) ; offset = 0L ; List < SectionHeader > headers = table . getSectionHeaders ( ) ; for ( SectionHeader section : headers ) { long alignedPoi...
Returns the file offset of the overlay .
350
public boolean dumpTo ( File outFile ) throws IOException { if ( exists ( ) ) { dump ( getOffset ( ) , outFile ) ; return true ; } else { return false ; } }
Writes a dump of the overlay to the specified output location .
351
private void dump ( long offset , File outFile ) throws IOException { try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ; FileOutputStream out = new FileOutputStream ( outFile ) ) { raf . seek ( offset ) ; byte [ ] buffer = new byte [ 2048 ] ; int bytesRead ; while ( ( bytesRead = raf . read ( buffer ) )...
Dumps the last part of the file beginning at the specified offset .
352
public byte [ ] getDump ( ) throws IOException { byte [ ] dump = new byte [ ( int ) getSize ( ) ] ; try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { raf . seek ( offset ) ; raf . readFully ( dump ) ; } return dump ; }
Loads all bytes of the overlay into an array and returns them .
353
public static < T extends Characteristic > List < T > getAllMatching ( long value , T [ ] flags ) { List < T > list = new ArrayList < > ( ) ; for ( T ch : flags ) { long mask = ch . getValue ( ) ; if ( ( value & mask ) != 0 ) { list . add ( ch ) ; } } return list ; }
Returns a list of all flags which are set in the value
354
private long fileAligned ( long value ) { long fileAlign = optHeader . getAdjustedFileAlignment ( ) ; long rest = value % fileAlign ; long result = value ; if ( rest != 0 ) { result = value - rest + fileAlign ; } if ( ! ( optHeader . isLowAlignmentMode ( ) || result % 512 == 0 ) ) { logger . error ( "file aligning went...
Rounds up the value to the file alignment of the optional header .
355
private long fileSizeAdjusted ( long alignedPointerToRaw , long readSize ) { if ( readSize + alignedPointerToRaw > file . length ( ) ) { readSize = file . length ( ) - alignedPointerToRaw ; } if ( alignedPointerToRaw > file . length ( ) ) { logger . info ( "invalid section: starts outside the file, readsize set to 0" )...
Adjusts the readsize of a section to the size of the file .
356
public Optional < Long > maybeGetFileOffset ( long rva ) { Optional < SectionHeader > section = maybeGetSectionHeaderByRVA ( rva ) ; long fileOffset = rva ; if ( section . isPresent ( ) ) { long virtualAddress = section . get ( ) . get ( VIRTUAL_ADDRESS ) ; long pointerToRawData = section . get ( ) . get ( POINTER_TO_R...
Returns the file offset for the given RVA . Returns absent if file offset is not within file .
357
public Optional < SectionHeader > maybeGetSectionHeaderByRVA ( long rva ) { List < SectionHeader > headers = table . getSectionHeaders ( ) ; for ( SectionHeader header : headers ) { VirtualLocation vLoc = getVirtualSectionLocation ( header ) ; if ( addressIsWithin ( vLoc , rva ) ) { return Optional . of ( header ) ; } ...
Returns the section entry of the section table the rva is pointing into .
358
public Optional < SectionHeader > maybeGetSectionHeaderByOffset ( long fileOffset ) { List < SectionHeader > headers = table . getSectionHeaders ( ) ; for ( SectionHeader header : headers ) { PhysicalLocation loc = getPhysicalSectionLocation ( header ) ; if ( addressIsWithin ( loc , fileOffset ) ) { return Optional . o...
Returns the section entry of the section table the offset is pointing into .
359
private static boolean addressIsWithin ( Location location , long address ) { long endpoint = location . from ( ) + location . size ( ) ; return address >= location . from ( ) && address < endpoint ; }
Returns true if the address is within the given location
360
private MemoryMappedPE getMemoryMappedPE ( ) { if ( ! memoryMapped . isPresent ( ) ) { memoryMapped = Optional . of ( MemoryMappedPE . newInstance ( data , this ) ) ; } return memoryMapped . get ( ) ; }
Creates new instance of MemoryMappedPE or just returns it if it is already there .
361
private Optional < LoadInfo > maybeGetLoadInfo ( DataDirectoryKey dataDirKey ) { Optional < DataDirEntry > dirEntry = optHeader . maybeGetDataDirEntry ( dataDirKey ) ; if ( dirEntry . isPresent ( ) ) { long virtualAddress = dirEntry . get ( ) . getVirtualAddress ( ) ; Optional < Long > maybeOffset = maybeGetFileOffsetF...
Assembles the loadInfo object for the dataDirKey .
362
public boolean containsEntryPoint ( SectionHeader header ) { long ep = data . getOptionalHeader ( ) . get ( StandardFieldEntryKey . ADDR_OF_ENTRY_POINT ) ; long vStart = header . getAlignedVirtualAddress ( ) ; long vSize = header . getAlignedVirtualSize ( ) ; if ( vSize == 0 ) { vSize = header . getAlignedSizeOfRaw ( )...
Returns whether the section contains the entry point of the file .
363
public static byte [ ] fileHash ( File file , MessageDigest messageDigest ) throws IOException { return computeHash ( file , messageDigest , 0L , file . length ( ) ) ; }
Returns the hash value of the file for the specified messageDigest .
364
public BufferedImage createEntropyImage ( File file ) throws IOException { resetAvailabilityFlags ( ) ; this . data = new PEData ( null , null , null , null , null , file ) ; image = new BufferedImage ( fileWidth , height , IMAGE_TYPE ) ; final int MIN_WINDOW_SIZE = 100 ; final int windowSize = Math . max ( MIN_WINDOW_...
Creates an image of the local entropies of this file .
365
private Color getColorForEntropy ( double entropy ) { assert entropy <= 1 ; assert entropy >= 0 ; Color entropyColor = colorMap . get ( ENTROPY ) ; float [ ] hsbvals = new float [ 3 ] ; Color . RGBtoHSB ( entropyColor . getRed ( ) , entropyColor . getGreen ( ) , entropyColor . getBlue ( ) , hsbvals ) ; float entropyHue...
Creates a color instance based on a given entropy .
366
public void writeImage ( File input , File output , String formatName ) throws IOException { BufferedImage image = createImage ( input ) ; ImageIO . write ( image , formatName , output ) ; }
Writes an image to the output file that displays the structure of the PE file .
367
public BufferedImage createDiffImage ( BufferedImage firstImage , BufferedImage secondImage ) throws IOException { BufferedImage diffImage = new BufferedImage ( firstImage . getWidth ( ) , firstImage . getHeight ( ) , IMAGE_TYPE ) ; for ( int x = 0 ; x < firstImage . getWidth ( ) && x < secondImage . getWidth ( ) ; x +...
Creates a buffered image containing the diff of both files .
368
public BufferedImage createImage ( File file ) throws IOException { resetAvailabilityFlags ( ) ; this . data = PELoader . loadPE ( file ) ; image = new BufferedImage ( fileWidth , height , IMAGE_TYPE ) ; drawSections ( ) ; Overlay overlay = new Overlay ( data ) ; if ( overlay . exists ( ) ) { long overlayOffset = overl...
Creates a buffered image that displays the structure of the PE file .
369
public BufferedImage createLegendImage ( boolean withBytePlot , boolean withEntropy , boolean withPEStructure ) { image = new BufferedImage ( legendWidth , height , IMAGE_TYPE ) ; drawLegend ( withBytePlot , withEntropy , withPEStructure ) ; assert image != null ; assert image . getWidth ( ) == legendWidth ; assert ima...
Creates a buffered image with a basic Legend
370
private void drawPEHeaders ( ) { long msdosOffset = 0 ; long msdosSize = withMinLength ( data . getMSDOSHeader ( ) . getHeaderSize ( ) ) ; drawPixels ( colorMap . get ( MSDOS_HEADER ) , msdosOffset , msdosSize ) ; long optOffset = data . getOptionalHeader ( ) . getOffset ( ) ; long optSize = withMinLength ( data . getO...
Draws the PE Header to the structure image
371
private Optional < Long > getEntryPoint ( ) { long rva = data . getOptionalHeader ( ) . get ( StandardFieldEntryKey . ADDR_OF_ENTRY_POINT ) ; Optional < SectionHeader > section = new SectionLoader ( data ) . maybeGetSectionHeaderByRVA ( rva ) ; if ( section . isPresent ( ) ) { long phystovirt = section . get ( ) . get ...
Returns the entry point of the PE if present and valid otherwise absent .
372
private void drawSections ( ) { SectionTable table = data . getSectionTable ( ) ; long sectionTableOffset = table . getOffset ( ) ; long sectionTableSize = table . getSize ( ) ; drawPixels ( colorMap . get ( SECTION_TABLE ) , sectionTableOffset , sectionTableSize ) ; logger . info ( "x pixels: " + getXPixels ( ) ) ; lo...
Draw the sections to the structure image .
373
private Color getSectionColor ( SectionHeader header ) { int nr = header . getNumber ( ) ; Color sectionColor = colorMap . get ( SECTION_START ) ; for ( int i = 1 ; i < nr ; i ++ ) { sectionColor = variate ( sectionColor ) ; } return sectionColor ; }
Generate the color of the given section .
374
private Color variate ( Color color ) { assert color != null ; final int diff = 30 ; int newRed = shiftColorPart ( color . getRed ( ) - diff ) ; int newGreen = shiftColorPart ( color . getGreen ( ) - diff ) ; int newBlue = shiftColorPart ( color . getBlue ( ) - diff ) ; Color newColor = new Color ( newRed , newGreen , ...
Shift the given section color one step .
375
private void drawRect ( Color color , int startX , int startY , int width , int height ) { assert color != null ; for ( int x = startX ; x < startX + width ; x ++ ) { for ( int y = startY ; y < startY + height ; y ++ ) { try { image . setRGB ( x , y , color . getRGB ( ) ) ; } catch ( ArrayIndexOutOfBoundsException e ) ...
Draws a rectangle .
376
private void drawCross ( Color color , int startX , int startY , int width , int height ) { assert color != null ; final int thickness = 2 ; for ( int x = startX ; x < startX + width ; x ++ ) { for ( int y = startY ; y < startY + height ; y ++ ) { try { if ( Math . abs ( ( x - startX ) - ( y - startY ) ) < thickness ||...
Draws a cross .
377
private void drawPixel ( Color color , long fileOffset ) { long size = withMinLength ( 0 ) ; drawPixels ( color , fileOffset , size ) ; }
Draws a square pixel at fileOffset with color .
378
private long getPixelNumber ( long fileOffset ) { assert fileOffset >= 0 ; long result = Math . round ( fileOffset / bytesPerPixel ( ) ) ; assert result >= 0 ; return result ; }
convert fileOffset to square pixels
379
private int bytesPerPixel ( ) { long fileSize = data . getFile ( ) . length ( ) ; long pixelMax = getXPixels ( ) * ( long ) getYPixels ( ) ; return ( int ) Math . ceil ( fileSize / ( double ) pixelMax ) ; }
Calculates how many bytes are covered by one square pixel .
380
private PEData loadData ( ) throws IOException { PESignature pesig = new PESignature ( file ) ; pesig . read ( ) ; checkState ( pesig . exists ( ) , "no valid pe file, signature not found" ) ; try ( RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ) { MSDOSHeader msdos = loadMSDOSHeader ( raf , pesig . getOff...
Loads the PE file header data into a PEData instance .
381
private MSDOSHeader loadMSDOSHeader ( RandomAccessFile raf , long peSigOffset ) throws IOException { byte [ ] headerbytes = loadBytesSafely ( 0 , MSDOSHeader . FORMATTED_HEADER_SIZE , raf ) ; return MSDOSHeader . newInstance ( headerbytes , peSigOffset ) ; }
Loads the MSDOS header .
382
private SectionTable loadSectionTable ( PESignature pesig , COFFFileHeader coff , RandomAccessFile raf ) throws IOException { long offset = pesig . getOffset ( ) + PESignature . PE_SIG . length + COFFFileHeader . HEADER_SIZE + coff . getSizeOfOptionalHeader ( ) ; logger . info ( "SectionTable offset: " + offset ) ; int...
Loads the section table . Presumes a valid PE file .
383
private COFFFileHeader loadCOFFFileHeader ( PESignature pesig , RandomAccessFile raf ) throws IOException { long offset = pesig . getOffset ( ) + PESignature . PE_SIG . length ; logger . info ( "COFF Header offset: " + offset ) ; byte [ ] headerbytes = loadBytesSafely ( offset , COFFFileHeader . HEADER_SIZE , raf ) ; r...
Loads the COFF File header . Presumes a valid PE file .
384
private OptionalHeader loadOptionalHeader ( PESignature pesig , COFFFileHeader coff , RandomAccessFile raf ) throws IOException { long offset = pesig . getOffset ( ) + PESignature . PE_SIG . length + COFFFileHeader . HEADER_SIZE ; logger . info ( "Optional Header offset: " + offset ) ; int size = getOptHeaderSize ( off...
Loads the optional header . Presumes a valid PE file .
385
public long getFileOffset ( SectionTable table ) { checkArgument ( table != null , "section table must not be null" ) ; Optional < SectionHeader > section = maybeGetSectionTableEntry ( table ) ; if ( section . isPresent ( ) ) { long sectionRVA = section . get ( ) . getAlignedVirtualAddress ( ) ; long sectionOffset = se...
Calculates the file offset of the data directory based on the virtual address and the entries in the section table . This method is subject to change .
386
public SectionHeader getSectionTableEntry ( SectionTable table ) { Optional < SectionHeader > entry = maybeGetSectionTableEntry ( table ) ; if ( entry . isPresent ( ) ) { return entry . get ( ) ; } throw new IllegalStateException ( "there is no section for this data directory entry" ) ; }
Returns the section table entry of the section that the data directory entry is pointing to .
387
public Optional < SectionHeader > maybeGetSectionTableEntry ( SectionTable table ) { checkArgument ( table != null , "table must not be null" ) ; List < SectionHeader > sections = table . getSectionHeaders ( ) ; for ( SectionHeader header : sections ) { long vSize = header . getAlignedVirtualSize ( ) ; if ( vSize == 0 ...
more convenient use of the API
388
public long getAlignedSizeOfRaw ( ) { long sizeOfRaw = get ( SIZE_OF_RAW_DATA ) ; if ( sizeOfRaw == ( sizeOfRaw & ~ 0xfff ) ) { return sizeOfRaw ; } long result = ( sizeOfRaw + 0xfff ) & ~ 0xfff ; assert result % 4096 == 0 ; return result ; }
Returns the SizeOfRawData rounded up to a multiple of 4kb .
389
public long getAlignedVirtualSize ( ) { long virtSize = get ( VIRTUAL_SIZE ) ; if ( virtSize == ( virtSize & ~ 0xfff ) ) { return virtSize ; } long result = ( virtSize + 0xfff ) & ~ 0xfff ; assert result % 4096 == 0 ; return result ; }
Returns the VirtualSize rounded up to a multiple of 4kb .
390
public long getAlignedVirtualAddress ( ) { long virtAddr = get ( VIRTUAL_ADDRESS ) ; if ( virtAddr == ( virtAddr & ~ 0xfff ) ) { return virtAddr ; } long result = ( virtAddr + 0xfff ) & ~ 0xfff ; assert result % 4096 == 0 ; return result ; }
Returns the VirtualAddress rounded up to a multiple of 4kb .
391
public List < SectionCharacteristic > getCharacteristics ( ) { long value = get ( SectionHeaderKey . CHARACTERISTICS ) ; List < SectionCharacteristic > list = SectionCharacteristic . getAllFor ( value ) ; assert list != null ; return list ; }
Returns a list of all characteristics of that section .
392
public SectionHeader getSectionHeader ( int number ) { for ( SectionHeader header : headers ) { if ( header . getNumber ( ) == number ) { return header ; } } throw new IllegalArgumentException ( "invalid section number, no section header found" ) ; }
Returns the section entry that has the given number or null if there is no section with that number .
393
public SectionHeader getSectionHeader ( String sectionName ) { for ( SectionHeader entry : headers ) { if ( entry . getName ( ) . equals ( sectionName ) ) { return entry ; } } throw new IllegalArgumentException ( "invalid section name, no section header found" ) ; }
Returns the section entry that has the given name . If there are several sections with the same name the first one will be returned .
394
public Optional < SectionHeader > getSectionHeaderByName ( String name ) { for ( SectionHeader header : headers ) { if ( header . getName ( ) . equals ( name ) ) { return Optional . of ( header ) ; } } return Optional . absent ( ) ; }
Returns an optional of the first section that has the given name .
395
public static String renderLinks ( CharSequence input , Iterable < LinkSpan > links , LinkRenderer linkRenderer ) { if ( input == null ) { throw new NullPointerException ( "input must not be null" ) ; } if ( links == null ) { throw new NullPointerException ( "links must not be null" ) ; } if ( linkRenderer == null ) { ...
Render the supplied links from the supplied input text using a renderer . The parts of the text outside of links are added to the result without processing .
396
private int findFirst ( CharSequence input , int beginIndex , int rewindIndex ) { int first = - 1 ; boolean atomBoundary = true ; for ( int i = beginIndex ; i >= rewindIndex ; i -- ) { char c = input . charAt ( i ) ; if ( localAtomAllowed ( c ) ) { first = i ; atomBoundary = false ; } else if ( c == '.' ) { if ( atomBo...
See Local - part in RFC 5321 plus extensions in RFC 6531
397
private int findLast ( CharSequence input , int beginIndex ) { boolean firstInSubDomain = true ; boolean canEndSubDomain = false ; int firstDot = - 1 ; int last = - 1 ; for ( int i = beginIndex ; i < input . length ( ) ; i ++ ) { char c = input . charAt ( i ) ; if ( firstInSubDomain ) { if ( subDomainAllowed ( c ) ) { ...
See Domain in RFC 5321 plus extension of sub - domain in RFC 6531
398
private boolean localAtomAllowed ( char c ) { if ( Scanners . isAlnum ( c ) || Scanners . isNonAscii ( c ) ) { return true ; } switch ( c ) { case '!' : case '#' : case '$' : case '%' : case '&' : case '\'' : case '*' : case '+' : case '-' : case '/' : case '=' : case '?' : case '^' : case '_' : case '`' : case '{' : c...
See Atom in RFC 5321 atext in RFC 5322
399
private int findFirst ( CharSequence input , int beginIndex , int rewindIndex ) { int first = - 1 ; int digit = - 1 ; for ( int i = beginIndex ; i >= rewindIndex ; i -- ) { char c = input . charAt ( i ) ; if ( Scanners . isAlpha ( c ) ) { first = i ; } else if ( Scanners . isDigit ( c ) ) { digit = i ; } else if ( ! sc...
See scheme in RFC 3986