forked from scanmem/scanmem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathendianness.c
91 lines (78 loc) · 2.4 KB
/
endianness.c
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
/*
$Id: $
Copyright (C) 2014 Hraban Luyat
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "endianness.h"
#include "scanmem.h"
#include "value.h"
static uint16_t swap_bytes16(uint16_t i)
{
uint16_t res = i & 0xff;
res <<= 8;
res |= i >> 8;
return res;
}
static uint32_t swap_bytes32(uint32_t i)
{
uint32_t res = swap_bytes16(i);
res <<= 16;
res |= swap_bytes16(i >> 16);
return res;
}
static uint64_t swap_bytes64(uint64_t i)
{
uint64_t res = swap_bytes32(i);
res <<= 32;
res |= swap_bytes32(i >> 32);
return res;
}
// swap endianness of 2, 4 or 8 byte word in-place.
void swap_bytes_var(void *p, size_t num)
{
switch (num) {
case sizeof(uint16_t): ; // empty statement to cheat the compiler
uint16_t i16 = swap_bytes16(*((uint16_t *)p));
memcpy(p, &i16, sizeof(uint16_t));
return;
case sizeof(uint32_t): ;
uint32_t i32 = swap_bytes32(*((uint32_t *)p));
memcpy(p, &i32, sizeof(uint32_t));
return;
case sizeof(uint64_t): ;
uint64_t i64 = swap_bytes64(*((uint64_t *)p));
memcpy(p, &i64, sizeof(uint64_t));
return;
}
assert(false);
return;
}
void fix_endianness(globals_t *vars, value_t *data_value)
{
if (!vars->options.reverse_endianness) {
return;
}
if (data_value->flags.u64b) {
data_value->uint64_value = swap_bytes64(data_value->uint64_value);
} else if (data_value->flags.u32b) {
data_value->uint32_value = swap_bytes32(data_value->uint32_value);
} else if (data_value->flags.u16b) {
data_value->uint16_value = swap_bytes16(data_value->uint16_value);
}
return;
}