├── .gitignore
├── CFG_reconstructor.py
├── LICENSE
├── Locals.props
├── Paper.pdf
├── README.md
├── icount
├── MyPinTool.sln
├── MyPinTool.vcxproj
├── MyPinTool.vcxproj.filters
├── MyPinTool.vcxproj.user
├── Win32
│ └── Debug
│ │ └── MyPinTool.log
├── callbacks.cpp
├── callbacks.h
├── constants.h
├── dump.cpp
├── dump.h
├── error_handlers.h
├── flusher.cpp
├── flusher.h
├── json.cpp
├── json.h
├── loggers.h
├── main.cpp
├── main.h
├── offline_flushed.cpp
├── proc.h
├── report.cpp
├── report.h
└── utils.h
├── performance_parser.py
├── pintools.sln
└── tester.ps1
/.gitignore:
--------------------------------------------------------------------------------
1 | # Spare
2 | idapython
3 | .vs
4 | .vscode
5 | CFG.gv*
6 |
7 | # Byte-compiled / optimized / DLL files
8 | __pycache__/
9 | *.py[cod]
10 | *$py.class
11 |
12 | # C extensions
13 | *.so
14 |
15 | # Distribution / packaging
16 | .Python
17 | build/
18 | develop-eggs/
19 | dist/
20 | downloads/
21 | eggs/
22 | .eggs/
23 | lib/
24 | lib64/
25 | parts/
26 | sdist/
27 | var/
28 | wheels/
29 | *.egg-info/
30 | .installed.cfg
31 | *.egg
32 | MANIFEST
33 |
34 | # PyInstaller
35 | # Usually these files are written by a python script from a template
36 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
37 | *.manifest
38 | *.spec
39 |
40 | # Installer logs
41 | pip-log.txt
42 | pip-delete-this-directory.txt
43 |
44 | # Unit test / coverage reports
45 | htmlcov/
46 | .tox/
47 | .coverage
48 | .coverage.*
49 | .cache
50 | nosetests.xml
51 | coverage.xml
52 | *.cover
53 | .hypothesis/
54 | .pytest_cache/
55 |
56 | # Translations
57 | *.mo
58 | *.pot
59 |
60 | # Django stuff:
61 | *.log
62 | local_settings.py
63 | db.sqlite3
64 |
65 | # Flask stuff:
66 | instance/
67 | .webassets-cache
68 |
69 | # Scrapy stuff:
70 | .scrapy
71 |
72 | # Sphinx documentation
73 | docs/_build/
74 |
75 | # PyBuilder
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # pyenv
82 | .python-version
83 |
84 | # celery beat schedule file
85 | celerybeat-schedule
86 |
87 | # SageMath parsed files
88 | *.sage.py
89 |
90 | # Environments
91 | .env
92 | .venv
93 | env/
94 | venv/
95 | ENV/
96 | env.bak/
97 | venv.bak/
98 |
99 | # Spyder project settings
100 | .spyderproject
101 | .spyproject
102 |
103 | # Rope project settings
104 | .ropeproject
105 |
106 | # mkdocs documentation
107 | /site
108 |
109 | # mypy
110 | .mypy_cache/
111 |
112 | # Prerequisites
113 | *.d
114 |
115 | # Compiled Object files
116 | *.slo
117 | *.lo
118 | *.o
119 | *.obj
120 |
121 | # Precompiled Headers
122 | *.gch
123 | *.pch
124 |
125 | # Compiled Dynamic libraries
126 | *.so
127 | *.dylib
128 | *.dll
129 |
130 | # Fortran module files
131 | *.mod
132 | *.smod
133 |
134 | # Compiled Static libraries
135 | *.lai
136 | *.la
137 | *.a
138 | *.lib
139 |
140 | # Executables
141 | *.exe
142 | *.out
143 | *.app
144 |
145 | # Visual Studio
146 | .vs/
147 | ## Ignore Visual Studio temporary files, build results, and
148 | ## files generated by popular Visual Studio add-ons.
149 | ##
150 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
151 |
152 | # User-specific files
153 | *.suo
154 | *.user
155 | *.userosscache
156 | *.sln.docstates
157 |
158 | # User-specific files (MonoDevelop/Xamarin Studio)
159 | *.userprefs
160 |
161 | # Build results
162 | [Dd]ebug/
163 | [Dd]ebugPublic/
164 | [Rr]elease/
165 | [Rr]eleases/
166 | x64/
167 | x86/
168 | bld/
169 | [Bb]in/
170 | [Oo]bj/
171 | [Ll]og/
172 |
173 | # Visual Studio 2015/2017 cache/options directory
174 | .vs/
175 | # Uncomment if you have tasks that create the project's static files in wwwroot
176 | #wwwroot/
177 |
178 | # Visual Studio 2017 auto generated files
179 | Generated\ Files/
180 |
181 | # MSTest test Results
182 | [Tt]est[Rr]esult*/
183 | [Bb]uild[Ll]og.*
184 |
185 | # NUNIT
186 | *.VisualState.xml
187 | TestResult.xml
188 |
189 | # Build Results of an ATL Project
190 | [Dd]ebugPS/
191 | [Rr]eleasePS/
192 | dlldata.c
193 |
194 | # Benchmark Results
195 | BenchmarkDotNet.Artifacts/
196 |
197 | # .NET Core
198 | project.lock.json
199 | project.fragment.lock.json
200 | artifacts/
201 |
202 | # StyleCop
203 | StyleCopReport.xml
204 |
205 | # Files built by Visual Studio
206 | *_i.c
207 | *_p.c
208 | *_i.h
209 | *.ilk
210 | *.meta
211 | *.obj
212 | *.iobj
213 | *.pch
214 | *.pdb
215 | *.ipdb
216 | *.pgc
217 | *.pgd
218 | *.rsp
219 | *.sbr
220 | *.tlb
221 | *.tli
222 | *.tlh
223 | *.tmp
224 | *.tmp_proj
225 | *.log
226 | *.vspscc
227 | *.vssscc
228 | .builds
229 | *.pidb
230 | *.svclog
231 | *.scc
232 |
233 | # Chutzpah Test files
234 | _Chutzpah*
235 |
236 | # Visual C++ cache files
237 | ipch/
238 | *.aps
239 | *.ncb
240 | *.opendb
241 | *.opensdf
242 | *.sdf
243 | *.cachefile
244 | *.VC.db
245 | *.VC.VC.opendb
246 |
247 | # Visual Studio profiler
248 | *.psess
249 | *.vsp
250 | *.vspx
251 | *.sap
252 |
253 | # Visual Studio Trace Files
254 | *.e2e
255 |
256 | # TFS 2012 Local Workspace
257 | $tf/
258 |
259 | # Guidance Automation Toolkit
260 | *.gpState
261 |
262 | # ReSharper is a .NET coding add-in
263 | _ReSharper*/
264 | *.[Rr]e[Ss]harper
265 | *.DotSettings.user
266 |
267 | # JustCode is a .NET coding add-in
268 | .JustCode
269 |
270 | # TeamCity is a build add-in
271 | _TeamCity*
272 |
273 | # DotCover is a Code Coverage Tool
274 | *.dotCover
275 |
276 | # AxoCover is a Code Coverage Tool
277 | .axoCover/*
278 | !.axoCover/settings.json
279 |
280 | # Visual Studio code coverage results
281 | *.coverage
282 | *.coveragexml
283 |
284 | # NCrunch
285 | _NCrunch_*
286 | .*crunch*.local.xml
287 | nCrunchTemp_*
288 |
289 | # MightyMoose
290 | *.mm.*
291 | AutoTest.Net/
292 |
293 | # Web workbench (sass)
294 | .sass-cache/
295 |
296 | # Installshield output folder
297 | [Ee]xpress/
298 |
299 | # DocProject is a documentation generator add-in
300 | DocProject/buildhelp/
301 | DocProject/Help/*.HxT
302 | DocProject/Help/*.HxC
303 | DocProject/Help/*.hhc
304 | DocProject/Help/*.hhk
305 | DocProject/Help/*.hhp
306 | DocProject/Help/Html2
307 | DocProject/Help/html
308 |
309 | # Click-Once directory
310 | publish/
311 |
312 | # Publish Web Output
313 | *.[Pp]ublish.xml
314 | *.azurePubxml
315 | # Note: Comment the next line if you want to checkin your web deploy settings,
316 | # but database connection strings (with potential passwords) will be unencrypted
317 | *.pubxml
318 | *.publishproj
319 |
320 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
321 | # checkin your Azure Web App publish settings, but sensitive information contained
322 | # in these scripts will be unencrypted
323 | PublishScripts/
324 |
325 | # NuGet Packages
326 | *.nupkg
327 | # The packages folder can be ignored because of Package Restore
328 | **/[Pp]ackages/*
329 | # except build/, which is used as an MSBuild target.
330 | !**/[Pp]ackages/build/
331 | # Uncomment if necessary however generally it will be regenerated when needed
332 | #!**/[Pp]ackages/repositories.config
333 | # NuGet v3's project.json files produces more ignorable files
334 | *.nuget.props
335 | *.nuget.targets
336 |
337 | # Microsoft Azure Build Output
338 | csx/
339 | *.build.csdef
340 |
341 | # Microsoft Azure Emulator
342 | ecf/
343 | rcf/
344 |
345 | # Windows Store app package directories and files
346 | AppPackages/
347 | BundleArtifacts/
348 | Package.StoreAssociation.xml
349 | _pkginfo.txt
350 | *.appx
351 |
352 | # Visual Studio cache files
353 | # files ending in .cache can be ignored
354 | *.[Cc]ache
355 | # but keep track of directories ending in .cache
356 | !*.[Cc]ache/
357 |
358 | # Others
359 | ClientBin/
360 | ~$*
361 | *~
362 | *.dbmdl
363 | *.dbproj.schemaview
364 | *.jfm
365 | *.pfx
366 | *.publishsettings
367 | orleans.codegen.cs
368 |
369 | # Including strong name files can present a security risk
370 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
371 | #*.snk
372 |
373 | # Since there are multiple workflows, uncomment next line to ignore bower_components
374 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
375 | #bower_components/
376 |
377 | # RIA/Silverlight projects
378 | Generated_Code/
379 |
380 | # Backup & report files from converting an old project file
381 | # to a newer Visual Studio version. Backup files are not needed,
382 | # because we have git ;-)
383 | _UpgradeReport_Files/
384 | Backup*/
385 | UpgradeLog*.XML
386 | UpgradeLog*.htm
387 | ServiceFabricBackup/
388 | *.rptproj.bak
389 |
390 | # SQL Server files
391 | *.mdf
392 | *.ldf
393 | *.ndf
394 |
395 | # Business Intelligence projects
396 | *.rdl.data
397 | *.bim.layout
398 | *.bim_*.settings
399 | *.rptproj.rsuser
400 |
401 | # Microsoft Fakes
402 | FakesAssemblies/
403 |
404 | # GhostDoc plugin setting file
405 | *.GhostDoc.xml
406 |
407 | # Node.js Tools for Visual Studio
408 | .ntvs_analysis.dat
409 | node_modules/
410 |
411 | # Visual Studio 6 build log
412 | *.plg
413 |
414 | # Visual Studio 6 workspace options file
415 | *.opt
416 |
417 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
418 | *.vbw
419 |
420 | # Visual Studio LightSwitch build output
421 | **/*.HTMLClient/GeneratedArtifacts
422 | **/*.DesktopClient/GeneratedArtifacts
423 | **/*.DesktopClient/ModelManifest.xml
424 | **/*.Server/GeneratedArtifacts
425 | **/*.Server/ModelManifest.xml
426 | _Pvt_Extensions
427 |
428 | # Paket dependency manager
429 | .paket/paket.exe
430 | paket-files/
431 |
432 | # FAKE - F# Make
433 | .fake/
434 |
435 | # JetBrains Rider
436 | .idea/
437 | *.sln.iml
438 |
439 | # CodeRush
440 | .cr/
441 |
442 | # Python Tools for Visual Studio (PTVS)
443 | __pycache__/
444 | *.pyc
445 |
446 | # Cake - Uncomment if you are using it
447 | # tools/**
448 | # !tools/packages.config
449 |
450 | # Tabs Studio
451 | *.tss
452 |
453 | # Telerik's JustMock configuration file
454 | *.jmconfig
455 |
456 | # BizTalk build output
457 | *.btp.cs
458 | *.btm.cs
459 | *.odx.cs
460 | *.xsd.cs
461 |
462 | # OpenCover UI analysis results
463 | OpenCover/
464 |
465 | # Azure Stream Analytics local run output
466 | ASALocalRun/
467 |
468 | # MSBuild Binary and Structured Log
469 | *.binlog
470 |
471 | # NVidia Nsight GPU debugger configuration file
472 | *.nvuser
473 |
474 | # MFractors (Xamarin productivity tool) working folder
475 | .mfractor/
476 |
477 | # Pin
478 | pin.log
479 | *.db
480 | *opendb
481 |
--------------------------------------------------------------------------------
/CFG_reconstructor.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | from graphviz import Digraph
4 | from capstone import *
5 | from collections import namedtuple
6 |
7 | TRACE_LIMIT = 9999999
8 |
9 | dot = Digraph(comment="Alamanas")
10 | dot.attr('node', shape='box')
11 |
12 | md = Cs(CS_ARCH_X86, CS_MODE_32)
13 | Instruction = namedtuple('Instruction', 'address disasm')
14 |
15 | global report, images, sections
16 | report = {}
17 | images = {}
18 | sections = {}
19 |
20 | main_image = ''
21 | text_instr = []
22 | global text_low, text_high, text_section
23 | text_low = 0x0
24 | text_high = 0x0
25 | text_section = ''
26 |
27 | # Trying to understand why some parts are not found
28 | global intervals
29 | intervals = []
30 | def updateIntervals(a, b):
31 | global intervals
32 | found = False
33 | for i in intervals:
34 | if i[0] <= a <= i[1]:
35 | found = True
36 | if b > i[1]:
37 | i[1] = b
38 |
39 | if i[0] <= b <= i[1]:
40 | found = True
41 | if a < i[0]:
42 | i[0] = a
43 | if not found:
44 | intervals += [[a, b]]
45 |
46 | def load_report():
47 | global report, images, sections
48 | global text_low, text_high, text_section
49 | with open("report.json") as f:
50 | report = json.load(f)
51 |
52 | images = report["images"]
53 | main_image = report["main_image"]
54 |
55 | sections = report["sections"]
56 | text_section = report['text_section']
57 | text_low = sections[text_section]['address']
58 | text_size = sections[text_section]['size']
59 | text_low = text_low
60 | text_size = text_size
61 | text_high = text_low + text_size
62 |
63 | def disasm_text_section():
64 | global text_low, text_high, text_section
65 | instructions = []
66 | disasm_file = open("TEXT.disasm", "w+")
67 | with open(text_section + '.dump', 'rb') as f:
68 | for i in md.disasm(f.read(), text_low):
69 | instructions += [Instruction(address=(i.address), disasm=i.mnemonic + ' ' + i.op_str)]
70 | print("0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str), file=disasm_file)
71 | return instructions
72 |
73 | def getDisasmInRange(a:int, b:int):
74 | instructions = []
75 | if (a > b) :
76 | print('Switched intervals {} {}'.format(a, b))
77 | for i in text_instr:
78 | if a <= i.address < b:
79 | instructions += [i.disasm]
80 | if len(instructions) == 0:
81 | # print('Nothing found from {} to {}'.format(hex(a), hex(b)))
82 | updateIntervals(min(a, b), max(a, b))
83 | return instructions
84 |
85 | def insertExternalStub(last_ip:str):
86 | found = False
87 | for name, mem_range in images.items():
88 | if mem_range['low_address'] <= int(last_ip, 16) <= mem_range['high_address']:
89 | found = True
90 | short_name = name[name.rfind('\\')+1:]
91 | dot.node(last_ip, label=short_name, shape='ellipse')
92 | if not found:
93 | dot.node(last_ip, label='Stub', shape='ellipse')
94 |
95 | def parse_trace():
96 | with open('trace_0.out') as f:
97 | lines_no = 0
98 | edges = set()
99 | last_ip = '0x0'
100 | for line in f:
101 | # Cleanup the string
102 | line = line.replace('\x00', '').strip()
103 | if len(line) == 0:
104 | continue
105 |
106 | ip, target = line.split('@')
107 | # Very first instruction
108 | if ip == '':
109 | last_ip = target
110 | continue
111 |
112 | if not (text_low <= int(last_ip, 16) <= text_high):
113 | insertExternalStub(last_ip)
114 | else:
115 | instr_in_range = getDisasmInRange(int(last_ip, 16), int(ip, 16))
116 | dot.node(last_ip, label='\n'.join(instr_in_range))
117 | edges.add((last_ip, target))
118 | last_ip = target
119 |
120 | if lines_no >= TRACE_LIMIT:
121 | break
122 | lines_no += 1
123 |
124 | dot.edges(list(edges))
125 |
126 |
127 | if __name__ == "__main__":
128 | load_report()
129 | text_instr = disasm_text_section()
130 | parse_trace()
131 | dot.render('CFG.gv', view=True)
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Andrea Tulimiero
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Locals.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | C:\Pin35
6 |
7 |
8 | <_PropertySheetDisplayName>Locals
9 |
10 |
11 |
12 |
13 | $(PinFolder)
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Paper.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/andreatulimiero/PinCFGReconstructor/eaa3b913321aa17505a5af718873dbec1482d45b/Paper.pdf
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PinCFGReconstructor
2 |
3 | ## TL;DR
4 | An efficient Pintool to reconstruct the Control Flow Graph (CFG) of plain and UPX packed executables.
5 |
6 | ## Abstract
7 | With the development of increasingly advanced techniques to hide the malicious
8 | payload of a Malware, the community of reverse engineers and security researchers
9 | has been facing more and more complex programs which brought about the need of
10 | more advanced analysis than classic ones based on static code inspection. To truly
11 | understand what such malicious programs do, an analyst needs to look at them
12 | while they are executing, thus tools to carry out their analyses at runtime have
13 | become one of the most powerful weapons to face new threats.
14 | Among the techniques for the design and implementation of such tools there is
15 | dynamic binary instrumentation (DBI), an advanced solution that makes it possible
16 | to instrument a program dynamically (i.e., while it is running), allowing for a
17 | fine-grained inspection of its execution. Although this technique is very powerful,
18 | it carries with it some performance and accuracy trade-offs. In this project we will
19 | build tools to record instructions and reconstruct the control flow graph of a possibly
20 | malicious program, discussing during the journey the challenges introduced by the
21 | usage of DBI and proposing some solutions to mitigate these problems.
22 |
23 | ## Dependencies
24 | - [Intel PIN](https://software.intel.com/sites/landingpage/pintool/downloads/pin-3.5-97503-gac534ca30-msvc-windows.zip)
25 | - [Capstone](https://www.capstone-engine.org/download.html)
26 | - [Graphviz](https://www.graphviz.org/download)
27 | - [Python 3.6.3](https://www.python.org/downloads/release/python-363)
28 | - The solution has been compiled using Visual Studio 2010 (v100) toolset. I strongly advise to install [Visual C++ 2010 Express Edition](https://my.visualstudio.com/Downloads?q=visual%20studio%202010&wt.mc_id=o~msft~vscom~older-downloads) (to get the toolset), and then using Visual Studio 2015 or later IDE.
29 |
30 | ## Usage
31 | Assuming Intel Pin folder is located at `C:\Pin35`, you can launch the tool with the following structure:
32 | `C:\Pin35\pin.exe -t C:\Pin35\icount.dll -- `
33 | By default the tool uses the Unbuffered version and generates a trace of 2Gb maximum
34 | Once the tool finishes instrumenting the executable it generates: a (i)`trace.out` file; a (ii)dump of each of the sections of the program; and a (iii) `report.json` file containing information about the executed programs (e.g.: Sections' low addresses and size).
35 | Once the analysis is finished, the CFG can be reconstructed by launching `python CFG_reconstructor.py`. A PDF of the CFG will be shown and a file called CFG.gv.pdf will be created
36 |
37 | #### Pintool otions
38 | Apart from the standard switches of Intel Pin, the Pintool can be configured with these additional switches:
39 | - -**buffered** [default false]:
40 | whether or not the trace is buffered
41 | - -**thread_flushed** [default false]:
42 | whether or not the trace has a thread for flushing
43 | - -**favor_main_thread** [default false]:
44 | allocate only a quarter of thread buffer for threads that are not the main one
45 | - -**tag** [default ""]:
46 | tag for the performance report. If missing no report will be generated
47 | - -**thread_buffer_size** [default 30Mb]:
48 | size of the per-thread buffer
49 | - -**trace_limit** [default 2Gb]:
50 | size of the trace limit
51 |
52 | ### Notes
53 | The tool has been tested on Win32 only with UPX packer.
54 |
55 | ## Thanks
56 | This work has also been possible thanks to: [Capstone](https://github.com/aquynh/capstone) and [Graphviz](https://gitlab.com/graphviz/graphviz)
57 |
--------------------------------------------------------------------------------
/icount/MyPinTool.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 11.00
3 | # Visual Studio 2010
4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MyPinTool", "MyPinTool.vcxproj", "{639EF517-FCFC-408E-9500-71F0DC0458DB}"
5 | EndProject
6 | Global
7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
8 | Debug|Win32 = Debug|Win32
9 | Debug|x64 = Debug|x64
10 | Release|Win32 = Release|Win32
11 | Release|x64 = Release|x64
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|Win32.ActiveCfg = Debug|Win32
15 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|Win32.Build.0 = Debug|Win32
16 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x64.ActiveCfg = Debug|x64
17 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Debug|x64.Build.0 = Debug|x64
18 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|Win32.ActiveCfg = Release|Win32
19 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|Win32.Build.0 = Release|Win32
20 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x64.ActiveCfg = Release|x64
21 | {639EF517-FCFC-408E-9500-71F0DC0458DB}.Release|x64.Build.0 = Release|x64
22 | EndGlobalSection
23 | GlobalSection(SolutionProperties) = preSolution
24 | HideSolutionNode = FALSE
25 | EndGlobalSection
26 | EndGlobal
27 |
--------------------------------------------------------------------------------
/icount/MyPinTool.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | Win32
7 |
8 |
9 | Debug
10 | x64
11 |
12 |
13 | Release
14 | Win32
15 |
16 |
17 | Release
18 | x64
19 |
20 |
21 |
22 | {639EF517-FCFC-408E-9500-71F0DC0458DB}
23 | MyPinTool
24 | Win32Proj
25 | icount
26 |
27 |
28 |
29 | DynamicLibrary
30 | MultiByte
31 | true
32 | v100
33 |
34 |
35 | DynamicLibrary
36 | MultiByte
37 | true
38 | v100
39 |
40 |
41 | DynamicLibrary
42 | MultiByte
43 | true
44 | v100
45 |
46 |
47 | DynamicLibrary
48 | MultiByte
49 | true
50 | v100
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 | <_ProjectFileVersion>10.0.40219.1
74 | $(PinFolder)\
75 | $(PinFolder)\
76 | $(Platform)\$(Configuration)\
77 | $(Platform)\$(Configuration)\
78 | $(Platform)\$(Configuration)\
79 | $(Platform)\$(Configuration)\
80 | false
81 | false
82 | false
83 | false
84 | false
85 | false
86 | false
87 | false
88 | AllRules.ruleset
89 | AllRules.ruleset
90 | AllRules.ruleset
91 | AllRules.ruleset
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 | $(PinFolder)\intel64\lib;$(PinFolder)\intel64\runtime\pincrt;$(PinFolder\extras\xed-intel64;$(LibraryPath)
101 | $(WindowsSdkDir)\lib
102 | $(WindowsSdkDir)\lib\x64
103 | $(WindowsSdkDir)\lib
104 |
105 |
106 | $(PinFolder)\
107 | $(ProjectName)32
108 |
109 |
110 | $(PinFolder)\
111 | $(ProjectName)32
112 |
113 |
114 | $(ProjectName)64
115 |
116 |
117 |
118 | X64
119 |
120 |
121 | /EHs- /EHa- %(AdditionalOptions)
122 | true
123 | false
124 | $(PinFolder)\source\include\pin;$(PinFolder)\source\include\pin\gen;$(PinFolder)\extras\stlport\include;$(PinFolder)\extras;$(PinFolder)\extras\libstdc++\include;$(PinFolder)\extras\crt\include;$(PinFolder)\extras\crt;$(PinFolder)\extras\crt\include\arch-x86_64;$(PinFolder)\extras\components\include;$(PinFolder)\extras\crt\include\kernel\uapi;$(PinFolder)\extras\crt\include\kernel\uapi\asm-x86;$(PinFolder)\extras\xed-intel64\include\xed;$(AdditionalIncludeDirectories)
125 | TARGET_IA32E;__LP64__;HOST_IA32E;__PIN__=1;PIN_CRT=1;TARGET_WINDOWS;BIGARRAY_MULTIPLIER=1;_CRT_SECURE_NO_DEPRECATE;_SECURE_SCL=0;WIN32;_WINDOWS_H_PATH_=$(WindowsSdkDir)\Include;_PIN_FOLDER="$(PinFolder)"
126 | false
127 |
128 |
129 | Default
130 | MultiThreaded
131 | false
132 | true
133 | false
134 |
135 |
136 | Level3
137 |
138 |
139 | 4005;4530;%(DisableSpecificWarnings)
140 | include/msvc_compat.h
141 | false
142 |
143 |
144 | /export:main /ignore:4210 /ignore:4049 %(AdditionalOptions)
145 | $(PinFolder)\intel64\runtime\pincrt\crtbeginS.obj;pin.lib;xed.lib;pinvm.lib;stlport-static.lib;m-static.lib;c-static.lib;os-apis.lib;ntdll-64.lib;kernel32.lib;%(AdditionalDependencies)
146 | $(PinFolder)\intel64\lib;$(PinFolder)\intel64\lib-ext;$(PinFolder)\extras\xed-intel64\lib;%(AdditionalLibraryDirectories)
147 | true
148 | %(IgnoreSpecificDefaultLibraries)
149 | true
150 | NotSet
151 | true
152 |
153 |
154 |
155 |
156 | Ptrace_DllMainCRTStartup
157 | 0xC5000000
158 | MachineX64
159 | false
160 |
161 |
162 |
163 |
164 |
165 | /EHs- /EHa- %(AdditionalOptions)
166 | true
167 | false
168 | $(PinFolder)\source\include\pin;$(PinFolder)\source\include\pin\gen;$(PinFolder)\extras\stlport\include;$(PinFolder)\extras;$(PinFolder)\extras\libstdc++\include;$(PinFolder)\extras\crt\include;$(PinFolder)\extras\crt;$(PinFolder)\extras\crt\include\kernel\uapi;$(PinFolder)\extras\crt\include\kernel\uapi\asm-x86;$(PinFolder)\extras\components\include;$(PinFolder)\extras\crt\include\arch-x86;$(PinFolder)\extras\xed-ia32\include\xed
169 | TARGET_IA32;__i386__;HOST_IA32;__PIN__=1;PIN_CRT=1;TARGET_WINDOWS;BIGARRAY_MULTIPLIER=1;USING_XED;_CRT_SECURE_NO_DEPRECATE;_SECURE_SCL=0;WIN32;_WINDOWS_H_PATH_=$(WindowsSdkDir)\Include;_PIN_FOLDER="$(PinFolder)"
170 | false
171 |
172 |
173 | Default
174 | MultiThreaded
175 | false
176 | true
177 | false
178 |
179 |
180 | Level3
181 |
182 |
183 | 4005;4530;%(DisableSpecificWarnings)
184 | include/msvc_compat.h
185 | false
186 |
187 |
188 | /export:main /ignore:4210 /ignore:4049 %(AdditionalOptions)
189 | $(PinFolder)\ia32\runtime\pincrt\crtbeginS.obj;pin.lib;xed.lib;pinvm.lib;stlport-static.lib;m-static.lib;c-static.lib;os-apis.lib;ntdll-32.lib;kernel32.lib;%(AdditionalDependencies)
190 | $(PinFolder)\ia32\lib;$(PinFolder)\ia32\lib-ext;$(PinFolder)\ia32\runtime\pincrt\;$(PinFolder)\extras\xed-ia32\lib;%(AdditionalLibraryDirectories)
191 | true
192 | %(IgnoreSpecificDefaultLibraries)
193 | true
194 | NotSet
195 | true
196 |
197 |
198 |
199 |
200 | Ptrace_DllMainCRTStartup%4012
201 | 0x55000000
202 | false
203 |
204 |
205 |
206 |
207 | X64
208 |
209 |
210 | /EHs- /EHa- %(AdditionalOptions)
211 | false
212 | false
213 | $(PinFolder)\source\include\pin;$(PinFolder)\source\include\pin\gen;$(PinFolder)\extras\stlport\include;$(PinFolder)\extras;$(PinFolder)\extras\libstdc++\include;$(PinFolder)\extras\crt\include;$(PinFolder)\extras\crt;$(PinFolder)\extras\crt\include\arch-x86_64;$(PinFolder)\extras\components\include;$(PinFolder)\extras\crt\include\kernel\uapi;$(PinFolder)\extras\crt\include\kernel\uapi\asm-x86;$(PinFolder)\extras\xed-intel64\include\xed;$(AdditionalIncludeDirectories)
214 | false
215 |
216 |
217 | Default
218 | MultiThreaded
219 | false
220 | true
221 | false
222 |
223 |
224 | Level3
225 | ProgramDatabase
226 | 4005;4530;%(DisableSpecificWarnings)
227 | include/msvc_compat.h
228 | false
229 | TARGET_IA32E;__LP64__;HOST_IA32E;__PIN__=1;PIN_CRT=1;TARGET_WINDOWS;BIGARRAY_MULTIPLIER=1;_CRT_SECURE_NO_DEPRECATE;_SECURE_SCL=0;WIN32;_WINDOWS_H_PATH_=$(WindowsSdkDir)\Include;_PIN_FOLDER="$(PinFolder)"
230 |
231 |
232 | /export:main /ignore:4210 /ignore:4049 %(AdditionalOptions)
233 | $(PinFolder)\intel64\runtime\pincrt\crtbeginS.obj;pin.lib;xed.lib;pinvm.lib;stlport-static.lib;m-static.lib;c-static.lib;os-apis.lib;ntdll-64.lib;kernel32.lib;%(AdditionalDependencies)
234 | $(PinFolder)\intel64\lib;$(PinFolder)\intel64\lib-ext;$(PinFolder)\intel64\runtime\pincrt\;$(PinFolder)\extras\xed-intel64\lib;%(AdditionalLibraryDirectories)
235 | true
236 | %(IgnoreSpecificDefaultLibraries)
237 | true
238 | NotSet
239 | false
240 |
241 |
242 |
243 |
244 | Ptrace_DllMainCRTStartup
245 | 0xC5000000
246 | MachineX64
247 | false
248 |
249 |
250 |
251 |
252 |
253 | /EHs- /EHa- %(AdditionalOptions)
254 | false
255 | false
256 | $(PinFolder)\source\include\pin;$(PinFolder)\source\include\pin\gen;$(PinFolder)\extras\stlport\include;$(PinFolder)\extras;$(PinFolder)\extras\libstdc++\include;$(PinFolder)\extras\crt\include;$(PinFolder)\extras\crt;$(PinFolder)\extras\crt\include\kernel\uapi;$(PinFolder)\extras\crt\include\kernel\uapi\asm-x86;$(PinFolder)\extras\components\include;$(PinFolder)\extras\crt\include\arch-x86;$(PinFolder)\extras\xed-ia32\include\xed
257 | TARGET_IA32;__i386__;HOST_IA32;__PIN__=1;PIN_CRT=1;TARGET_WINDOWS;BIGARRAY_MULTIPLIER=1;USING_XED;_CRT_SECURE_NO_DEPRECATE;_SECURE_SCL=0;WIN32;_WINDOWS_H_PATH_=$(WindowsSdkDir)\Include;_PIN_FOLDER="$(PinFolder)"
258 | false
259 |
260 |
261 | Default
262 | MultiThreaded
263 | false
264 | true
265 | false
266 |
267 |
268 | Level3
269 | ProgramDatabase
270 | 4005;4530;%(DisableSpecificWarnings)
271 | include/msvc_compat.h
272 | false
273 | Disabled
274 | false
275 |
276 |
277 | /export:main /ignore:4210 /ignore:4049 %(AdditionalOptions)
278 | $(PinFolder)\ia32\runtime\pincrt\crtbeginS.obj;pin.lib;xed.lib;pinvm.lib;stlport-static.lib;m-static.lib;c-static.lib;os-apis.lib;ntdll-32.lib;kernel32.lib;%(AdditionalDependencies)
279 | $(PinFolder)\ia32\lib;$(PinFolder)\ia32\lib-ext;$(PinFolder)\ia32\runtime\pincrt\;$(PinFolder)\extras\xed-ia32\lib;%(AdditionalLibraryDirectories)
280 | true
281 | %(IgnoreSpecificDefaultLibraries)
282 | true
283 | NotSet
284 | false
285 |
286 |
287 |
288 |
289 | Ptrace_DllMainCRTStartup%4012
290 | 0x55000000
291 | false
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 |
--------------------------------------------------------------------------------
/icount/MyPinTool.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hpp;hxx;hm;inl;inc;xsd
11 |
12 |
13 |
14 |
15 | Header Files
16 |
17 |
18 | Header Files
19 |
20 |
21 | Header Files
22 |
23 |
24 | Header Files
25 |
26 |
27 | Header Files
28 |
29 |
30 | Header Files
31 |
32 |
33 | Header Files
34 |
35 |
36 | Header Files
37 |
38 |
39 | Header Files
40 |
41 |
42 | Header Files
43 |
44 |
45 | Header Files
46 |
47 |
48 |
49 |
50 | Source Files
51 |
52 |
53 | Source Files
54 |
55 |
56 | Source Files
57 |
58 |
59 | Source Files
60 |
61 |
62 | Source Files
63 |
64 |
65 | Source Files
66 |
67 |
68 |
--------------------------------------------------------------------------------
/icount/MyPinTool.vcxproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/icount/Win32/Debug/MyPinTool.log:
--------------------------------------------------------------------------------
1 | dump.cpp
2 | main.cpp
3 | callbacks.cpp
4 | flusher.cpp
5 | json.cpp
6 | report.cpp
7 | Generating Code...
8 | c:\users\tulim\works\pincfgreconstructor\icount\json.cpp(3095): warning C4715: 'Json::Value::asString' : not all control paths return a value
9 | c:\users\tulim\works\pincfgreconstructor\icount\json.cpp(3127): warning C4715: 'Json::Value::asInt' : not all control paths return a value
10 | c:\users\tulim\works\pincfgreconstructor\icount\json.cpp(3149): warning C4715: 'Json::Value::asUInt' : not all control paths return a value
11 | c:\users\tulim\works\pincfgreconstructor\icount\json.cpp(3172): warning C4715: 'Json::Value::asInt64' : not all control paths return a value
12 | c:\users\tulim\works\pincfgreconstructor\icount\json.cpp(3193): warning C4715: 'Json::Value::asUInt64' : not all control paths return a value
13 | c:\users\tulim\works\pincfgreconstructor\icount\json.cpp(3232): warning C4715: 'Json::Value::asDouble' : not all control paths return a value
14 | c:\users\tulim\works\pincfgreconstructor\icount\json.cpp(3255): warning C4715: 'Json::Value::asFloat' : not all control paths return a value
15 | c:\users\tulim\works\pincfgreconstructor\icount\json.cpp(3274): warning C4715: 'Json::Value::asBool' : not all control paths return a value
16 | Creating library C:\Pin35\icount32.lib and object C:\Pin35\icount32.exp
17 | json.obj : warning LNK4217: locally defined symbol ___sF imported in function "private: bool __thiscall Json::OurReader::decodeString(class Json::OurReader::Token &,class std::basic_string,class std::allocator > &)" (?decodeString@OurReader@Json@@AAE_NAAVToken@12@AAV?$basic_string@DV?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z)
18 | main.obj : warning LNK4217: locally defined symbol ___sF imported in function "void __cdecl `dynamic initializer for 'KnobTraceLimit''(void)" (??__EKnobTraceLimit@@YAXXZ)
19 | callbacks.obj : warning LNK4217: locally defined symbol ___sF imported in function "public: static bool __cdecl LEVEL_PINCLIENT::CLIENT_TLS::IsValidTlsKey(int,unsigned int)" (?IsValidTlsKey@CLIENT_TLS@LEVEL_PINCLIENT@@SA_NHI@Z)
20 | MyPinTool.vcxproj -> C:\Pin35\icount32.dll
21 |
--------------------------------------------------------------------------------
/icount/callbacks.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #include "callbacks.h"
4 | #include "main.h"
5 | #include "constants.h"
6 | #include "loggers.h"
7 | #include "utils.h"
8 | #include "error_handlers.h"
9 | #include
10 |
11 | void INS_EntryPoint(ADDRINT ip, THREADID thread_idx) {
12 | if (IN_RANGE(ip, main_img_memory.first, main_img_memory.second) &&
13 | proc_info->EP == INVALID_ENTRY_POINT) {
14 |
15 | proc_info->EP = ip;
16 | /* Allocate enough space in order to save:
17 | - @ char (1 byte)
18 | - address in hex format (sizeof(ADDRINT) * 2 bytes) for ip
19 | - 0 terminator (1 byte)*/
20 | size_t buf_len = sizeof(ADDRINT) * 2 + 2;
21 | char* buf = (char*) malloc(buf_len);
22 | sprintf(buf, "@%08x\0", ip);
23 |
24 | trace_t* trace = (trace_t*) PIN_GetThreadData(tls_key, thread_idx);
25 | // Trace limit guard
26 | if (traceLimitGuard(trace, buf_len, thread_idx)) return;
27 |
28 | if (isBuffered)
29 | recordTraceInMemory(buf, buf_len, trace)
30 | else
31 | recordTraceToFile(files[thread_idx], buf, buf_len, trace);
32 | }
33 | }
34 |
35 | void INS_Analysis(char* buf, UINT32 buf_len, THREADID thread_idx) {
36 | trace_t* trace = (trace_t*) PIN_GetThreadData(tls_key, thread_idx);
37 | // Trace limit guard
38 | if (traceLimitGuard(trace, buf_len, thread_idx)) return;
39 |
40 | if (isBuffered)
41 | recordTraceInMemory(buf, buf_len, trace)
42 | else
43 | recordTraceToFile(files[thread_idx], buf, buf_len, trace);
44 | }
45 |
46 | void INS_JumpAnalysis(ADDRINT ins_end, ADDRINT target_branch, INT32 taken, THREADID thread_idx) {
47 | if (!taken) return;
48 | trace_t* trace = (trace_t*) PIN_GetThreadData(tls_key, thread_idx);
49 | /* Allocate enough space in order to save:
50 | - @ char (1 byte)
51 | - address in hex format (sizeof(ADDRINT) * 2) * 2 bytes for ip and target
52 | - \n delimiter (1 byte)
53 | - 0 terminator (1 byte)*/
54 | size_t buf_len = (sizeof(ADDRINT) * 4 + 3);
55 | // Trace limit guard
56 | if (traceLimitGuard(trace, buf_len, thread_idx)) return;
57 |
58 | char* buf = (char*) malloc(sizeof(char) * buf_len);
59 | MALLOC_ERROR_HANDLER(buf, "[x] Not enough space to allocate the buf for the INS_JumpAnalysis\n");
60 | // Consider removing this sprintf since it is very slow
61 | sprintf(buf, "\n%08x@%08x\0", ins_end, target_branch);
62 |
63 | if (isBuffered)
64 | recordTraceInMemory(buf, buf_len, trace)
65 | else
66 | recordTraceToFile(files[thread_idx], buf, buf_len, trace);
67 |
68 | /* Since this buf is either flushed or copied in memory we can free it */
69 | free(buf);
70 | }
71 |
72 | void INS_WriteAnalysis(ADDRINT at, ADDRINT size) {
73 | if (upx_info->metJmp) return;
74 | time_t tv;
75 | START_STOPWATCH(tv);
76 | bool hasFoundRange = false;
77 | for each (pair interval in written_mem_intervals) {
78 | // Check if low address is in range
79 | if (IN_RANGE(at, interval.first, interval.second)) {
80 | // If high address is bigger than second interval enlarge it
81 | if ((at + size) > interval.second) interval.second = at + size;
82 | hasFoundRange = true;
83 | }
84 |
85 | // Check if high address is in range
86 | if (IN_RANGE(at + size, interval.first, interval.second)) {
87 | // If low address is smaller than first interval enlarge it
88 | if (at < interval.first) interval.first = at;
89 | hasFoundRange = true;
90 | }
91 | }
92 |
93 | // If no range has been found, let's create a new one
94 | if (!hasFoundRange)
95 | written_mem_intervals.push_front(make_pair(at, at + size));
96 | total_writed_intervals_creation_time += GET_STOPWATCH_LAP(tv);
97 | }
98 |
99 | void INS_UPXEndAnalysis(OPCODE opcode) {
100 | if (!upx_info->metJmp) {
101 | if (opcode == XED_ICLASS_PUSHAD)
102 | upx_info->metPushad = true;
103 | else if (upx_info->metPushad && opcode == XED_ICLASS_POPAD)
104 | upx_info->metPopad = true;
105 | else if (upx_info->metPopad && opcode == XED_ICLASS_JMP)
106 | upx_info->metJmp = true;
107 | }
108 | }
109 |
110 | void INS_WXorX(ADDRINT at, const char* disasm_ins) {
111 | time_t tv;
112 | START_STOPWATCH(tv);
113 | for each (pair interval in written_mem_intervals) {
114 | if (IN_RANGE(at, interval.first, interval.second)) {
115 | if (upx_info->OEP == INVALID_ENTRY_POINT)
116 | upx_info->OEP = at;
117 | fprintf(upx_dump_file, "%s", disasm_ins);
118 | }
119 | }
120 | total_wxorx_check_time += GET_STOPWATCH_LAP(tv);
121 | }
122 |
--------------------------------------------------------------------------------
/icount/callbacks.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include "pin.H"
4 |
5 | void INS_EntryPoint(ADDRINT ip, THREADID thread_idx);
6 | void INS_Analysis(char* buf, UINT32 buf_len, THREADID thread_idx);
7 | void INS_JumpAnalysis(ADDRINT ins_end, ADDRINT target_branch, INT32 taken, THREADID thread_idx);
8 | void INS_WriteAnalysis(ADDRINT at, ADDRINT size);
9 | void INS_UPXEndAnalysis(OPCODE opcode);
10 | void INS_WXorX(ADDRINT at, const char* disasm_ins);
--------------------------------------------------------------------------------
/icount/constants.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #define Kb 1024
4 | #define Mb (1024*Kb)
5 | #define Gb (1024*Mb)
6 |
7 | #define CACHE_LINE_SIZE 64
8 | #define MAIN_THREAD_FAVOR_FACTOR 4
9 |
10 | #define INS_DELIMITER '\n'
11 | #define MAX_FILENAME_LENGTH 128
12 |
13 | #define THREAD_BUFFER_SIZE 30*Mb
14 | #define TRACE_LIMIT 2047*Mb
15 | #define TRACE_NAME_LENGTH_LIMIT 128
16 | #define THREADS_MAX_NO 256
17 |
18 | #define TEXT_SEC_NAME ".text"
19 |
20 | #define INVALID_ENTRY_POINT 0
--------------------------------------------------------------------------------
/icount/dump.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #include "pin.H"
4 | #include "main.h"
5 | #include "report.h"
6 | #include "loggers.h"
7 |
8 | void dumpImg(IMG img) {
9 | char dump_file_name[MAX_FILENAME_LENGTH] = { 0 };
10 | sprintf(dump_file_name, "%s_img.dump", prog_name);
11 | FILE* dump_file = fopen(dump_file_name, "w+");
12 | size_t img_size = main_img_memory.second - main_img_memory.first;
13 | char* dump = (char*) malloc(img_size);
14 | PIN_SafeCopy(dump, (void*) main_img_memory.first, img_size);
15 | fwrite(dump, sizeof(char), img_size, dump_file);
16 | fclose(dump_file);
17 | }
18 |
19 | void dumpSections(IMG img) {
20 | for (SEC sec = IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec)) {
21 | INFO("[*] Name: %s, from: 0x%08x to: 0x%08x\n", SEC_Name(sec).c_str(), SEC_Address(sec), SEC_Address(sec) + SEC_Size(sec));
22 | FILE* f = fopen((SEC_Name(sec) + ".dump").c_str(), "w+");
23 | char* sec_dump = (char*) malloc(SEC_Size(sec));
24 | PIN_SafeCopy(sec_dump, (void*) SEC_Address(sec), SEC_Size(sec));
25 | INFO("[+] Dumped %d/%d\n", fwrite(sec_dump, sizeof(char), SEC_Size(sec), f), SEC_Size(sec));
26 | fclose(f);
27 |
28 | report_j["sections"][SEC_Name(sec)]["address"] = SEC_Address(sec);
29 | report_j["sections"][SEC_Name(sec)]["size"] = SEC_Size(sec);
30 | }
31 | }
32 |
33 | void dumpWrittenIntervals() {
34 | char dump_file_name[MAX_FILENAME_LENGTH] = { 0 };
35 | sprintf(dump_file_name, "%s_written_intervals.dump", prog_name);
36 | FILE* dump_file = fopen(dump_file_name, "w+");
37 | for each (pair interval in written_mem_intervals) {
38 | //INFO("[+] Dumping from 0x%08x to 0x%08x\n", interval.first, interval.second);
39 | char* dump = (char*) malloc(interval.second - interval.first);
40 | PIN_SafeCopy(dump, (void*) interval.first, interval.second - interval.first);
41 | fprintf(dump_file, "%s", dump);
42 | }
43 | fclose(dump_file);
44 | }
--------------------------------------------------------------------------------
/icount/dump.h:
--------------------------------------------------------------------------------
1 | #include "pin.H"
2 |
3 | void dumpImg(IMG img);
4 | void dumpSections(IMG img);
5 | void dumpWrittenIntervals();
--------------------------------------------------------------------------------
/icount/error_handlers.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #include "loggers.h"
3 | #include "pin.H"
4 |
5 | #define MALLOC_ERROR_HANDLER(buf, msg) {\
6 | if (buf == NULL) {\
7 | ERROR(msg);\
8 | PIN_ExitProcess(1);\
9 | }\
10 | }
11 |
12 | #define ERROR_HANDLER(cond, msg) {\
13 | if (cond) {\
14 | ERROR(msg);\
15 | PIN_ExitProcess(1);\
16 | }\
17 | }
--------------------------------------------------------------------------------
/icount/flusher.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include "pin.H"
4 | #include "loggers.h"
5 | #include "constants.h"
6 | #include "utils.h"
7 | #include "flusher.h"
8 | #include "main.h"
9 |
10 | namespace flusher {
11 | PIN_SEMAPHORE flusher_ready_sem;
12 | PIN_SEMAPHORE flusher_sem;
13 | THREADID requesting_thread_idx = -1;
14 | doub_buf_trace_t* dbt;
15 | FILE* f;
16 | bool isPoisoned;
17 |
18 | void flusherThread(void* arg) {
19 | INFO("[*]{Flusher} Started with OS_THREADID %d\n", PIN_GetTid());
20 | time_t tv, tx;
21 | while (1) {
22 | PIN_SemaphoreWait(&flusher_sem);
23 | START_STOPWATCH(tx);
24 | if (isPoisoned) return;
25 | INFO("[*]{Flusher} Received request from thread %d, flushing ...\n", requesting_thread_idx);
26 | dbt->isFlushing = true;
27 |
28 | START_STOPWATCH(tv);
29 | flushTraceToFile(f, dbt->flush_buf, dbt->flush_buf_len);
30 | total_flusher_flushing_time += GET_STOPWATCH_LAP(tv);
31 |
32 | free(dbt->flush_buf);
33 | dbt->isFlushing = false;
34 | dbt->isFlushBufEmpty = true;
35 | PIN_SemaphoreSet(&dbt->end_flush_sem);
36 | if (isPoisoned) return;
37 | PIN_SemaphoreClear(&flusher_sem);
38 | PIN_MutexUnlock(&flusher_req_mutex);
39 | total_flusher_time += GET_STOPWATCH_LAP(tx);
40 | INFO("[*]{Flusher} Completed request from thread %d, waiting for incoming requests ...\n", requesting_thread_idx);
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/icount/flusher.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 | #include "main.h"
3 |
4 | namespace flusher {
5 | void flusherThread(void* arg);
6 |
7 | extern THREADID requesting_thread_idx;
8 | extern doub_buf_trace_t* dbt;
9 | extern FILE* f;
10 | extern bool isPoisoned;
11 |
12 | extern PIN_SEMAPHORE flusher_sem;
13 | extern PIN_SEMAPHORE flusher_ready_sem;
14 | }
--------------------------------------------------------------------------------
/icount/json.h:
--------------------------------------------------------------------------------
1 | /* DCD: to get it running under Pin CRT */
2 | #define PIN_CRT
3 | #define JSON_USE_EXCEPTION 0
4 |
5 | /// Json-cpp amalgated header (http://jsoncpp.sourceforge.net/).
6 | /// It is intended to be used with #include "json/json.h"
7 |
8 | // //////////////////////////////////////////////////////////////////////
9 | // Beginning of content of file: LICENSE
10 | // //////////////////////////////////////////////////////////////////////
11 |
12 | /*
13 | The JsonCpp library's source code, including accompanying documentation,
14 | tests and demonstration applications, are licensed under the following
15 | conditions...
16 |
17 | The author (Baptiste Lepilleur) explicitly disclaims copyright in all
18 | jurisdictions which recognize such a disclaimer. In such jurisdictions,
19 | this software is released into the Public Domain.
20 |
21 | In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
22 | 2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
23 | released under the terms of the MIT License (see below).
24 |
25 | In jurisdictions which recognize Public Domain property, the user of this
26 | software may choose to accept it either as 1) Public Domain, 2) under the
27 | conditions of the MIT License (see below), or 3) under the terms of dual
28 | Public Domain/MIT License conditions described here, as they choose.
29 |
30 | The MIT License is about as close to Public Domain as a license can get, and is
31 | described in clear, concise terms at:
32 |
33 | http://en.wikipedia.org/wiki/MIT_License
34 |
35 | The full text of the MIT License follows:
36 |
37 | ========================================================================
38 | Copyright (c) 2007-2010 Baptiste Lepilleur
39 |
40 | Permission is hereby granted, free of charge, to any person
41 | obtaining a copy of this software and associated documentation
42 | files (the "Software"), to deal in the Software without
43 | restriction, including without limitation the rights to use, copy,
44 | modify, merge, publish, distribute, sublicense, and/or sell copies
45 | of the Software, and to permit persons to whom the Software is
46 | furnished to do so, subject to the following conditions:
47 |
48 | The above copyright notice and this permission notice shall be
49 | included in all copies or substantial portions of the Software.
50 |
51 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
52 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
53 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
54 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
55 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
56 | ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
57 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58 | SOFTWARE.
59 | ========================================================================
60 | (END LICENSE TEXT)
61 |
62 | The MIT license is compatible with both the GPL and commercial
63 | software, affording one all of the rights of Public Domain with the
64 | minor nuisance of being required to keep the above copyright notice
65 | and license text in the source code. Note also that by accepting the
66 | Public Domain "license" you can re-license your copy using whatever
67 | license you like.
68 |
69 | */
70 |
71 | // //////////////////////////////////////////////////////////////////////
72 | // End of content of file: LICENSE
73 | // //////////////////////////////////////////////////////////////////////
74 |
75 |
76 |
77 |
78 |
79 | #ifndef JSON_AMALGATED_H_INCLUDED
80 | # define JSON_AMALGATED_H_INCLUDED
81 | /// If defined, indicates that the source file is amalgated
82 | /// to prevent private header inclusion.
83 | #define JSON_IS_AMALGAMATION
84 |
85 | // //////////////////////////////////////////////////////////////////////
86 | // Beginning of content of file: include/json/version.h
87 | // //////////////////////////////////////////////////////////////////////
88 |
89 | // DO NOT EDIT. This file (and "version") is generated by CMake.
90 | // Run CMake configure step to update it.
91 | #ifndef JSON_VERSION_H_INCLUDED
92 | # define JSON_VERSION_H_INCLUDED
93 |
94 | # define JSONCPP_VERSION_STRING "1.7.2"
95 | # define JSONCPP_VERSION_MAJOR 1
96 | # define JSONCPP_VERSION_MINOR 7
97 | # define JSONCPP_VERSION_PATCH 2
98 | # define JSONCPP_VERSION_QUALIFIER
99 | # define JSONCPP_VERSION_HEXA ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | (JSONCPP_VERSION_PATCH << 8))
100 |
101 | #ifdef JSONCPP_USING_SECURE_MEMORY
102 | #undef JSONCPP_USING_SECURE_MEMORY
103 | #endif
104 | #define JSONCPP_USING_SECURE_MEMORY 0
105 | // If non-zero, the library zeroes any memory that it has allocated before
106 | // it frees its memory.
107 |
108 | #endif // JSON_VERSION_H_INCLUDED
109 |
110 | // //////////////////////////////////////////////////////////////////////
111 | // End of content of file: include/json/version.h
112 | // //////////////////////////////////////////////////////////////////////
113 |
114 |
115 |
116 |
117 |
118 |
119 | // //////////////////////////////////////////////////////////////////////
120 | // Beginning of content of file: include/json/config.h
121 | // //////////////////////////////////////////////////////////////////////
122 |
123 | // Copyright 2007-2010 Baptiste Lepilleur
124 | // Distributed under MIT license, or public domain if desired and
125 | // recognized in your jurisdiction.
126 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
127 |
128 | #ifndef JSON_CONFIG_H_INCLUDED
129 | #define JSON_CONFIG_H_INCLUDED
130 | #include
131 | #include //typdef String
132 |
133 | /// If defined, indicates that json library is embedded in CppTL library.
134 | //# define JSON_IN_CPPTL 1
135 |
136 | /// If defined, indicates that json may leverage CppTL library
137 | //# define JSON_USE_CPPTL 1
138 | /// If defined, indicates that cpptl vector based map should be used instead of
139 | /// std::map
140 | /// as Value container.
141 | //# define JSON_USE_CPPTL_SMALLMAP 1
142 |
143 | // If non-zero, the library uses exceptions to report bad input instead of C
144 | // assertion macros. The default is to use exceptions.
145 | #ifndef JSON_USE_EXCEPTION
146 | #define JSON_USE_EXCEPTION 1
147 | #endif
148 |
149 | /// If defined, indicates that the source file is amalgated
150 | /// to prevent private header inclusion.
151 | /// Remarks: it is automatically defined in the generated amalgated header.
152 | // #define JSON_IS_AMALGAMATION
153 |
154 | #ifdef JSON_IN_CPPTL
155 | #include
156 | #ifndef JSON_USE_CPPTL
157 | #define JSON_USE_CPPTL 1
158 | #endif
159 | #endif
160 |
161 | #ifdef JSON_IN_CPPTL
162 | #define JSON_API CPPTL_API
163 | #elif defined(JSON_DLL_BUILD)
164 | #if defined(_MSC_VER) || defined(__MINGW32__)
165 | #define JSON_API __declspec(dllexport)
166 | #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
167 | #endif // if defined(_MSC_VER)
168 | #elif defined(JSON_DLL)
169 | #if defined(_MSC_VER) || defined(__MINGW32__)
170 | #define JSON_API __declspec(dllimport)
171 | #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING
172 | #endif // if defined(_MSC_VER)
173 | #endif // ifdef JSON_IN_CPPTL
174 | #if !defined(JSON_API)
175 | #define JSON_API
176 | #endif
177 |
178 | // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for
179 | // integer
180 | // Storages, and 64 bits integer support is disabled.
181 | // #define JSON_NO_INT64 1
182 |
183 | #if defined(_MSC_VER) // MSVC
184 | # if _MSC_VER <= 1200 // MSVC 6
185 | // Microsoft Visual Studio 6 only support conversion from __int64 to double
186 | // (no conversion from unsigned __int64).
187 | # define JSON_USE_INT64_DOUBLE_CONVERSION 1
188 | // Disable warning 4786 for VS6 caused by STL (identifier was truncated to '255'
189 | // characters in the debug information)
190 | // All projects I've ever seen with VS6 were using this globally (not bothering
191 | // with pragma push/pop).
192 | # pragma warning(disable : 4786)
193 | # endif // MSVC 6
194 |
195 | # if _MSC_VER >= 1500 // MSVC 2008
196 | /// Indicates that the following function is deprecated.
197 | # define JSONCPP_DEPRECATED(message) __declspec(deprecated(message))
198 | # endif
199 |
200 | #endif // defined(_MSC_VER)
201 |
202 | // In c++11 the override keyword allows you to explicity define that a function
203 | // is intended to override the base-class version. This makes the code more
204 | // managable and fixes a set of common hard-to-find bugs.
205 | #ifdef PIN_CRT
206 | #define JSONCPP_OVERRIDE
207 | #else
208 | #if __cplusplus >= 201103L
209 | # define JSONCPP_OVERRIDE override
210 | #elif defined(_MSC_VER) && _MSC_VER > 1600
211 | # define JSONCPP_OVERRIDE override
212 | #else
213 | # define JSONCPP_OVERRIDE
214 | #endif
215 | #endif
216 |
217 | #ifndef JSON_HAS_RVALUE_REFERENCES
218 | #ifndef PIN_CRT
219 | #if defined(_MSC_VER) && _MSC_VER >= 1600 // MSVC >= 2010
220 | #define JSON_HAS_RVALUE_REFERENCES 1
221 | #endif
222 | #endif // MSVC >= 2010
223 |
224 | #ifdef __clang__
225 | #if __has_feature(cxx_rvalue_references)
226 | #define JSON_HAS_RVALUE_REFERENCES 1
227 | #endif // has_feature
228 |
229 | #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
230 | #if defined(__GXX_EXPERIMENTAL_CXX0X__) || (__cplusplus >= 201103L)
231 | #define JSON_HAS_RVALUE_REFERENCES 1
232 | #endif // GXX_EXPERIMENTAL
233 |
234 | #endif // __clang__ || __GNUC__
235 |
236 | #endif // not defined JSON_HAS_RVALUE_REFERENCES
237 |
238 | #ifndef JSON_HAS_RVALUE_REFERENCES
239 | #define JSON_HAS_RVALUE_REFERENCES 0
240 | #endif
241 |
242 | #ifdef __clang__
243 | #elif defined __GNUC__ // not clang (gcc comes later since clang emulates gcc)
244 | # if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5))
245 | # define JSONCPP_DEPRECATED(message) __attribute__ ((deprecated(message)))
246 | # elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1))
247 | # define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__))
248 | # endif // GNUC version
249 | #endif // __clang__ || __GNUC__
250 |
251 | #if !defined(JSONCPP_DEPRECATED)
252 | #define JSONCPP_DEPRECATED(message)
253 | #endif // if !defined(JSONCPP_DEPRECATED)
254 |
255 | #if __GNUC__ >= 6
256 | # define JSON_USE_INT64_DOUBLE_CONVERSION 1
257 | #endif
258 |
259 | #if !defined(JSON_IS_AMALGAMATION)
260 |
261 | # include "version.h"
262 |
263 | # if JSONCPP_USING_SECURE_MEMORY
264 | # include "allocator.h" //typedef Allocator
265 | # endif
266 |
267 | #endif // if !defined(JSON_IS_AMALGAMATION)
268 |
269 | namespace Json {
270 | typedef int Int;
271 | typedef unsigned int UInt;
272 | #if defined(JSON_NO_INT64)
273 | typedef int LargestInt;
274 | typedef unsigned int LargestUInt;
275 | #undef JSON_HAS_INT64
276 | #else // if defined(JSON_NO_INT64)
277 | // For Microsoft Visual use specific types as long long is not supported
278 | #if defined(_MSC_VER) // Microsoft Visual Studio
279 | typedef __int64 Int64;
280 | typedef unsigned __int64 UInt64;
281 | #else // if defined(_MSC_VER) // Other platforms, use long long
282 | typedef long long int Int64;
283 | typedef unsigned long long int UInt64;
284 | #endif // if defined(_MSC_VER)
285 | typedef Int64 LargestInt;
286 | typedef UInt64 LargestUInt;
287 | #define JSON_HAS_INT64
288 | #endif // if defined(JSON_NO_INT64)
289 | #if JSONCPP_USING_SECURE_MEMORY
290 | #define JSONCPP_STRING std::basic_string, Json::SecureAllocator >
291 | #define JSONCPP_OSTRINGSTREAM std::basic_ostringstream, Json::SecureAllocator >
292 | #define JSONCPP_OSTREAM std::basic_ostream>
293 | #define JSONCPP_ISTRINGSTREAM std::basic_istringstream, Json::SecureAllocator >
294 | #define JSONCPP_ISTREAM std::istream
295 | #else
296 | #define JSONCPP_STRING std::string
297 | #define JSONCPP_OSTRINGSTREAM std::ostringstream
298 | #define JSONCPP_OSTREAM std::ostream
299 | #define JSONCPP_ISTRINGSTREAM std::istringstream
300 | #define JSONCPP_ISTREAM std::istream
301 | #endif // if JSONCPP_USING_SECURE_MEMORY
302 | } // end namespace Json
303 |
304 | #endif // JSON_CONFIG_H_INCLUDED
305 |
306 | // //////////////////////////////////////////////////////////////////////
307 | // End of content of file: include/json/config.h
308 | // //////////////////////////////////////////////////////////////////////
309 |
310 |
311 |
312 |
313 |
314 |
315 | // //////////////////////////////////////////////////////////////////////
316 | // Beginning of content of file: include/json/forwards.h
317 | // //////////////////////////////////////////////////////////////////////
318 |
319 | // Copyright 2007-2010 Baptiste Lepilleur
320 | // Distributed under MIT license, or public domain if desired and
321 | // recognized in your jurisdiction.
322 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
323 |
324 | #ifndef JSON_FORWARDS_H_INCLUDED
325 | #define JSON_FORWARDS_H_INCLUDED
326 |
327 | #if !defined(JSON_IS_AMALGAMATION)
328 | #include "config.h"
329 | #endif // if !defined(JSON_IS_AMALGAMATION)
330 |
331 | namespace Json {
332 |
333 | // writer.h
334 | class FastWriter;
335 | class StyledWriter;
336 |
337 | // reader.h
338 | class Reader;
339 |
340 | // features.h
341 | class Features;
342 |
343 | // value.h
344 | typedef unsigned int ArrayIndex;
345 | class StaticString;
346 | class Path;
347 | class PathArgument;
348 | class Value;
349 | class ValueIteratorBase;
350 | class ValueIterator;
351 | class ValueConstIterator;
352 |
353 | } // namespace Json
354 |
355 | #endif // JSON_FORWARDS_H_INCLUDED
356 |
357 | // //////////////////////////////////////////////////////////////////////
358 | // End of content of file: include/json/forwards.h
359 | // //////////////////////////////////////////////////////////////////////
360 |
361 |
362 |
363 |
364 |
365 |
366 | // //////////////////////////////////////////////////////////////////////
367 | // Beginning of content of file: include/json/features.h
368 | // //////////////////////////////////////////////////////////////////////
369 |
370 | // Copyright 2007-2010 Baptiste Lepilleur
371 | // Distributed under MIT license, or public domain if desired and
372 | // recognized in your jurisdiction.
373 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
374 |
375 | #ifndef CPPTL_JSON_FEATURES_H_INCLUDED
376 | #define CPPTL_JSON_FEATURES_H_INCLUDED
377 |
378 | #if !defined(JSON_IS_AMALGAMATION)
379 | #include "forwards.h"
380 | #endif // if !defined(JSON_IS_AMALGAMATION)
381 |
382 | namespace Json {
383 |
384 | /** \brief Configuration passed to reader and writer.
385 | * This configuration object can be used to force the Reader or Writer
386 | * to behave in a standard conforming way.
387 | */
388 | class JSON_API Features {
389 | public:
390 | /** \brief A configuration that allows all features and assumes all strings
391 | * are UTF-8.
392 | * - C & C++ comments are allowed
393 | * - Root object can be any JSON value
394 | * - Assumes Value strings are encoded in UTF-8
395 | */
396 | static Features all();
397 |
398 | /** \brief A configuration that is strictly compatible with the JSON
399 | * specification.
400 | * - Comments are forbidden.
401 | * - Root object must be either an array or an object value.
402 | * - Assumes Value strings are encoded in UTF-8
403 | */
404 | static Features strictMode();
405 |
406 | /** \brief Initialize the configuration like JsonConfig::allFeatures;
407 | */
408 | Features();
409 |
410 | /// \c true if comments are allowed. Default: \c true.
411 | bool allowComments_;
412 |
413 | /// \c true if root must be either an array or an object value. Default: \c
414 | /// false.
415 | bool strictRoot_;
416 |
417 | /// \c true if dropped null placeholders are allowed. Default: \c false.
418 | bool allowDroppedNullPlaceholders_;
419 |
420 | /// \c true if numeric object key are allowed. Default: \c false.
421 | bool allowNumericKeys_;
422 | };
423 |
424 | } // namespace Json
425 |
426 | #endif // CPPTL_JSON_FEATURES_H_INCLUDED
427 |
428 | // //////////////////////////////////////////////////////////////////////
429 | // End of content of file: include/json/features.h
430 | // //////////////////////////////////////////////////////////////////////
431 |
432 |
433 |
434 |
435 |
436 |
437 | // //////////////////////////////////////////////////////////////////////
438 | // Beginning of content of file: include/json/value.h
439 | // //////////////////////////////////////////////////////////////////////
440 |
441 | // Copyright 2007-2010 Baptiste Lepilleur
442 | // Distributed under MIT license, or public domain if desired and
443 | // recognized in your jurisdiction.
444 | // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
445 |
446 | #ifndef CPPTL_JSON_H_INCLUDED
447 | #define CPPTL_JSON_H_INCLUDED
448 |
449 | #if !defined(JSON_IS_AMALGAMATION)
450 | #include "forwards.h"
451 | #endif // if !defined(JSON_IS_AMALGAMATION)
452 | #include
453 | #include
454 | #include
455 |
456 | #ifndef JSON_USE_CPPTL_SMALLMAP
457 | #include