SMC (Self modifing code) under Linux with GAS

April 14, 2009 – 2:18 am

With the Gnu Assembler (also known as GAS) it is quite simple to write self modifying assembly code. The only issue is that you can’t make the text section directly self modifiable you have to create a new section:

.section .text
.globl _start
_start:
  jmp modifing # directly jump in the smc section where code is modifiable

.section .smc, "awx" # set the section as allocatable, writable and executable
modifing:
  movl $1, %eax
  addl $17, modified (,%eax,) # Set the return code as 17 instead of 0.

modified:
  movl $0, %ebx    # This is the instruction that is modified.
                   # The $0 will be changed in $17.
                   # If you look at it in machine code the first byte is
                   # the instruction "movl into ebx"
                   # and the other 4 next bytes are the number $0.
  movl $1, %eax
  int $0x80

Free lifting for a space elevator

January 7, 2009 – 12:20 am

As I was reading an article about a new kind of lifter for the space elevator, I started thinking about the energy you would need to bring anything to the geostationary orbit. I also remember thinking that over the geostationary orbit, moving still upward gives you energy. If you imagine the space elevator as a tube and you put a rock in it, under the geostationary orbit it falls downward, but over it it falls upward. So there is energy to be salvaged if you let the object go above the orbit.

The potential of this rock looks like that

[this curb is shamefully stolen from this page I hope the author will forgive me but it looks a lot better than the one I made]

It comes from the gravitational potential [from wikipedia but can be easily calculated as the integral of the force]

With G the gravitational constant, Mt the mass of the earth and r the distance from the center of the earth.

And the centrifugal one which is V = - w^2 * r^2 / 2 [as the integral of the force |F| = w^2 * r].

With w the angular speed of the earth and r the distance from the center of the earth.

I bet you could notice that the top of the curb is the geostationary point where the potential is maximum, it produces an instable equilibrium. Something else that I would like to point out is that if you suppose that the space elevator has no counterweight and its diameter does not change, then this is similar to the equation of the integral of all the forces on the cable ! Which means that the cable will fall on the earth unless it is longer than DE (the point where the equation reach 0).

DE ~ 144000 km

So DE is 4 times higher than the geostationary orbit which is at 36000 km, and about a third of the distance to the moon.

So the center of mass of the cable is at half DE which is at about twice Dgeo (the distance to the geostationary orbit). So the center of mass is usually quite different from the geostationary point ! This has already been noticed and explained here but wikipedia still has an image that states the opposite on the space elevator article, let’s hope this will be fixed soon.

Now let’s think of this curb in another way: it represents the minimum energy needed to get an object to a certain height on the space elevator. So it means that you don’t need any energy to get an object to DE, the energy that you consume fighting gravity to get the object to the geostationary point can be regained by the centrifugal force. It will absorb the kinetic energy of the rotating earth and slow down the earth rotation on itself.

And what if we make the elevator longer than DE ? Then you can actually gain energy by moving matter all the way up the elevator ! This can also be thought of as a siphon: if you attach a giant drinking straw at the bottom of the ocean that goes all the way above DE and start to siphon water off the straw, then once you initiate the move, water will continue flowing into space, emptying the oceans until the earth stand still or the oceans are empty (I leave it to you to determine which one happens first), if water doesn’t freeze in the straw of course.

This is all nice and theoretical but what about practice ?

Let’s put a pulley on the earth and possibly one in space and have a cable turn around them, so that the cable is moving upward and downward. Now attach some rocks regularly along the cable on the ground (not too much the total mass of the rocks must be a lot smaller than the mass of the cable) and let go of them at the top of the cable. If the cable is longer than DE then the cable will be accelerated by that ! And it could be used to lift some passenger or material to geostationary orbit instead of rocks, which might possibly be more useful.

This could also be used as a clean energy source. We could use the rotation of the wheel inside the pulley on the ground to produce electricity. It is also interesting to notice that it is possible to slow down the rotation of the earth on itself without consuming any energy and without any interaction with another body such as the moon.

This may not be an original idea but I haven’t found any reference to it while googling.

Compared to a “standard” elevator with a counterweight it has various good and bad points.

Good:

- lifting doesn’t consume any energy, in fact it could produce some

- no lifting problem: you just have to attach yourself to the moving cable

- you can go up and down at the same time

- the tension on the cable isn’t necessarily higher than on a “conventional” elevator except for the fact that the thickness of the cable must be constant

Bad:

- need a ~6 times longer cable than an elevator with a counterweight

- the thickness of the cable must be constant

- must be careful that the cable going up won’t touch the cable going down

[edit a nicer schema contributed by a friend]

Why is programming repetitive ? Was Turing wrong ?

December 13, 2008 – 11:48 pm

Instruction tables will have to be made up by mathematicians with computing experience and perhaps a certain puzzle-solving ability. There need be no real danger of it ever becoming a drudge, for any processes that are quite mechanical may be turned over to the machine itself.

Alan Turing

In essence Turing was saying that programming should never be boring or repetitive. Because you should always be able to program any repetition.

I don’t know about you but this is not the feeling I got when programming in c or java. In fact this is not a feeling I always get when programming in python !

Was Turing just plain wrong ? Or are we just fools ? Fools that use languages too complex for our own good. Languages so complex that they become black boxes that you dare not modify or extend in order to forget about repetitive programming.

Maybe we went in the wrong direction when choosing C over lisp. I have a feeling that this quote is not that wrong when programming in lisp.

I wonder what Turing would have done if he had lived to an old age. I dare hope that he would have made his words come true.

PS: I like Turing word for a programmer. I want to put “mathematician with computing experience and perhaps a certain puzzle-solving ability” on my resume.

Using grep to search in files

November 5, 2008 – 11:14 pm

I’m moving away from eclipse and more and more into the wonderfull (and cold) world of the command line.

So I need to search for file that contain something in the current directory and its subdirectories all the time

grep -R "something I'm searching for" .

Grep is the way. And with some colors it’s still nicer

grep -R --color "something I'm searching for" .

Now what if I only want files that end with .py that’s a little more subtle

grep -R "something" $(find . -name "*.py")

Now if you want still better you can go for ack which is a grep like tool, only better

ack "something" .

Yeah you don’t have to type the -R it’s the default, also the executable is called ack-grep under debian/ubuntu.

Don’t feel like typing the . that says you’re searching in the current directory ? Add that to your .bashrc

g() {
  if [ $# = 1 ]
  then ack -i $1 .
  else ack -i $@
  fi
}

Now you can search in the current directory with a simple

g something

Don’t forget to replace ack by ack-grep under debian/ubuntu.

Finally installed archlinux

November 5, 2008 – 10:35 pm

That’s it, the new ubuntu was coming and I was thinking, I’ll get gimp 2.6 and tabs in nautilus … But I should wait a few days before updating cause update is always buggy the first days …

And fuck that I wanted to install archlinux anyway (it’s just that I needed to backup my whole computer and felling very lazy about it) so I overcame my laziness and finally got into the wonderfull world of arch pacman and yaourt.

Pacman is the package manager used by arch and it is great, making a new package is really really simple which means that you can make your own package when installing software from source. Also arch has a good number of compiled packages, not as many as debian but quite a lot. And it has a huge number of source packages that can be installed really easily by using yaourt. Yaourt makes installing anything as easy as typing

yaourt anything

Oh and the archlinux wiki is great. Making the install really easy.

Gimp 2.6 is out !

October 1, 2008 – 8:49 pm

I’m using GIMP 2.4 at my job to make a website and I heard a lot of people bad-mouthing it so I expected having a bad time with it, but it’s really usable. And I had no experience of it before, my previous experience of photo editing takes me back 7 years ago in high school and with some Paint Shop Pro.

At work I have Photoshop in a windows within a VirtualBox in my Ubuntu, and … it’s awfully slow. I mean gimp isn’t fast to start up but Photoshop is something else. It takes about 20 seconds to start up.

So having the choice between the two I chose to use Gimp and I’m really happy with it. Can’t wait to try 2.6 and all its new nice features.

We are just like C

September 26, 2008 – 12:06 am

Dear blog, it’s been long since I last talked to you, but I felt like doing it tonight. This is the unfaithful transcription and translation of a chat I had tonight.

me: Math sucks.

mister M: That’s not what you told me 10 minutes ago when talking about the number theory described in GEB.

me: You don’t know when something is beautifull and cool or when it is bloated and ugly and you only learn it that way cause it was discovered that way.

me: You’re not good enough to know.

me: The two cases exist.

Mister M.: Hehe, I think there is a limit to ugliness.

Mister M.: When you reach it, people snap and agree, “ok let’s change that”.

Mister M.: But the limit must be pretty far away.

me: Math are good when you’re able to say: your concepts sucks, they are equivalent to this beautiful concept which is very powerfull, so let’s not talk about your shits anymore.

me: And I agree with you there is a practical limit, if you simplify old concepts your students won’t understand anything about those official old concepts. So for a new concept to work it must be simple and powerfull enough for your students to gain enough time from using it to be able to translate back into the old concepts within that gained time.

me: Actually I read a post about this recently, well not exactly that it was about programming languages, for a new language to work it must solve a problem that is harder that the time you need to learn this new language.

Mister M.: It was saying bad stuff about C I’m sure.

me: No. At all. Hum I don’t remember, but I don’t think so.

Mister M.: I’m just on the defensive.

(Mister M likes the C language a lot, and what I just said could be a good argument to say that C is still here cause it was here first.)

me: Hehe, I understand.

(And I do like to criticize C)

me: Survival of the fittest meme, or maybe not fittest but already in place.

Mister M.: Hehe.

me: It’s the same for animals: they start from a niche and only from there they can spread.

Mister M.: Haha how we blew up all the other species !

me: And now we’re in place they have no chance. We’re just like C.

Mister M.: Clear, C has nothing to do in many places where it is used.

Mister M.: Like us in antactica.

Mister M.: Or in the Arizona desert.

me: Well this deserves a blog entry. And I’m gonna twist all your words …

END

PS

me: How do you translate “Je suis juste sur la défensive” in english ? I’m just on the defence ?

Mister M.: It sounds strange.

Mister M.: WordRefence says on the defensive http://www.wordreference.com/fren/defensive

me: Arg. It sounds french, come on, tell me your sentense in english.

Mister M.: I’m on the defensive.

me: lol, ok fine.

Mister M.: English is french.

Linux distros

July 22, 2008 – 10:35 pm

I found a cool schema that I hadn’t seen before on reddit today: the linux distro timeline.

We notice three main roots Debian the community distro, Slackware the one man distro and Red Hat the company developed distro. I guess everyone know them, nothing to see move along.

What’s interesting ? The other roots that are still alive.

  • Smoothwall: a firewall
  • Engarde: company developed internet services oriented
  • Yoper: supposedly the “fastest out-of-the-box distribution”
  • Pardus: now an interesting one, a distro which rewrote many tools in python including a package manager and an init system. It is easy to use and KDE based. Also it’s developped in Turkey. Great distro.
  • Puppy: a livecd that is so small that the entire operating system and all its applications can be loaded in 256 MB of RAM
  • DeLi: a desktop distribution for old PCs
  • Sorcerer: a source based distribution like Gentoo
  • Gentoo: THE source based distribution, used for its great source based package manage (portage)
  • CRUX: a lightweight, i686-optimized distro targeted at experienced users, gave birth to Arch
  • Rock Linux: a flexible Linux distribution Build Kit
  • Linux from scratch: not really a distro, it’s a book about how to build your own linux distro
  • GoboLinux: let’s reorganize the filesystem and place all programs in one folder and keep things simple and logical, nice ideas, lack packages
  • dine:bolix: no idea and I’m getting tired of this
  • Ark: easy to use desktop distro

What about me ? Well I’m still on the ubuntu that was installed on my dell laptop. I’m planning to install arch linux (in fact I already did it in a virtual machine) which has a really great package manager which makes it really easy to make your own packages. Also I like its minimalistic approach and the idea of not patching the upstream more than necessary, and debian and therefor ubuntu love patches. But dell puts all in one partition, so I can’t install a new distro without backuping all my data and formating my hard disk. So for the time being I’m staying on my nice and working ubuntu.

What are your chances of hitting a fly with a tennis racquet?

July 18, 2008 – 1:09 am

Just one of the problems that I finished solving a few hours ago for google code jam. It’s the first time I tried a programming competition, and it’s a pretty interesting one. Problems are hard but solvable and you always get a few sample inputs and outputs, which is really really helpful. Programming competition often focus on speed of execution and python isn’t a good competitor then (except for a scripting language around C maybe), but I think code jam is a lot more focussed on the algorithm: you’ve got a bad algorithm ? You’ll be too slow anyway. You have a good one ? Your program will be fast enough in python or (even probably) ruby.

I see problems in three categories:

  1. problems complicated to understand or to translate to a program but without algorithmic complexity (if your implementation works it’s usually fast enough) and without too much math, think string manipulation for example, or parsing a grammar
  2. the same but with the complexity based on math, often geometry problems requiring a good knowledge of trigonometry, yeah the hit a fly with a tennis racquet problem is one of them
  3. problems that you can easily make into an inefficient brute force program, but that get hard when trying to solve with an efficient algorithm

I don’t like the first category: you make a program that works with the few examples you have and then if you are lucky you’re finished pretty quickly. But because there are so many cases it will probably break in some situations, and you can’t know which ones, and you can’t really test your program cause you don’t know what the output should really be. To test your program you would need to reimplement it in another way and since you have already done the easier way … well it’s hard.

The second type is … harder when you don’t have (or have forgotten) the math skill … easier if you’re a math nerd. After having solved the math problem implementing the program is usually easy enough.

The third type is fun. You can start by implementing a brute force method quickly, that will obviously be too slow for large inputs, but then you can use this method to compare the result with your optimized method, if your optimized method doesn’t always provide the good result. And I like this category of problems, I like exploring the space of solutions in a smart way. Here is a small class I made to write exploring code quickly, but which is often not efficient enough …

class Explorer(object):
    """The explorer class to explore a finite tree of possibilities.
    The basic usage is
    e = Explorer()
    while e.next():
        person = e.choose(['Linus', 'Theo'])
        if person == 'Linus':
            object = e.choose(['the linux guru.', 'a stupid dickhead.'])
        elif person == 'Theo':
            object = e.choose(['the openbsd guru.', 'a masturbating monkey.'])
        print person, 'is', object
    Which should display:
    Linus is the linux guru.
    Linus is a stupid dickhead.
    Theo is the openbsd guru.
    Theo is a masturbating monkey.
    """
    def __init__(self):
        """Init isn't enough you need to call next after initialising.
        """
        self.current_branch = None
    def next(self):
        """Start a new branch. Return False if it is the end. True if it is not.
        """
        if self.current_branch != None:
            branch = self._next_branch(self.current_branch)
            if branch == None:
                return False
        else:
            branch = []
        self.infinite_branch = self._infinite_branch(branch)
        self.current_branch = []
        return True
    def choose(self, list):
        """Choose an element in a list.
        """
        choice = self.infinite_branch.next()
        self.current_branch.append((choice, len(list) - 1))
        return list[choice]
    def choose_or_not(self, list):
        """Choose an element in a list, or return None.
        """
        choice = self.infinite_branch.next()
        self.current_branch.append((choice, len(list)))
        if choice == 0:
            return None
        return list[choice - 1]
    def _next_increment(self, branch):
        for i, (choice, maximum) in enumerate(reversed(branch)):
            if choice != maximum:
                return len(branch) - i - 1
        return None
    def _next_branch(self, branch):
        position = self._next_increment(branch)
        if position == None:
            return None
        result = branch[:]
        result[position] = result[position][0] + 1, result[position][1]
        for i in range(position+1, len(result)):
            result[i] = (0, result[i][1])
        return result
    def _infinite_branch(self, branch):
        for choice, maximum in branch:
            yield choice
        while True:
            yield 0

Oh yeah I don’t actually answer the question in the title … I don’t really feel like explaning all the problem actually. I’ll just say that I solved it thanks to sage. It’s a great replacement for a TI-89, or matlab, or mapple or mathematica. It’s all of that and more, and in python. The language is actually a very slightly modified python. Here is an example that was helpfull in solving the tennis racquet problem:

sage: var('x')
x
sage: integral(cos(asin(x)))
arcsin(x)/2 + x*sqrt(1 - x^2)/2

Good news everyone ! Futurama: the beast with a billion backs is out

July 13, 2008 – 1:19 am

Futurama: the beast with a billion backs is out in DVD in the US and Canada and illegally on the internet for others, may it lead to the end of civilisation. This is a must watch. Futurama is as witty and fun as ever. You will have the honor to meet Fry new girlfriends (well one isn’t really a girl but I digress), the head of Stephen Hawking with the real synthesised voice of Stephen Hawking, and a great way to settle scientific disputes: Deathball

Bad news everyone. Five more months to wait before the next futurama movie: Bender’s Game.