This kind of exploitation is useful in use-after-free, double-free or memory corruption
vulnerabilities. In such attacks the program tries to access an object instance's methods or poroperties in heap
memory after the instance has been freed, this may lead to the code execution.

And in general we can seperate the heap spray exploits in two sections:

1. Heap Sprayer
2. Vulnerability Trigger

1. Heap Sprayer : A heap sprayer sprays the heap with the properly alligned code to be executed
upon triggering the vulnerability. In heap spray the memory is repeatedly allocated in the heap area
and then injection vector is placed in it untill whole heap gets filled up.

The ammount of spray depends upon the available memory for the program and the guessed position of the
block of memory in which the vulnerable instance of object gets placed in general.

In order to develop some efficient sprayers, we must know a little about the fundamentals of allocations.

Well variable "a" will be allocated on stack whereas b will be allocated on heap.

also consider following assignments:

var c = a + a;
var d = a.substring(0,a.length-3);

c and d Will also be allocated in heap area.

Also take into note that whan a heap allocation occurs, the largest unused block gets deallocated first and then
the smaller chunk is allocated there. This also gives control of the heap allocations and its alignment to the attacker.

Now we should know a little about the data placement in heap area.

Consider a string "AAAA", it will be placed in memory as unicode string in following form:

00 41 00 41 00 41 00 41 00 00

This kind of data handling can destroy the shellcode in memory. therefore, shellcode should be placed in memory
in unicode form occupying 00 bytes also with precious shellcode bytes.

For examples consider 90 90 90 90 bytes to be placed in memory as nop sled. Then this nop sled can be allocated as:

var nopsled = unescape("\u9090\u9090");

Sameway the shellcode can be placed in memory.

So now we have basic idea of code allocation. Now let us proceed to develop a sprayer:

The heap spray is done in two stages.

First a very large instance of injection vector is prepared & allocated on heap area
and then it is sprayed all over heap to fill up all available memory for heap allocations.

Note: After a perfect heap spray, no further heap allocations can be done.

Above code properly adjusts the nop sled 0x0d0d0d0d and shellcode.
Now this large heap chunk contained in variable "nopsled" needs to be sprayed throughout the
heap along with shellcode suffixed to it as:

In order to exploit such a vulnerability, we just need to spray the heap right before triggering the vulnerability.
after hit and trials and adjustments of "single chunk" size and spray size, we got an efficient exploit :