Debian Codegraph @

include/fcml_assembler.hpp

raw
1 /*
2 * FCML - Free Code Manipulation Library.
3 * Copyright (C) 2010-2020 Slawomir Wojtasiak
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
20 /** @file fcml_assembler.hpp
21 * C++ wrapper for FCML assembler.
22 *
23 * @copyright Copyright (C) 2010-2020 Slawomir Wojtasiak. All rights reserved.
24 * This project is released under the GNU Lesser General Public License.
25 */
26
27 #ifndef FCML_ASSEMBLER_HPP_
28 #define FCML_ASSEMBLER_HPP_
29
30 #include <vector>
31 #include <ostream>
32
33 #include "fcml_assembler.h"
34
35 #include "fcml_common.hpp"
36 #include "fcml_errors.hpp"
37 #include "fcml_dialect.hpp"
38
39 namespace fcml {
40
41 /**
42 * Assembling failed.
43 * @since 1.1.0
44 */
45 class AssemblingFailedException: public ErrorContainerAwareException {
46 public:
47 AssemblingFailedException(const fcml_cstring msg,
48 ErrorContainer errorContainer = ErrorContainer(),
49 fcml_ceh_error error = FCML_CEH_GEC_NO_ERROR) :
50 ErrorContainerAwareException(msg, errorContainer, error) {
51 }
52 };
53
54 /** Describes an assembled instruction.
55 * @since 1.1.0
56 */
57 class AssembledInstruction {
58 public:
59
60 /**
61 * Creates an assembled instruction basing on given code buffer and errors.
62 *
63 * @param buffer Pointer to the machine code buffer.
64 * @param len Number of machine code bytes.
65 * @param errorContainer Potential warnings related to the
66 * assembled instruction.
67 * @since 1.1.0
68 *
69 */
70 AssembledInstruction(const fcml_uint8_t *buffer, fcml_usize len,
71 const ErrorContainer &errorContainer) {
72 set(buffer, len, errorContainer);
73 }
74
75 /**
76 * Copy constructor.
77 * @since 1.1.0
78 */
79 AssembledInstruction(const AssembledInstruction &cpy) {
80 set(cpy._code, cpy._codeLength, cpy._warningContainer);
81 }
82
83 /**
84 * Copies one instruction into another.
85 *
86 * @param cpy The source instruction.
87 * @return A reference to the destination instruction.
88 * @since 1.1.0
89 */
90 AssembledInstruction& operator=(const AssembledInstruction &cpy) {
91 if (&cpy != this) {
92 if (this->_code) {
93 delete[] this->_code;
94 }
95 set(cpy._code, cpy._codeLength, cpy._warningContainer);
96 }
97 return *this;
98 }
99
100 /**
101 * @since 1.1.0
102 */
103 virtual ~AssembledInstruction() {
104 if (_code) {
105 delete[] _code;
106 _code = NULL;
107 }
108 }
109
110 public:
111
112 /**
113 * Gets pointer to machine code buffer.
114 *
115 * @return Pointer to machine code buffer.
116 * @since 1.1.0
117 */
118 const fcml_uint8_t* getCode() const {
119 return _code;
120 }
121
122 /**
123 * Gets number of bytes in the buffer.
124 *
125 * @return Number of bytes in the buffer.
126 * @since 1.1.0
127 */
128 fcml_usize getCodeLength() const {
129 return _codeLength;
130 }
131
132 /**
133 * Gets reference to the errors container.
134 *
135 * @return A reference to the errors container.
136 * @since 1.1.0
137 */
138 const ErrorContainer& getWarningContainer() const {
139 return _warningContainer;
140 }
141
142 private:
143
144 /**
145 * Fills the assembled instruction with new data.
146 *
147 * @param buffer The code buffer.
148 * @param len The code buffer lenght.
149 * @param warnings The warnings container.
150 * @since 1.1.0
151 */
152 void set(const fcml_uint8_t *buffer, fcml_usize len,
153 const ErrorContainer warnigns) {
154 _warningContainer = warnigns;
155 if (len > 0) {
156 _code = new fcml_uint8_t[len];
157 for (fcml_usize i = 0; i < len; i++) {
158 _code[i] = buffer[i];
159 }
160 } else {
161 _code = NULL;
162 }
163 _codeLength = len;
164 }
165
166 private:
167
168 /** Warnings related to this instruction. */
169 ErrorContainer _warningContainer;
170
171 /** Pointer to the instruction machine code. */
172 fcml_uint8_t *_code;
173
174 /** Number of machine code bytes in the array above. */
175 fcml_usize _codeLength;
176
177 };
178
179 class Assembler;
180
181 /** Assembler result. */
182 class AssemblerResult {
183 public:
184
185 /**
186 * @since 1.1.0
187 */
188 AssemblerResult() :
189 _chosenInstructionIndex(-1) {
190 }
191
192 public:
193
194 /**
195 * Gets instruction chosen by the assembler as the preferred one.
196 *
197 * @return Preferred instruction.
198 * @since 1.1.0
199 */
200 const AssembledInstruction* getChosenInstruction() const {
201 if (_chosenInstructionIndex == -1) {
202 return NULL;
203 }
204 return &(_assembledInstructions[_chosenInstructionIndex]);
205 }
206
207 /**
208 * Gets errors container.
209 *
210 * @return Errors container.
211 * @since 1.1.0
212 */
213 const ErrorContainer& getErrorContainer() const {
214 return _errorContainer;
215 }
216
217 /**
218 * Gets number of instructions alternatives available in the result.
219 *
220 * @return Number of available instructions.
221 * @since 1.1.0
222 */
223 fcml_usize getSize() const {
224 return static_cast<fcml_usize>(_assembledInstructions.size());
225 }
226
227 /**
228 * Gets pointer to the chosen instruction.
229 *
230 * @return Pointer to the chosen instruction.
231 * @since 1.1.0
232 */
233 operator const AssembledInstruction*() const {
234 if (_chosenInstructionIndex == -1) {
235 return NULL;
236 }
237 return &(_assembledInstructions[_chosenInstructionIndex]);
238 }
239
240 /**
241 * Gets an assembled instruction reference by its index.
242 *
243 * @return The assembled instruction for given index.
244 * @throw BadArgumentException Array index out of bound.
245 * @since 1.1.0
246 */
247 const AssembledInstruction& operator[](fcml_usize index) const {
248 if (index > _assembledInstructions.size()) {
249 throw BadArgumentException(FCML_TEXT("Array index out of bound."),
250 FCML_CEH_GEC_VALUE_OUT_OF_RANGE);
251 }
252 return _assembledInstructions[index];
253 }
254
255 /**
256 * Copies machine code of the chosen instruction to the output stream.
257 *
258 * @param[out] out Output stream.
259 * @param result Assembler result.
260 * @return Output stream from the parameter.
261 * @since 1.1.0
262 */
263 friend std::basic_ostream<fcml_uint8_t>& operator<<(
264 std::basic_ostream<fcml_uint8_t> &out,
265 const AssemblerResult &result) {
266 const AssembledInstruction *assembled = result.getChosenInstruction();
267 if (assembled) {
268 // If chosen instruction is not available, do not
269 // stream anything. It's not so common, because
270 // instructions choosers are obliged to chose something.
271 if (assembled->getCode() && assembled->getCodeLength() > 0) {
272 out.write(assembled->getCode(), assembled->getCodeLength());
273 }
274 }
275 return out;
276 }
277
278 /**
279 * Clears assembler result by removing all assembled instructions,
280 * errors and reseting the chosen instruction.
281 * @since 1.1.0
282 */
283 void clear() {
284 _errorContainer.clean();
285 _assembledInstructions.clear();
286 _chosenInstructionIndex = -1;
287 }
288
289 protected:
290
291 friend Assembler;
292
293 void setErrorContainer(const ErrorContainer &errorContainer) {
294 _errorContainer = errorContainer;
295 }
296
297 std::vector<AssembledInstruction>& getAssembledInstructions() {
298 return _assembledInstructions;
299 }
300
301 void setChoosenInstructionIndex(fcml_int index) {
302 _chosenInstructionIndex = index;
303 }
304
305 private:
306
307 /** Assembling errors. */
308 ErrorContainer _errorContainer;
309 /** All assembled instructions are going here. */
310 std::vector<AssembledInstruction> _assembledInstructions;
311 /** Index for the chosen instruction. */
312 fcml_int _chosenInstructionIndex;
313
314 };
315
316 /** Assembler configuration.
317 * For more information about the flags, see fcml_st_assembler_conf
318 * structure documentation.
319 * @since 1.1.0
320 */
321 class AssemblerConf {
322 public:
323
324 /**
325 * @since 1.1.0
326 */
327 AssemblerConf() :
328 _throwExceptionOnError(true),
329 _incrementIp(true),
330 _enableErrorMessages(true),
331 _chooseSibEncoding(false),
332 _chooseAbsEncoding(false),
333 _forceRexPrefix(false),
334 _forceThreeByteVEX(false),
335 _noBranchPrediction(false),
336 _optimizer(NULL),
337 _optimizerFlags(0),
338 _chooser(NULL) {
339 }
340
341 public:
342
343 /**
344 * @since 1.1.0
345 */
346 bool isChooseAbsEncoding() const {
347 return _chooseAbsEncoding;
348 }
349
350 /**
351 * @since 1.1.0
352 */
353 void setChooseAbsEncoding(bool chooseAbsEncoding) {
354 _chooseAbsEncoding = chooseAbsEncoding;
355 }
356
357 /**
358 * @since 1.1.0
359 */
360 fcml_fnp_asm_instruction_chooser getChooser() const {
361 return _chooser;
362 }
363
364 /**
365 * @since 1.1.0
366 */
367 void setChooser(fcml_fnp_asm_instruction_chooser chooser) {
368 _chooser = chooser;
369 }
370
371 /**
372 * @since 1.1.0
373 */
374 bool isChooseSibEncoding() const {
375 return _chooseSibEncoding;
376 }
377
378 /**
379 * @since 1.1.0
380 */
381 void setChooseSibEncoding(bool chooseSibEncoding) {
382 _chooseSibEncoding = chooseSibEncoding;
383 }
384
385 /**
386 * @since 1.1.0
387 */
388 bool isEnableErrorMessages() const {
389 return _enableErrorMessages;
390 }
391
392 /**
393 * @since 1.1.0
394 */
395 void setEnableErrorMessages(bool enableErrorMessages) {
396 _enableErrorMessages = enableErrorMessages;
397 }
398
399 /**
400 * @since 1.1.0
401 */
402 bool isForceRexPrefix() const {
403 return _forceRexPrefix;
404 }
405
406 /**
407 * @since 1.1.0
408 */
409 void setForceRexPrefix(bool forceRexPrefix) {
410 _forceRexPrefix = forceRexPrefix;
411 }
412
413 /**
414 * @since 1.1.0
415 */
416 bool isForceThreeByteVex() const {
417 return _forceThreeByteVEX;
418 }
419
420 /**
421 * @since 1.1.0
422 */
423 void setForceThreeByteVex(bool forceThreeByteVex) {
424 _forceThreeByteVEX = forceThreeByteVex;
425 }
426
427 /**
428 * @since 1.1.0
429 */
430 bool isIncrementIp() const {
431 return _incrementIp;
432 }
433
434 /**
435 * @since 1.1.0
436 */
437 void setIncrementIp(bool incrementIp) {
438 _incrementIp = incrementIp;
439 }
440
441 /**
442 * @since 1.1.0
443 */
444 fcml_fnp_asm_optimizer getOptimizer() const {
445 return _optimizer;
446 }
447
448 /**
449 * @since 1.1.0
450 */
451 void setOptimizer(fcml_fnp_asm_optimizer optimizer) {
452 _optimizer = optimizer;
453 }
454
455 /**
456 * @since 1.1.0
457 */
458 fcml_uint16_t getOptimizerFlags() const {
459 return _optimizerFlags;
460 }
461
462 /**
463 * @since 1.1.0
464 */
465 void setOptimizerFlags(fcml_uint16_t optimizerFlags) {
466 _optimizerFlags = optimizerFlags;
467 }
468
469 /**
470 * Returns true if exception should be thrown when assembling fails.
471 *
472 * @return True if exception is the preferred way of error handling
473 * in case of failure.
474 * @since 1.1.0
475 */
476 bool isThrowExceptionOnError() const {
477 return _throwExceptionOnError;
478 }
479
480 /**
481 * Sets the way how the error handling is done.
482 *
483 * @param throwExceptionOnError True if exception should be thrown
484 * in case of failure.
485 * @since 1.1.0
486 */
487 void setThrowExceptionOnError(bool throwExceptionOnError) {
488 _throwExceptionOnError = throwExceptionOnError;
489 }
490
491 private:
492 bool _throwExceptionOnError;
493 bool _incrementIp;
494 bool _enableErrorMessages;
495 bool _chooseSibEncoding;
496 bool _chooseAbsEncoding;
497 bool _forceRexPrefix;
498 bool _forceThreeByteVEX;
499 bool _noBranchPrediction;
500 fcml_fnp_asm_optimizer _optimizer;
501 fcml_uint16_t _optimizerFlags;
502 fcml_fnp_asm_instruction_chooser _chooser;
503 };
504
505 /** Assembler context.
506 *
507 * It is a counterpart to the fcml_st_assembler_context structure.
508 * @since 1.1.0
509 */
510 class AssemblerContext {
511
512 public:
513
514 /**
515 * @since 1.1.0
516 */
517 AssemblerContext() {
518 }
519
520 /**
521 * Creates an entry point instance for given operating mode
522 * and optional instruction pointer.
523 *
524 * @param operatingMode The processor operating mode.
525 * @param ip The instruction pointer.
526 * @since 1.1.0
527 */
528 AssemblerContext(EntryPoint::OperatingMode operatingMode, fcml_ip ip = 0) :
529 _entryPoint(operatingMode, ip) {
530 }
531
532 public:
533
534 /**
535 * Gets constant assembler configuration associated with the context.
536 *
537 * @return Assembler configuration.
538 * @since 1.1.0
539 */
540 const AssemblerConf& getConfig() const {
541 return _config;
542 }
543
544 /**
545 * Gets assembler configuration associated with the context.
546 *
547 * @return Assembler configuration.
548 * @since 1.1.0
549 */
550 AssemblerConf& getConfig() {
551 return _config;
552 }
553
554 /**
555 * Copies given configuration to the instance associated with the context.
556 * Deep copy is performed, so passed object not need to be maintained as
557 * long as the context is used.
558 *
559 * @param config Configuration that is copied to the context.
560 * @since 1.1.0
561 */
562 void setConfig(const AssemblerConf &config) {
563 _config = config;
564 }
565
566 /**
567 * Gets reference to the constant entry point instance
568 * associated with the context.
569 *
570 * @return Reference to the constant entry point.
571 * @since 1.1.0
572 */
573 const EntryPoint& getEntryPoint() const {
574 return _entryPoint;
575 }
576
577 /**
578 * Gets reference to the entry point instance associated with the context.
579 *
580 * @return Reference to the entry point.
581 * @since 1.1.0
582 */
583 EntryPoint& getEntryPoint() {
584 return _entryPoint;
585 }
586 /**
587 * Copies given entry point to the instance associated with the context.
588 * Deep copy is performed, so passed object not need to be maintained as
589 * long as the context is used.
590 *
591 * @param entryPoint The entry point.
592 * @since 1.1.0
593 */
594 void setEntryPoint(const EntryPoint &entryPoint) {
595 _entryPoint = entryPoint;
596 }
597
598 /**
599 * Sets instruction pointer directly into the entry point.
600 *
601 * @param ip The new IP.
602 * @since 1.1.0
603 */
604 void setIP(fcml_ip ip) {
605 _entryPoint.setIP(ip);
606 }
607
608 /**
609 * Increments entry point by given number of bytes.
610 *
611 * @param ip Number of bytes the instruction pointer
612 * has to be incremented by.
613 * @since 1.1.0
614 */
615 void incrementIP(fcml_ip ip) {
616 _entryPoint.incrementIP(ip);
617 }
618
619 /**
620 * Sets processor operating mode directly into the entry point.
621 *
622 * @param operatingMode Processor operating mode to be set.
623 * @since 1.1.0
624 */
625 void setOperatingMode(EntryPoint::OperatingMode operatingMode) {
626 _entryPoint.setOpMode(operatingMode);
627 }
628
629 /**
630 * Sets a new address size attribute for the entry point.
631 *
632 * @param addressSizeAttribute The address size attribute.
633 * @since 1.1.0
634 */
635 void setAddressSizeAttribute(fcml_usize addressSizeAttribute) {
636 _entryPoint.setAddressSizeAttribute(addressSizeAttribute);
637 }
638
639 /**
640 * Sets a new operand size attribute for the entry point.
641 *
642 * @param operandSizeAttribute The operand size attribute.
643 * @since 1.1.0
644 */
645 void setOperandSizeAttribute(fcml_usize operandSizeAttribute) {
646 _entryPoint.setOperandSizeAttribute(operandSizeAttribute);
647 }
648
649 private:
650
651 /** Entry point associated with the context. */
652 EntryPoint _entryPoint;
653 /** Assembler configuration associated with the context. */
654 AssemblerConf _config;
655
656 };
657
658 /** Converts objects to their structures counterparts.
659 * @since 1.1.0
660 * @remarks Internal API, not intended to be used outside.
661 */
662 class AssemblerTypeConverter {
663 public:
664
665 static void convert(const fcml_st_assembler_context &src,
666 AssemblerContext &dest) {
667 // Converts assembler configuration and entry point.
668 // Both of them have dedicated conversion methods.
669 convert(src.configuration, dest.getConfig());
670 TypeConverter::convert(src.entry_point, dest.getEntryPoint());
671 }
672
673 static void convert(const AssemblerContext &src,
674 fcml_st_assembler_context &dest) {
675 // Converts assembler configuration and entry point. Both of them
676 // have dedicated conversion methods.
677 convert(src.getConfig(), dest.configuration);
678 TypeConverter::convert(src.getEntryPoint(), dest.entry_point);
679 }
680
681 static void convert(const fcml_st_assembler_conf &src,
682 AssemblerConf &dest) {
683 dest.setChooseAbsEncoding(FCML_TO_CPP_BOOL(src.choose_abs_encoding));
684 dest.setChooseSibEncoding(FCML_TO_CPP_BOOL(src.choose_sib_encoding));
685 dest.setChooser(src.chooser);
686 dest.setEnableErrorMessages(
687 FCML_TO_CPP_BOOL(src.enable_error_messages));
688 dest.setForceRexPrefix(FCML_TO_CPP_BOOL(src.force_rex_prefix));
689 dest.setForceThreeByteVex(FCML_TO_CPP_BOOL(src.force_three_byte_VEX));
690 dest.setIncrementIp(FCML_TO_CPP_BOOL(src.increment_ip));
691 dest.setOptimizer(src.optimizer);
692 dest.setOptimizerFlags(src.optimizer_flags);
693 }
694
695 static void convert(const AssemblerConf &src,
696 fcml_st_assembler_conf &dest) {
697 dest.choose_abs_encoding = src.isChooseAbsEncoding();
698 dest.choose_sib_encoding = src.isChooseSibEncoding();
699 dest.chooser = src.getChooser();
700 dest.enable_error_messages = src.isEnableErrorMessages();
701 dest.force_rex_prefix = src.isForceRexPrefix();
702 dest.force_three_byte_VEX = src.isForceThreeByteVex();
703 dest.increment_ip = src.isIncrementIp();
704 dest.optimizer = src.getOptimizer();
705 dest.optimizer_flags = src.getOptimizerFlags();
706 }
707
708 };
709
710 /**
711 * An assembler wrapper.
712 * As you can see the assembler instance is managed internally
713 * and is not exposed outside.
714 * @since 1.1.0
715 * @remarks This class is thread-safe.
716 */
717 class Assembler: public NonCopyable, protected DialectAware {
718 public:
719
720 /**
721 * Creates an assembler instance for given dialect.
722 *
723 * @param dialect The dialect for the assembler instance.
724 * @throw InitException Cannot initialize the assembler.
725 * @since 1.1.0
726 */
727 Assembler(Dialect &dialect) :
728 _dialect(dialect) {
729 fcml_ceh_error error = ::fcml_fn_assembler_init(extractDialect(dialect),
730 &_assembler);
731 if (error) {
732 throw InitException(FCML_TEXT("Cannot initialize the assembler."),
733 error);
734 }
735 }
736
737 /**
738 * @since 1.1.0
739 */
740 virtual ~Assembler() {
741 if (_assembler) {
742 ::fcml_fn_assembler_free(_assembler);
743 _assembler = NULL;
744 }
745 }
746
747 public:
748
749 /**
750 * Assembles given generic instruction model.
751 *
752 * @param ctx The assembler context.
753 * @param instruction The generic instruction model to be assembled.
754 * @param[out] result Assembler result.
755 * @throw AssemblingFailedException Thrown if assembling fails
756 * and AssemblerConf.isThrowExceptionOnError returns true.
757 * @return Error code.
758 * @since 1.1.0
759 */
760 fcml_ceh_error assemble(AssemblerContext &ctx,
761 const Instruction &instruction, AssemblerResult &result) {
762
763 // Prepare assembler context.
764 fcml_st_assembler_context context;
765 AssemblerTypeConverter::convert(ctx, context);
766
767 context.assembler = _assembler;
768
769 // Prepare instruction.
770 fcml_st_instruction inst;
771 TypeConverter::convert(instruction, inst);
772
773 // Prepare assembler result.
774 fcml_st_assembler_result res;
775 ::fcml_fn_assembler_result_prepare(&res);
776
777 fcml_ceh_error error = FCML_CEH_GEC_NO_ERROR;
778
779 try {
780
781 result.clear();
782
783 error = ::fcml_fn_assemble(&context, &inst, &res);
784
785 // Free instruction mnemonic.
786 TypeConverter::free(inst);
787
788 // Failed or not, convert assembler errors.
789 ErrorContainer errorContainer;
790 ErrorTypeConverter::convert(res.errors, errorContainer);
791
792 // Prepares assembler result.
793 result.setErrorContainer(errorContainer);
794
795 if (error && ctx.getConfig().isThrowExceptionOnError()) {
796 ::fcml_fn_assembler_result_free(&res);
797 throw AssemblingFailedException(FCML_TEXT("Assembling failed."),
798 errorContainer, error);
799 }
800
801 if (!error) {
802
803 std::vector<AssembledInstruction> &assembledInstructions =
804 result.getAssembledInstructions();
805
806 assembledInstructions.clear();
807
808 if (res.number_of_instructions > 0) {
809 ErrorContainer instructionWarnings;
810 fcml_int i = 0;
811 fcml_st_assembled_instruction *next_instruction =
812 res.instructions;
813 while (next_instruction) {
814 fcml_st_ceh_error_container &instruction_warnings =
815 next_instruction->warnings;
816 ErrorTypeConverter::convert(instruction_warnings,
817 instructionWarnings);
818 AssembledInstruction assembledInstruction(
819 next_instruction->code,
820 next_instruction->code_length,
821 instructionWarnings);
822 assembledInstructions.push_back(assembledInstruction);
823 if (next_instruction == res.chosen_instruction) {
824 result.setChoosenInstructionIndex(i);
825 }
826 next_instruction = next_instruction->next;
827 i++;
828 }
829 }
830
831 // Convert it back to the context because it might have been
832 // modified during assembling process (IP incrementing etc).
833 TypeConverter::convert(context.entry_point,
834 ctx.getEntryPoint());
835
836 }
837
838 ::fcml_fn_assembler_result_free(&res);
839
840 } catch (std::exception &exc) {
841 // If anything failed, free assembler results.
842 TypeConverter::free(inst);
843 ::fcml_fn_assembler_result_free(&res);
844 throw exc;
845 }
846
847 return error;
848 }
849
850 /**
851 * Gets dialect associated with the assembler.
852 * @return The dialect instance associated with the assembler.
853 * @since 1.1.0
854 */
855 Dialect& getDialect() const {
856 return _dialect;
857 }
858
859 private:
860
861 // A dialect used by the assembler.
862 Dialect &_dialect;
863
864 // An initialized assembler instance.
865 fcml_st_assembler *_assembler;
866
867 };
868
869 /** Iterates over machine code bytes from assembled instructions.
870 * @since 1.1.0
871 */
872 class CodeIterator: public Iterator<fcml_uint8_t> {
873 public:
874
875 /**
876 * Creates a code iterator instance.
877 * @param assembledInstructions Assembled instructions.
878 * @since 1.1.0
879 */
880 CodeIterator(std::vector<AssembledInstruction> &assembledInstructions) :
881 _buffer(NULL), _len(0), _pos(0), _iterator(
882 assembledInstructions.begin()), _assembledInstructions(
883 assembledInstructions) {
884 }
885
886 /**
887 * @since 1.1.0
888 */
889 virtual ~CodeIterator() {
890 }
891
892 /**
893 * Gets true if there is an another element in the iterator.
894 *
895 * @return True if there is another byte in the iterator.
896 * @since 1.1.0
897 */
898 bool hasNext() {
899 if (_buffer && _pos >= _len) {
900 _buffer = NULL;
901 }
902 if (!_buffer) {
903 if (_iterator == _assembledInstructions.end()) {
904 return false;
905 }
906 AssembledInstruction &current = *_iterator++;
907 _buffer = current.getCode();
908 _len = current.getCodeLength();
909 _pos = 0;
910 }
911 return true;
912 }
913
914 /**
915 * Gets the next element from the iterator.
916 *
917 * @return Next machine code byte.
918 * @throw IllegalStateException If iterator is empty.
919 * @since 1.1.0
920 */
921 fcml_uint8_t next() {
922 if ((!_buffer || _pos >= _len) && !hasNext()) {
923 throw IllegalStateException(
924 FCML_TEXT("No more elements in the iterator."));
925 }
926 return _buffer[_pos++];
927 }
928
929 private:
930
931 /** Code of the current instruction iterator points to. */
932 const fcml_uint8_t *_buffer;
933 /** Code length in bytes. */
934 fcml_usize _len;
935 /** Position in the code buffer */
936 fcml_usize _pos;
937 /** Assembled instructions iterator. */
938 std::vector<AssembledInstruction>::iterator _iterator;
939 /** Vector with assembled instructions. */
940 std::vector<AssembledInstruction> &_assembledInstructions;
941
942 };
943
944 }
945
946 #endif //FCML_ASSEMBLER_HPP_