123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="container" ng-app="cpuJS">
  <div class="col-full">
    <h1>System Programming</h1>
    <p><strong>the {C}SS way!</strong></p>
  </div>
  <div class="col-4 machine" ng-controller="Machine">
    <h2>Machine Layout</h2>
    <fieldset>
        <legend>Memory range</legend>
        <div>
          <label class="iconicstroke-layers">&nbsp;Base (hex):</label>
          <input type="text" maxlength="10" ng-model="baseAddress" />
        </div>
        <div>  
          <label class="iconicstroke-bars">&nbsp;Size (bytes):</label>
          <input type="text" maxlength="10" ng-model="memorySize" />
        </div>
    </fieldset>
    <div class="stack col-2" ng-controller="StackUI">
      <h3>Memory Layout</h3>
      <div class="label">
        <span ng-bind="baseAddress | hex"></span>
        <span ng-bind="baseAddress + 31 | hex" class="pull-right"></span>
      </div>
      <div class="addresses">
        <span class="addr-cell" ng-repeat="address in addresses" ng-class="{assigned:address.value>0}" ng-click="probeCell(address)"></span>
      </div>
      <div class="label">
        <span ng-bind="baseAddress + memorySize - 32 | hex"></span>
        <span ng-bind="baseAddress + memorySize - 1 | hex" class="pull-right"></span>
      </div>      
    </div>
    <div class="registers col-2" ng-controller="RegistersUI">
      <h3>Registers</h3>
      <div>
        <div class="register" ng-repeat="(name,value) in registers">
          <span class="addr-cell">
            {{name}}
          </span>&nbsp;{{value | hex}}
        </div>
      </div>
    </div>
  </div>
  <div class="col-4 editor">    
    <h2>Code in C++</h2>
    <div class="source-code" ng-controller="CodeEditor">
      <ul>
        <li><span class="keyword">int</span> main(<span class="keyword">int</span> argc, <span class="keyword">char</span>*argv[]) { </li>
          <li>    <span class="keyword">int</span> a = 5;</li>
          <li>    *<span class="keyword">int</span> ptr_a = &a;</li>
        <li>    printf("a = %d",a);</li>
        <li>};</li>
      </ul>
    </div>
    <h2>Dissembly in AT&T ASM</h2>
    <div class="source-code asm" ng-controller="Dissembler">
      <div class="toolbar">
        <button ng-click="run()">
          <i class="iconicstroke-play"></i>
          RUN
        </button>
        <button ng-click="step()">
          <i class="iconicstroke-last"></i>
          STEP
        </button>
      </div>
      <ul>
        <li ng-repeat="line in lines" ng-class="{active:$index==current}">
          <span class="action" ng-class="{breakpoint:$index==breakpoint}" ng-click="toggleBreakpoint($index)"></span>
          <span ng-bind-html="line"></span>
        </li>
      </ul>
    </div>
  </div>
</div>
            
          
!
            
              @import "compass/css3";

@import "compass/css3";

@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);
@import url(https://fonts.googleapis.com/css?family=Ubuntu);
@import url(http://weloveiconfonts.com/api/?family=iconicstroke);
/* iconicstroke */
[class*="iconicstroke-"]:before {
  font-family: 'IconicStroke', sans-serif;
  @include box-sizing(border-box);
}

$width: 960px;
$gap: 10px;
$col-width: $width/8 - $gap;

$addresses-width: $width/6;
$addr-gap: $addresses-width/32/40;
$addr-width: $addresses-width/32 - 2*$addr-gap;
$addr-height: $addresses-width/32;

$regs-width: $col-width;
$register-width: 2 * $col-width;
// Colors: 
$color-keyword: blue;
$color-addr: #999;
$color-addr-assigned: lightgreen;
$color-button: #eef;
$color-button-bg: darken($color-button, 10%);
$color-button-hi: lighten($color-button, 5%);
$color-button-lo: darken($color-button, 25%);
// GENERAL THEME
html {
  font-family: "Open Sans", sans-serif;
}      
h1, h2, h3, h4, h5, h6 {
  font-family: "Ubuntu", sans-serif;
}
strong {
  font-style: italic;
}
.addr-cell {
  font-family: monospace;
  color: white;
}
button {
  border: 1px solid $color-button-lo;
  background-color: $color-button-bg;
  &[class*="fontawesome-"] {
    padding-left: 32px;
  }
}
fieldset {
  div {
    width: 100%;
    label {
      width: $col-width;
      display: inline-block;
    }
    input {
      width: 2 * $col-width;
      border: 1px solid $color-button-lo;       
    }
  }
}

span.action {
  display: inline-block;    
  width: 16px;
  height: 16px;
  vertical-align: middle;

  cursor: pointer;

  font-family: 'IconicStroke', sans-serif;
  &:before {
    display: inline-block;
    height: inherit;
    vertical-align: middle;
  }
  &:hover:before {
    content:'\e048';
  }
  &.breakpoint:before {
    content:'\e048';
    color: red;
  }
}
// LAYOUT
.container {
  width: $width;
  height: 640px;
  margin: auto;
}
.col-full {
 width: $width; 
}
.pull-right {
  float: right;
}
@for $i from 1 through 8 {
  .col-#{$i} {
    width: $col-width * $i;
    height: inherit;
    display: block;
    float: left;
  }
}

.stack {
  .label {
    font-family: monospace;
  }
  .addresses, .label {
    width: $addresses-width;
  }
  .addr-cell {
    display: block;
    width: $addr-width;
    height: $addr-height;
    margin: 0 $addr-gap $addr-gap + 4;
    background-color: $color-addr;
    
    float: left;
    @include box-sizing(border-box);
    &.assigned {
      background-color: $color-addr-assigned;
    }
  }
}

.registers {
   .register {
     width: $register-width;
     float: left; 
     
     .addr-cell {
       display: inline-block;
       width: $addr-width * 8;
       height: $addr-width * 4;
       margin-bottom: $addr-gap;
       @include box-sizing(border-box);
     
       vertical-align: middle;
       text-align: center;
     
       line-height: $addr-width * 4;
     
       color: white;
       background: $color-addr;
     }
   }
}

.source-code {
  ul {
    padding-left: 0;
    counter-reset: line-number;
  }
  ul li {
    display: block;
    font-family: monospace;
    white-space: pre;
    
    &.active {
      background-color: darken(#dfdfdf,20%);
    }
    &:hover {
      background-color: #dfdfdf;
    }
    
    &:before {
      content: counter(line-number, decimal-leading-zero) ".";
      counter-increment: line-number;
    }
  }
  
  .keyword {
    color: $color-keyword;
  }
  
  &.asm {
    ul li {
      white-space: nowrap;
    }
    .addr, .stack-frame, .instruction, .params {
      display: inline-block;
      padding-right: $gap;
    }
    .stack-frame {
      width: $col-width * 1.7;
    }
  }
}
            
          
!
            
              module = angular.module 'cpuJS', []
module.config ($sceProvider)->
  $sceProvider.enabled false

module.filter 'hex',()->
  (input)->
    try
      if (input + '').substr(2) == "0x" then input else "0x#{(new Number(input).toString 16).toUpperCase()}" 
    catch err
      console.error err.message
      return 'Invalid hex'
  
module.controller "MainCtrl", ($scope) ->
  $scope
  return

module.controller "CodeEditor", ($scope) ->
  $scope
  return

module.controller "Dissembler", ["$rootScope", "$scope", "$timeout", ($rootScope, $scope, $timeout) ->
  grep = (str)->
    re = /(\b[\w]+?\b)|(\<.+?\>)|([%$-].+?$)/g
    l = while (m=re.exec str) != null
      m[0].replace '<','&lt;'.replace '>','&gt;'
  
  asm = [
    "0x4004f4 <main(int, char**)>    push   %rbp",
    "0x4004f5 <main(int, char**)+1>  mov    %rsp,%rbp",
    "0x4004f8 <main(int, char**)+4>  sub    $0x20,%rsp",
    "0x4004fc <main(int, char**)+8>  mov    %edi,-0x14(%rbp)",
    "0x4004ff <main(int, char**)+11> mov    %rsi,-0x20(%rbp)",
    "0x400503 <main(int, char**)+15> movl   $0x5,-0x4(%rbp)",
    "0x40050a <main(int, char**)+22> lea    -0x4(%rbp),%rax",
    "0x40050e <main(int, char**)+26> mov    %rax,-0x10(%rbp)",
    "0x400512 <main(int, char**)+30> mov    -0x4(%rbp),%eax",
    "0x400515 <main(int, char**)+33> mov    %eax,%esi",
    "0x400517 <main(int, char**)+35> mov    $0x1c,%edi",
    "0x40051c <main(int, char**)+40> mov    $0x0,%eax",
    "0x400521 <main(int, char**)+45> callq  0xf0 <printf@plt>",
    "0x400526 <main(int, char**)+50> mov    $0x0,%eax",
    "0x40052b <main(int, char**)+55> leaveq",
    "0x40052c <main(int, char**)+56> retq"]

  $scope.lines = (((switch index 
    when 0 then '<span class="addr">' + token + '</span>' 
    when 1 then '<span class="stack-frame">' + token + '</span>' 
    when 2 then '<span class="instruction">' + token + '</span>' 
    else '<span class="params">' + token + '</span>') for token, index in grep line).join '' for line in asm)
  
  $scope.status = 'RESET' # RUNNING, BREAK
  $scope.current = null
  $scope.breakpoint = null
  timr = null

  $scope.run = ()->
    if $scope.current is null
      $scope.current = 0
      $scope.status = 'RUNNING'

    recursFn = ()->
      timr = $timeout ()->
        if $scope.current < asm.length
          if $scope.status == 'RUNNING'
            if $scope.breakpoint == $scope.current
              $scope.status = 'BREAK'
              return
          else if $scope.status == 'BREAK'
            $scope.status = 'RUNNING'

          exec asm[$scope.current]          
          $scope.current++
          recursFn()
        else
          $scope.current = null
          return
      , 1000
      return
    recursFn()
  
  $scope.stop = ()->
    if $scope.current isnt null
      $timeout.cancel(timr)
      $scope.current = null
      return

  $scope.step = ()->
    if $scope.current is null
      $scope.current = 0
    else
      $scope.current++
    exec asm[$scope.current]

  $scope.toggleBreakpoint = (line)->
    if $scope.breakpoint == line
      $scope.breakpoint = null
    else
      $scope.breakpoint = line

  exec = (line)->
    [ins, params] = (grep line)[2..]
    switch ins
      when 'push' then $rootScope.$broadcast 'stack.push', params
      when 'pop' then $rootScope.$broadcast 'stack.pop', params
      when 'mov'
        [operand1, operand2] = params.split ','
        $rootScope.$broadcast 'mem.mov', operand1, operand2
      when 'movl'
        [operand1, operand2] = params.split ','
        $rootScope.$broadcast 'mem.mov', operand1, operand2
      when 'sub'
        [operand1, operand2] = params.split ','
        $rootScope.$broadcast 'mem.sub', operand1, operand2
      when 'lea'
        [operand1, operand2] = params.split ','
        $rootScope.$broadcast 'sys.lea', operand1, operand2
      when 'callq' then $rootScope.$broadcast 'sys.callq', params
      when 'leaveq' then $rootScope.$broadcast 'sys.leaveq'
      when  'retq' then $rootScope.$broadcast 'sys.retq'
      else $rootScope.$broadcast 'error', 'Invalid instruction'

  return
]
module.controller "Machine", ($scope) ->
  generateAddress = ()->
    dict = {}
    dict[hex(i)] = {addr:hex(i),value:0} for i in[$scope.baseAddress..$scope.baseAddress+$scope.memorySize-1]
    dict
  
  $scope.baseAddress = 0
  $scope.memorySize = 512
  $scope.addresses = generateAddress()
  
  $scope.$watch "memorySize", ()->
    $scope.addresses = generateAddress()
  
  $scope.registers =
    rax: 0
    rbx: 0
    rcx: 0
    rdx: 0
    rsi: 15
    rdi: 1
    edi: 1
    rsp: 480
    rbp: 1
    rip: 0

  $scope.$on 'mem.mov', (e, expr1, expr2) ->
    operand1 = resolve(expr1, $scope.registers, $scope.addresses)
    operand2 = resolve(expr2, $scope.registers, $scope.addresses)
    if operand1.type is 'REGISTER'
      if operand2.type is 'REGISTER' # Mov the content of operand1 to operand2
        $scope.registers[operand2.value] = $scope.registers[operand1.value]
      else if operand2.type is 'ADDR' # Must deference the value of this operand
        $scope.addresses[hex(operand2.value)].value = $scope.registers[operand1.value]
    else if operand1.type is 'ADDR'
      if operand2.type is 'REGISTER' # Mov the content of operand1 to operand2
        $scope.registers[operand2.value] = $scope.addresses[hex(operand1.value)].value
      else if operand2.type is 'ADDR' # Must deference the value of this operand
        $scope.addresses[hex(operand2.value)].value = $scope.addresses[hex(operand1.value)].value
    else if operand1.type is 'VALUE'
      if operand2.type is 'REGISTER' # Mov the content of operand1 to operand2
        $scope.registers[operand2.value] = operand1.value
      else if operand2.type is 'ADDR' # Must deference the value of this operand
        $scope.addresses[hex(operand2.value)].value = operand1.value
    else
      0

    return
  $scope.$on 'mem.sub', (e, expr1, expr2) ->
    operand1 = resolve(expr1, $scope.registers, $scope.addresses)
    operand2 = resolve(expr2, $scope.registers, $scope.addresses)
    if operand1.type is 'REGISTER'
      if operand2.type is 'REGISTER' # Mov the content of operand1 to operand2
        $scope.registers[operand2.value] = $scope.registers[operand2.value] - $scope.registers[operand1.value]
      else if operand2.type is 'ADDR' # Must deference the value of this operand
        $scope.addresses[hex(operand2.value)].value = $scope.addresses[hex(operand2.value)].value - $scope.registers[operand1.value]
    else if operand1.type is 'ADDR'
      if operand2.type is 'REGISTER' # Mov the content of operand1 to operand2
        $scope.registers[operand2.value] = $scope.registers[operand2.value] - $scope.addresses[hex(operand1.value)].value
      else if operand2.type is 'ADDR' # Must deference the value of this operand
        $scope.addresses[hex(operand2.value)].value = $scope.addresses[hex(operand2.value)].value - $scope.addresses[hex(operand1.value)].value
    else if operand1.type is 'VALUE'
      if operand2.type is 'REGISTER' # Mov the content of operand1 to operand2
        $scope.registers[operand2.value] = $scope.registers[operand2.value] - operand1.value
      else if operand2.type is 'ADDR' # Must deference the value of this operand
        $scope.addresses[hex(operand2.value)].value = $scope.addresses[hex(operand2.value)].value - operand1.value
    else
      0
    
    return

  $scope.$on 'stack.push', (e, expr)->
    # if value[0] == '%' # dereference a register
    #   value = $scope.registers[value[1..]]
    rsp = $scope.registers.rsp
    $scope.registers.rsp -= 32

    operand = resolve(expr, $scope.registers, $scope.addresses)
    if operand.type is 'REGISTER'
      $scope.addresses[hex(rsp)].value = $scope.registers[operand.value]
    else if operand.type is 'ADDR'
      $scope.addresses[hex(rsp)].value = $scope.addresses[hex(operand.value)].value
    else if operand.type is 'VALUE'
      $scope.addresses[hex(rsp)].value = operand.value
    
    return
  $scope.$on 'stack.pop', (e, addr)->
    $scope.registers.rsp += 32
    return

  $scope.$on 'sys.lea', (e, expr1, expr2)->
    operand1 = resolve(expr1, $scope.registers, $scope.addresses)
    operand2 = resolve(expr2, $scope.registers, $scope.addresses)
    if operand1.type is 'REGISTER'
      console.error 'Invalid instruction: LEA cannot take a REGISTER in the first param'
    else if operand1.type is 'ADDR'
      if operand2.type is 'REGISTER' # Mov the content of operand1 to operand2
        $scope.registers[operand2.value] = operand1.value
      else if operand2.type is 'ADDR' # Must deference the value of this operand
        $scope.addresses[hex(operand2.value)].value = operand1.value
    else if operand1.type is 'VALUE'
      console.error 'Invalid instruction: LEA cannot take an IMMEDIATE VALUE in the first param'
    else
      0
    return
  $scope.$on 'sys.callq', (e, addr)->
    return
  $scope.$on 'sys.leaveq', ()->
    return
  $scope.$on 'sys.retq', ()->
    return
    
  return

module.controller "StackUI", ($scope) ->
  $scope.probeCell = (addr)->
    console.log "#{addr.addr}=#{addr.value}"
  
  return

module.controller "RegistersUI", ($scope) ->
    
  return

hex = (int)->
  zeros = '00000000'
  int = new Number(int).toString(16)
  "#{zeros[..8-int.length] + int}"

# Resolve an ASM addressing model to a:
# - "value" an integer which could be another address. It's the ASM world
# - a register name
resolve = (expr, regs, addresses)->
  rgx_reg         = /^%(\w{2,})$/ # Get the name of the register. R/W
  rgx_reg_val     = /^\(%(\w{2,})\)$/ # Get the value pointed by the register. R/W
  rgx_imm         = /^\$0x([\da-f]+)$/ # Get the value in hex
  rgx_offset_addr  = /^(\-?)0x([\da-f]+)\(%(\w+)\)$/ #TODO more complex. Get the offset address
  rgx_addr        = /^\(\$?0x([\da-f]+)\)$/ # Get the value pointed by the address. R/W

  if m=expr.match rgx_offset_addr # I'm a complex expression
    reg_val = regs[m[3]] # get the register value
    offset = if m[1] then -parseInt m[2], 16 else parseInt m[2], 16
    ret =
      type:   'ADDR'
      value:  reg_val + offset

  else if m=expr.match rgx_reg # I'm a register: %rsp, %rdx
    ret =
      type:   'REGISTER'
      value:  m[1]

  else if m=expr.match rgx_reg_val # I'm a register evaluated
    ret =
      type:   'VALUE'
      value:  addresses[regs[m[1]]].value

  else if m=expr.match rgx_imm # I'm a value. Should be understood "as is"
    ret =
      type:   'VALUE'
      value:  parseInt m[1], 16

  else if m=expr.match rgx_addr # I'm an address to be dereferenced
    ret =
      type:   'ADDR'
      value:  addresses[m[1]].value

  else
    console.error 'Could not resolve', expr
    0
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console