Tuesday, February 01, 2005

TCL

I've been looking up a lot of TCL lately. Wrote my first script. Its for modreg.tcl, which modifies a field within a register without disturbing surrounding bits. Assume commands readreg (which reads the contents of a register, specified by its hexadecimal address in memory) and writereg (which writes a value to a register).

#!/usr/bin/tclsh
#
# Usage : modreg.tcl reg value low high
#
# Example : modreg.tcl 0x340 0x11 3 7
#
# Now, this would read register 0x340, write the value 0x11 into
# bits 3 through 7 and write this back into register 0x340.
#

# Power procedure
proc power {base p} {
set res 1
while {$p>0} {
set res [expr $res*$base]
set p [expr $p-1]
}
return $res
}

# Check arguments
if {$argc != 4} {
puts "Invalid arguments!"
return 0
}

# Read arguments into variables
set reg [lindex $argv 0]
set new [lindex $argv 1]
set low [lindex $argv 2]
set high [lindex $argv 3]

# Swap low and high if user entered them backwards
if {$low > $high} {
set temp $low
set low $high
set high $temp
}

# Process high
set high [expr $high+1]

# Read register value into 'val' with the 'readreg' command
set val [exec readreg $reg]

# Process variables 'highp' and 'lowp' from low bits and high bits
set highp [expr {[power 2 $high]-1}]

if {$low == 0} {
set lowp 0
} else {
set lowp [expr {[power 2 $low]-1}]
}

# Find number to AND with 'val' to clear the appropriate bits
set and [expr {0xffffffff - $highp + $lowp}]

# Clear the appropriate bits
set clear [expr {$val & $and}]

# Left-shift the value to be written to the field by appropriate amount
set or [expr {$new << $low}]

# Find result by ORing this with 'clear'
set result [expr {$clear | $or}]

# Write this result into the register with the 'writereg' command
set ret [exec writereg $reg $result]

0 Comments:

Post a Comment

<< Home