summaryrefslogtreecommitdiffstats
path: root/common/StExecutableImage.cpp
blob: 6e36d4fa3483374368404f8e243c2c58ff2ff968 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
 * File:	StExecutableImage.cpp
 *
 * Copyright (c) Freescale Semiconductor, Inc. All rights reserved.
 * See included license file for license details.
 */

#include "StExecutableImage.h"
#include <stdexcept>
#include <algorithm>
#include <string.h>
#include <stdio.h>

StExecutableImage::StExecutableImage(int inAlignment)
:	m_alignment(inAlignment),
	m_hasEntry(false),
	m_entry(0)
{
}

//! Makes a duplicate of each memory region.
StExecutableImage::StExecutableImage(const StExecutableImage & inOther)
:	m_name(inOther.m_name),
    m_alignment(inOther.m_alignment),
	m_hasEntry(inOther.m_hasEntry),
	m_entry(inOther.m_entry),
    m_filters(inOther.m_filters)
{
	const_iterator it = inOther.getRegionBegin();
	for (; it != inOther.getRegionEnd(); ++it)
	{
		const MemoryRegion & region = *it;
		
		MemoryRegion regionCopy(region);
		if (region.m_type == FILL_REGION && region.m_data != NULL)
		{
			regionCopy.m_data = new uint8_t[region.m_length];
			memcpy(regionCopy.m_data, region.m_data, region.m_length);
		}
		
		m_image.push_back(regionCopy);
	}
}

//! Disposes of memory allocated for each region.
StExecutableImage::~StExecutableImage()
{
	MemoryRegionList::iterator it;
	for (it = m_image.begin(); it != m_image.end(); ++it)
	{
		if (it->m_data)
		{
			delete [] it->m_data;
			it->m_data = NULL;
		}
	}
}

//! A copy of \a inName is made, so the original may be disposed of by the caller
//! after this method returns.
void StExecutableImage::setName(const std::string & inName)
{
	m_name = inName;
}

std::string StExecutableImage::getName() const
{
	return m_name;
}

// The region is added with read and write flags set.
//! \exception std::runtime_error will be thrown if the new overlaps an
//!		existing region.
void StExecutableImage::addFillRegion(uint32_t inAddress, unsigned inLength)
{
	MemoryRegion region;
	region.m_type = FILL_REGION;
	region.m_address = inAddress;
	region.m_data = NULL;
	region.m_length = inLength;
	region.m_flags = REGION_RW_FLAG;
	
	insertOrMergeRegion(region);
}

//! A copy of \a inData is made before returning. The copy will be deleted when 
//! the executable image is destructed. Currently, the text region is created with
//! read, write, and executable flags set.
//! \exception std::runtime_error will be thrown if the new overlaps an
//!		existing region.
//! \exception std::bad_alloc is thrown if memory for the copy of \a inData
//!		cannot be allocated.
void StExecutableImage::addTextRegion(uint32_t inAddress, const uint8_t * inData, unsigned inLength)
{
	MemoryRegion region;
	region.m_type = TEXT_REGION;
	region.m_address = inAddress;
	region.m_flags = REGION_RW_FLAG | REGION_EXEC_FLAG;
	
	// copy the data
	region.m_data = new uint8_t[inLength];
	region.m_length = inLength;
	memcpy(region.m_data, inData, inLength);
	
	insertOrMergeRegion(region);
}

//! \exception std::out_of_range is thrown if \a inIndex is out of range.
//!
const StExecutableImage::MemoryRegion & StExecutableImage::getRegionAtIndex(unsigned inIndex) const
{
	// check bounds
	if (inIndex >= m_image.size())
		throw std::out_of_range("inIndex");
	
	// find region by index
	MemoryRegionList::const_iterator it = m_image.begin();
	unsigned i = 0;
	for (; it != m_image.end(); ++it, ++i)
	{
		if (i == inIndex)
			break;
	}
	return *it;
}

//! The list of address filters is kept sorted as filters are added.
//!
void StExecutableImage::addAddressFilter(const AddressFilter & filter)
{
    m_filters.push_back(filter);
    m_filters.sort();
}

//!
void StExecutableImage::clearAddressFilters()
{
    m_filters.clear();
}

//! \exception StExecutableImage::address_filter_exception Raised when a filter
//!     with the type #ADDR_FILTER_ERROR or #ADDR_FILTER_WARNING is matched.
//!
//! \todo Build a list of all matching filters and then execute them at once.
//!     For the warning and error filters, a single exception should be raised
//!     that identifies all the overlapping errors. Currently the user will only
//!     see the first (lowest address) overlap.
void StExecutableImage::applyAddressFilters()
{
restart_loops:
    // Iterate over filters.
    AddressFilterList::const_iterator fit = m_filters.begin();
    for (; fit != m_filters.end(); ++fit)
    {
        const AddressFilter & filter = *fit;
        
        // Iterator over regions.
        MemoryRegionList::iterator rit = m_image.begin();
        for (; rit != m_image.end(); ++rit)
        {
            MemoryRegion & region = *rit;
            
            if (filter.matchesMemoryRegion(region))
            {
                switch (filter.m_action)
                {
                    case ADDR_FILTER_NONE:
                        // Do nothing.
                        break;
                        
                    case ADDR_FILTER_ERROR:
                        // throw error exception
                        throw address_filter_exception(true, m_name, filter);
                        break;
                        
                    case ADDR_FILTER_WARNING:
                        // throw warning exception
                        throw address_filter_exception(false, m_name, filter);
                        break;
                        
                    case ADDR_FILTER_CROP:
                        // Delete the offending portion of the region and restart
                        // the iteration loops.
                        cropRegionToFilter(region, filter);
                        goto restart_loops;
                        break;
                }
            }
        }
    }
}

//! There are several possible cases here:
//!     - No overlap at all. Nothing is done.
//!
//!     - All of the memory region is matched by the \a filter. The region is
//!         removed from #StExecutableImage::m_image and its data memory freed.
//!
//!     - The remaining portion of the region is one contiguous chunk. In this
//!         case, \a region is simply modified. 
//!
//!     - The region is split in the middle by the filter. The original \a region
//!         is modified to match the first remaining chunk. And a new #StExecutableImage::MemoryRegion
//!         instance is created to hold the other leftover piece.
void StExecutableImage::cropRegionToFilter(MemoryRegion & region, const AddressFilter & filter)
{
    uint32_t firstByte = region.m_address;      // first byte occupied by this region
    uint32_t lastByte = region.endAddress();    // last used byte in this region
    
    // compute new address range
    uint32_t cropFrom = filter.m_fromAddress;
    if (cropFrom < firstByte)
    {
        cropFrom = firstByte;
    }
    
    uint32_t cropTo = filter.m_toAddress;
    if (cropTo > lastByte)
    {
        cropTo = lastByte;
    }
    
    // is there actually a match?
    if (cropFrom > filter.m_toAddress || cropTo < filter.m_fromAddress)
    {
        // nothing to do, so bail
        return;
    }
    
    printf("Deleting region 0x%08x-0x%08x\n", cropFrom, cropTo);
    
    // handle if the entire region is to be deleted
    if (cropFrom == firstByte && cropTo == lastByte)
    {
        delete [] region.m_data;
        region.m_data = NULL;
        m_image.remove(region);
    }
    
    // there is at least a little of the original region remaining
    uint32_t newLength = cropTo - cropFrom + 1;
    uint32_t leftoverLength = lastByte - cropTo;
    uint8_t * oldData = region.m_data;
    
    // update the region
    region.m_address = cropFrom;
    region.m_length = newLength;
    
    // crop data buffer for text regions
    if (region.m_type == TEXT_REGION && oldData)
    {
        region.m_data = new uint8_t[newLength];
        memcpy(region.m_data, &oldData[cropFrom - firstByte], newLength);
        
        // dispose of old data
        delete [] oldData;
    }
    
    // create a new region for any part of the original region that was past
    // the crop to address. this will happen if the filter range falls in the
    // middle of the region.
    if (leftoverLength)
    {
        MemoryRegion newRegion;
        newRegion.m_type = region.m_type;
        newRegion.m_flags = region.m_flags;
        newRegion.m_address = cropTo + 1;
        newRegion.m_length = leftoverLength;
        
        if (region.m_type == TEXT_REGION && oldData)
        {
            newRegion.m_data = new uint8_t[leftoverLength];
            memcpy(newRegion.m_data, &oldData[cropTo - firstByte + 1], leftoverLength);
        }
        
        insertOrMergeRegion(newRegion);
    }
}

//! \exception std::runtime_error will be thrown if \a inRegion overlaps an
//!		existing region.
//!
//! \todo Need to investigate if we can use the STL sort algorithm at all. Even
//!     though we're doing merges too, we could sort first then examine the list
//!     for merges.
void StExecutableImage::insertOrMergeRegion(MemoryRegion & inRegion)
{
	uint32_t newStart = inRegion.m_address;
	uint32_t newEnd = newStart + inRegion.m_length;
	
	MemoryRegionList::iterator it = m_image.begin();
	for (; it != m_image.end(); ++it)
	{
		MemoryRegion & region = *it;
		uint32_t thisStart = region.m_address;
		uint32_t thisEnd = thisStart + region.m_length;
		
		// keep track of where to insert it to retain sort order
		if (thisStart >= newEnd)
		{
			break;
		}
			
		// region types and flags must match in order to merge
		if (region.m_type == inRegion.m_type && region.m_flags == inRegion.m_flags)
		{
			if (newStart == thisEnd || newEnd == thisStart)
			{
				mergeRegions(region, inRegion);
				return;
			}
			else if ((newStart >= thisStart && newStart < thisEnd) || (newEnd >= thisStart && newEnd < thisEnd))
			{
				throw std::runtime_error("new region overlaps existing region");
			}
		}
	}
	
	// not merged, so just insert it in the sorted position
	m_image.insert(it, inRegion);
}

//! Extends \a inNewRegion to include the data in \a inOldRegion. It is
//! assumed that the two regions are compatible. The new region may come either
//! before or after the old region in memory. Note that while the two regions
//! don't necessarily have to be touching, it's probably a good idea. That's
//! because any data between the regions will be set to 0.
//!
//! For TEXT_REGION types, the two original regions will have their data deleted
//! during the merge. Thus, this method is not safe if any outside callers may
//! be accessing the region's data.
void StExecutableImage::mergeRegions(MemoryRegion & inOldRegion, MemoryRegion & inNewRegion)
{
	bool isOldBefore = inOldRegion.m_address < inNewRegion.m_address;
	uint32_t oldEnd = inOldRegion.m_address + inOldRegion.m_length;
	uint32_t newEnd = inNewRegion.m_address + inNewRegion.m_length;
	
	switch (inOldRegion.m_type)
	{
		case TEXT_REGION:
		{
			// calculate new length
			unsigned newLength;
			if (isOldBefore)
			{
				newLength = newEnd - inOldRegion.m_address;
			}
			else
			{
				newLength = oldEnd - inNewRegion.m_address;
			}
			
			// alloc memory
			uint8_t * newData = new uint8_t[newLength];
			memset(newData, 0, newLength);
			
			// copy data from the two regions into new block
			if (isOldBefore)
			{
				memcpy(newData, inOldRegion.m_data, inOldRegion.m_length);
				memcpy(&newData[newLength - inNewRegion.m_length], inNewRegion.m_data, inNewRegion.m_length);
			}
			else
			{
				memcpy(newData, inNewRegion.m_data, inNewRegion.m_length);
				memcpy(&newData[newLength - inOldRegion.m_length], inOldRegion.m_data, inOldRegion.m_length);
				
				inOldRegion.m_address = inNewRegion.m_address;
			}
			
			// replace old region's data
			delete [] inOldRegion.m_data;
			inOldRegion.m_data = newData;
			inOldRegion.m_length = newLength;
			
			// delete new region's data
			delete [] inNewRegion.m_data;
			inNewRegion.m_data = NULL;
			break;
		}
			
		case FILL_REGION:
		{
			if (isOldBefore)
			{
				inOldRegion.m_length = newEnd - inOldRegion.m_address;
			}
			else
			{
				inOldRegion.m_length = oldEnd - inNewRegion.m_address;
				inOldRegion.m_address = inNewRegion.m_address;
			}
			break;
		}
	}
}

//! Used when we remove a region from the region list by value. Because this
//! operator compares the #m_data member, it will only return true for either an
//! exact copy or a reference to the original.
bool StExecutableImage::MemoryRegion::operator == (const MemoryRegion & other)
{
   return (m_type == other.m_type) && (m_address == other.m_address) && (m_length == other.m_length) && (m_flags == other.m_flags) && (m_data == other.m_data);
}

//! Returns true if the address filter overlaps \a region.
bool StExecutableImage::AddressFilter::matchesMemoryRegion(const MemoryRegion & region) const
{
    uint32_t firstByte = region.m_address;      // first byte occupied by this region
    uint32_t lastByte = region.endAddress();    // last used byte in this region
    return (firstByte >= m_fromAddress && firstByte <= m_toAddress) || (lastByte >= m_fromAddress && lastByte <= m_toAddress);
}

//! The comparison does \em not take the action into account. It only looks at the
//! priority and address ranges of each filter. Priority is considered only if the two
//! filters overlap. Lower priority filters will come after higher priority ones.
//!
//! \retval -1 This filter is less than filter \a b.
//! \retval 0 This filter is equal to filter \a b.
//! \retval 1 This filter is greater than filter \a b.
int StExecutableImage::AddressFilter::compare(const AddressFilter & other) const
{
    if (m_priority != other.m_priority && ((m_fromAddress >= other.m_fromAddress && m_fromAddress <= other.m_toAddress) || (m_toAddress >= other.m_fromAddress && m_toAddress <= other.m_toAddress)))
    {
        // we know the priorities are not equal
        if (m_priority > other.m_priority)
        {
            return -1;
        }
        else
        {
            return 1;
        }
    }
    
    if (m_fromAddress == other.m_fromAddress)
    {
        if (m_toAddress == other.m_toAddress)
        {
            return 0;
        }
        else if (m_toAddress < other.m_toAddress)
        {
            return -1;
        }
        else
        {
            return 1;
        }
    }
    else if (m_fromAddress < other.m_fromAddress)
    {
        return -1;
    }
    else
    {
        return 1;
    }
}