Search Results: "xam"

3 December 2008

David Bremner: Using GLPK from C++

Recently I suggested to some students that they could use the Gnu Linear Programming Toolkit from C++. Shortly afterwards I thought I had better verify that I had not just sent people on a hopeless mission. To test things out, I decided to try using GLPK as part of an ongoing project with Lars Schewe The basic idea of this example is to use glpk to solve an integer program with row generation. The main hurdle (assuming you want to actually write object oriented c++) is how to make the glpk callback work in an object oriented way. Luckily glpk provides a pointer "info" that can be passed to the solver, and which is passed back to the callback routine. This can be used to keep track of what object is involved. Here is the class header
#ifndef GLPSOL_HH
#define GLPSOL_HH
#include "LP.hh"
#include "Vektor.hh"
#include "glpk.h"
#include "combinat.hh"
namespace mpc  
  class  GLPSol : public LP  
  private:
    glp_iocp parm;
    static Vektor<double> get_primal_sol(glp_prob *prob);
    static void callback(glp_tree *tree, void *info);
    static int output_handler(void *info, const char *s);
  protected:
    glp_prob *root;
  public:
    GLPSol(int columns);
    ~GLPSol()  ;
    virtual void rowgen(const Vektor<double> &candidate)  ;
    bool solve();
    bool add(const LinearConstraint &cnst);
   ;
 
#endif
The class LP is just an abstract base class (like an interface for java-heads) defining the add method. The method rowgen is virtual because it is intended to be overridden by a subclass if row generation is actually required. By default it does nothing. Notice that the callback method here is static; that means it is essentially a C function with a funny name. This will be the function that glpk calls when it wants from help.
#include <assert.h>
#include "GLPSol.hh"
#include "debug.hh"
namespace mpc 
  GLPSol::GLPSol(int columns)  
    // redirect logging to my handler
    glp_term_hook(output_handler,NULL);
    // make an LP problem
    root=glp_create_prob();
    glp_add_cols(root,columns);
    // all of my variables are binary, my objective function is always the same
    //  your milage may vary
    for (int j=1; j<=columns; j++) 
      glp_set_obj_coef(root,j,1.0);
      glp_set_col_kind(root,j,GLP_BV);
     
    glp_init_iocp(&parm);
    // here is the interesting bit; we pass the address of the current object
    // into glpk along with the callback function
    parm.cb_func=GLPSol::callback;
    parm.cb_info=this;
   
  int GLPSol::output_handler(void *info, const char *s) 
    DEBUG(1) << s;
    return 1;
   
  Vektor<double> GLPSol::get_primal_sol(glp_prob *prob) 
    Vektor<double> sol;
    assert(prob);
    for (int i=1; i<=glp_get_num_cols(prob); i++) 
      sol[i]=glp_get_col_prim(prob,i);
     
    return sol;
   
  // the callback function just figures out what object called glpk and forwards
  // the call. I happen to decode the solution into a more convenient form, but 
  // you can do what you like
  void GLPSol::callback(glp_tree *tree, void *info) 
    GLPSol *obj=(GLPSol *)info;
    assert(obj);
    switch(glp_ios_reason(tree)) 
    case GLP_IROWGEN:
      obj->rowgen(get_primal_sol(glp_ios_get_prob(tree)));
      break;
    default:
      break;
     
   
  bool GLPSol::solve(void)    
    int ret=glp_simplex(root,NULL);
    if (ret==0) 
      ret=glp_intopt(root,&parm);
    if (ret==0)
      return (glp_mip_status(root)==GLP_OPT);
    else
      return false;
   
  bool GLPSol::add(const LinearConstraint&cnst) 
    int next_row=glp_add_rows(root,1);
    // for mysterious reasons, glpk wants to index from 1
    int indices[cnst.size()+1];
    double coeff[cnst.size()+1];
    DEBUG(3) << "adding " << cnst << std::endl;
    int j=1;
    for (LinearConstraint::const_iterator p=cnst.begin();
         p!=cnst.end(); p++) 
      indices[j]=p->first;
      coeff[j]=(double)p->second;
      j++;
     
    int gtype=0;
    switch(cnst.type()) 
    case LIN_LEQ:
      gtype=GLP_UP;
      break;
    case LIN_GEQ:
      gtype=GLP_LO;
      break;
    default:
      gtype=GLP_FX;
     
    glp_set_row_bnds(root,next_row,gtype,       
                       (double)cnst.rhs(),(double)cnst.rhs());
    glp_set_mat_row(root,
                    next_row,
                    cnst.size(),
                    indices,
                    coeff);
    return true;
   
 
All this is a big waste of effort unless we actually do some row generation. I'm not especially proud of the crude rounding I do here, but it shows how to do it, and it does, eventually solve problems.
#include "OMGLPSol.hh"
#include "DualGraph.hh"
#include "CutIterator.hh"
#include "IntSet.hh"
namespace mpc 
  void OMGLPSol::rowgen(const Vektor<double>&candidate) 
    if (diameter<=0) 
      DEBUG(1) << "no path constraints to generate" << std::endl;
      return;
     
    DEBUG(3) << "Generating paths for " << candidate << std::endl;
  // this looks like a crude hack, which it is, but motivated by the
  // following: the boundary complex is determined only by the signs
  // of the bases, which we here represent as 0 for - and 1 for +
    Chirotope chi(*this);
    for (Vektor<double>::const_iterator p=candidate.begin();
         p!=candidate.end(); p++) 
      if (p->second > 0.5)  
        chi[p->first]=SIGN_POS;
        else  
        chi[p->first]=SIGN_NEG;
       
     
    BoundaryComplex bc(chi);
    DEBUG(3) << chi;
    DualGraph dg(bc);
    CutIterator pathins(*this,candidate);
    int paths_found=
      dg.all_paths(pathins,
                   IntSet::lex_set(elements(),rank()-1,source_facet),
                   IntSet::lex_set(elements(),rank()-1,sink_facet),
                   diameter-1);
    DEBUG(1) << "row generation found " << paths_found << " realized paths\n";
    DEBUG(1) << "effective cuts: " << pathins.effective() << std::endl;
   
  void OMGLPSol::get_solution(Chirotope &chi)  
    int nv=glp_get_num_cols(root);
    for(int i=1;i<=nv;++i)  
      int val=glp_mip_col_val(root,i);
      chi[i]=(val==0 ? SIGN_NEG : SIGN_POS);
     
   
 
So ignore the problem specific way I generate constraints, the key remaining piece of code is CutIterator which filters the generated constraints to make sure they actually cut off the candidate solution. This is crucial, because row generation must not add constraints in the case that it cannot improve the solution, because glpk assumes that if the user is generating cuts, the solver doesn't have to.
#ifndef PATH_CONSTRAINT_ITERATOR_HH
#define PATH_CONSTRAINT_ITERATOR_HH
#include "PathConstraint.hh"
#include "CNF.hh"
namespace mpc  
  class CutIterator : public std::iterator<std::output_iterator_tag,
                                                      void,
                                                      void,
                                                      void,
                                                      void> 
  private:
    LP& _list;
    Vektor<double> _sol;
    std::size_t _pcount;
    std::size_t _ccount;
  public:
    CutIterator (LP& list, const Vektor<double>& sol) : _list(list),_sol(sol), _pcount(0), _ccount(0)  
    CutIterator& operator=(const Path& p)  
      PathConstraint pc(p);
      _ccount+=pc.appendTo(_list,&_sol);
      _pcount++;
      if (_pcount %10000==0)  
        DEBUG(1) << _pcount << " paths generated" << std::endl;
       
      return *this;
     
    CutIterator& operator*()  return *this; 
    CutIterator& operator++()  return *this; 
    CutIterator& operator++(int)  return *this; 
    int effective()   return _ccount;  ;
   ;
 
#endif
Oh heck, another level of detail; the actual filtering actually happens in the appendTo method the PathConstraint class. This is just computing the dot product of two vectors. I would leave it as an exercise to the readier, but remember some fuzz is neccesary to to these kinds of comparisons with floating point numbers. Eventually, the decision is made by the following feasible method of the LinearConstraint class.
 bool feasible(const
Vektor<double> & x)  double sum=0; for (const_iterator
p=begin();p!=end(); p++)  sum+= p->second*x.at(p->first);  
      switch (type()) 
      case LIN_LEQ:
        return (sum <= _rhs+epsilon);
      case LIN_GEQ:
        return (sum >= _rhs-epsilon);
    default:
      return (sum <= _rhs+epsilon) &&
        (sum >= _rhs-epsilon);
       
     

Stefano Zacchiroli: thanks for the cookies Joss

You remember the bug sprint, don't you? I've already argued how nice the idea was, being a stereotypical example of how in Debian efficiency and fun can (and often must) go together. Well, Joss' cookies have been delivered to my office last Wednesday, unfortunately I wasn't there!!!, due to my participation first in the Debian QA Meeting in Extremadura, and then another academic workshop in Amsterdam. Sadly, I had to "delegate" the task of cookie tasting to other fellow Debian-ers which happen to work with me. Today I've finally got back to my office, and to much of my surprise, 5 cookies were still there waiting for me. In spite of the bad previsions about their health status after a week, they were delicious: simple biscuits, not too sweet, with walnut in pieces, and dark chocolate. So long Joss, and thanks for all the fish cookies.

2 December 2008

Theodore Ts'o: Is the Linux community watching a setting Sun?

The title of this post was a headline that was probably written by an overly sensationalistic editor at http://www.searchenterpriselinux.com. The actual article, though, was written by Pam Derringer, was a pretty balanced piece (although it obviously could have been more in-depth; given length and time constraints, she talked to as many people as I think could have been expected, including a Sun spokeswoman, two analysts from different analyst companies, the chair of Apache Software Foundation, a Sun customer, and so on). I’m not sure I’d agree with Jim Jagielski when he claims that Sun has the “best and brightest business people in the world,” though. As I said in the article, and as I’ve said before, I have nothing but the highest respect for many of Sun’s engineers, especially those who work on Solaris. But their business people? I’m not so sure they have the best and brightest… in fact, I think that’s one of Sun’s greatest problems right now. Compare that with the job that Mark Hurd has done with HP, or with the work done by the executives at my employer (IBM), and I’m not so sure a strong case can be made for the excellence of Sun’s business folk. (I mean, how many people still believe that the $2 billion dollars which Sun spent to acquire Cobalt Networks, or the $4 billion dollars which Sun spent to acquire StorageTek, or the $1 billion dollars which Sun spent MySQL, were all good ideas? Sun is currently valued by the market at $2.4 billion dollars!) My bigger concern at the moment, however, is what happens if Sun gets purchased by a rival or by a corporate raider and gets broken up for parts? Since November 19th, when Sun’s stock price crashed through $3.27 (and has hit a low of $2.60 recently), it has been trading for less than its per-stock cash value. I say that not out of a sense of Schadenfreude, but out of concern about what happens if someone decides to buy the company, lay everyone off, and even after paying all of its debts, the resulting cash left over would be more than cost of completely buying the company — all of the real estate, the inventory, and the patent portfolio would all be pure profit. It’s the last I’m most concerned about; Sun has a very large patent portfolio! What if it fell into the hands of a patent troll? What damage could be done to not just Linux and the OSS comunity, but the software industry as a whole? Suppose Sun really does have patents that read upon many of NetApp’s products? If those patents fall into the hands of a patent troll, NetApp would no longer be able to negotiate a peace settlement based on its patents (if they survive the on-going patent re-examination process) that read on ZFS, since the patent troll would no longer be making any products based on ZFS. Maybe somewhere in Sun’s patent portfolio, there are patents that read on the GNOME and KDE desktops, but since Sun is trying to ship those with its Project Indiana/Open Solaris dekstop, it’s not bothering to assert them at this time? What if a patent troll, perhaps one funded by Microsoft, gets their hands on those patents? One final scary thought. Sun’s current market cap: $2.40 billion USD. Sun’s cash on hand: $2.63 billion USD. Microsoft’s current cash on hand: $19.71 billion USD. I can just imagine Steve Ballmer saying, “Chris, take it out of petty cash. I have an itsy-bitsy little acquistion I want to make…. Now I can embrace and extend Java all I want! And you know those term-limited, non-Open Source TCK licenses Sun gave to OpenJDK developers — not any more! They’re gone, within a year, the next time Red Hat needs to get the license renewed!” Could it happen? What do you think?

Aigars Mahinovs: iPhone review from a free software guy

I got an iPhone on the very first day it was available officially in my country. I have used it every day since then and am now ready to decide how good it really is. Summary: it is a great piece of technology and the only tradeback is the locked down platform. I have abandoned my Palm and am not looking back. Hardware: the hardware is just perfect. 4 buttons (Home, Power, Volume Up and Down) and 1 switch (Mute) are all very clear, easy to find and press and frankly are enough. The touchscreen is reasonably fast and very precise nicely corrected by software that guides your presses toward UI points of interest if such are within your finger. The casing is absolutely solid - there is no gaps, no wobble, nothing. All glossy surfaces attract fingerprints, but a couple passes with a microfiber cloth (included) clean it up easily. The loudspeaker is phenomenal - all sound comes from a single small hole, but it can easily fill a small room with music. Call sound quality is impeccable. You can plug in any headphones, but if you use the included headphones you get a microphone with a button that can pickup and hand up calls, start/pause music and skip to the next track. I also love that the only charger included is a very small power brick that provides a power-only USB port and a USB charging cable. That is a good way to reduce number of power bricks for gadgets. The iPhone 3G (that is what I have) also has a GPS build-in, but let us be clear - it is not good enough to replace a car GPS, the iPhone GPS is slow (takes several seconds to refresh the location and tens of seconds to find it first time) and the precision is measured in meters or even tens of meters. The WiFi is very good at getting a connection and doing it very fast. Oh and there is an acceptable camera. Out of the box software: the software included surely is better than on any other phone I have seen (including Palm). The UI widgets are nicely written specially for a touchscreen interface - the best example is having click wheels instead of drop down menus. It is much easier mentally to flick a wheel up or down then to click on a list, click to scroll the list and then click to select an entry. And the click wheel makes it much easier to correct off-by-one errors. Switches that look like regular physical switches instead of checkboxes is another very useful UI concept. I think a lot of this can be reused on the desktop as well. iTunes: and here comes the bad spot, the lock-in part. To get anywhere with the iPhone you need to associate it with an installation of iTunes. It fails to work in Wine or even in a virtual machine - apparently there are some errors related to avahi or something. Unfortunately, this means that you need wither Windows or MacOS to do nything with your iPhone. iTunes is the only way to backup, restore and upgrade your iPhone, it is the only way to get contacts and music on the iPhone (there is an iTunes Store app in the newest version that allows purchasing music over the air). Even after doing a jailbreak (see further) it is currently not possible to add music to the iPhone from any third party applications, because the iTunes database has a hashed checksum that the build-in iPhone music player (and iTunes) check before doing anything. If the checksum is wrong the only thing you can do is a full restore of the phone from backup. Crypto geeks - please help decrypt that hash, so that we can sync iPhones to amaroK. The iTunes itself is a bit weird - to get music onto the phone you need to create a playlist and then you can sync that playlist over. One of the playlist options is a smart playlist with a random feature and a limit on number of matches. That is the way to get random music from your collection onto the phone. I do dislike the fact that iTunes syncs all the contacts from Google to the phone and not only contacts for a certain group or only those that have a phone number, for example. Search and favorites do help here. Third party software (iTunes Store): it is very easy to install new software on the phone over the WiFi and there is plenty to choose from. You do need a Mac to develop this software which restricts the developer base a bit. The main bases that I needed (or did not know I needed) are covered: Last.fm player, TwitterFon, LockBox password storage, Stanza ebook reader, Shazam music identificator, Wordpress client, BigOven cookbook and lots of fun games. Have not used any paid-for apps due to the fact that iTunes store is not available in Latvia and the official documentation recommends registering with a fake address in UK or US. :) Most of the software is rather stable and useful, but there is also a lot of fluff. User reviews and ratings help a lot, can we have those for Debian packages? Jailbreak and third party software (Cydia): thanks to some anonymous hackers, we have the ability to break the software jail on the iPhone and install software that Apple did not approve. The process is made very simple, but again it does require you to boot into Windows or MacOS X. The main thing the jailbreak process does is install an installer on the phone. Currently the best one is Cydia which is built on top of … apt-get and dpkg! After that is done, you can install a terminal, a ssh server and BossPrefs advanced preferences. There are also other interesting programs there - a different dock, file manager, caching youtube player, quake, themed app launcher with categories and startup page (winterboard). Theoretically the ssh server allows you to manage your music over WiFi from any platform, but unfortunately until the iTuned database hash algorithm is decoded, we can only copy music from the phone to the PC and not back. It is possible to copy files over using ssh and then play them using third-party players, but those players are very crude and featureless. To summarize: an iPhone is a great phone and a decent application platform. To make using an iPhone with Linux easier we need to make iTunes run in Wine (and allow it to see the iPhone) and reverse engineer the iTunes database hashing algorithm so that we can get music on our phones with Linux tools. I also wish there was a way to develop iPhone apps in Linux, but that really is reaching for the stars.

30 November 2008

Theodore Ts'o: Followups to the ebooks ethical question

When I have a moment, I’ll try to tally up the responses that I got to “An ethical question involving ebooks”and see if there are any interesting patterns based on self-identified generational markers. Obviously, this is not a properly controlled survey, so the results aren’t going to mean much, but it is interesting that some fairly passionately written comments came from folks who self-identified as coming from generations that broke with the common stereotypes of their respective demographic groups. If I were going to commission a study, one thing that I would almost certainly do is to ask pose a similar question about music and mp3’s, and do have the surveys asking the question about ebooks first, and half the surveys asking the questions about music first. It would be interesting to see if (a) there is a difference in attitudes between music and books, and (b) whether the order of the questions might influence the answers or not. A number of poeple have asked me about the author’s name and the title of the books/series involved. I deliberately didn’t include that information, for a number of reasons. First of all, I don’t believe idenifying the author/books/character involved is relevant to the question at hand, and in fact, might be distracting. Secondly, given the many comments, some of them quite passionate, I don’t think it would be fair to drag her name into the discussion without her permission first. I will say that the author does have a fairly extensive internet presence, and has apparently gotten a lot of questions about said character, and in fact whether those books would be made into ebooks. It’s been made quite clear that while those books were successful, they weren’t that successful, and so from an economic point of view, she chooses to write books that she (and her publishers) feel will be more economically viable. Because there will likely be no further books published containing this character, it is very unlikely that the publisher will reprint the original series of books — and when asked about whether they would be made available in ebook form, her response was effectively “it’s up to the publisher”, Apparently she has worked with a number of publishers, and while publisher X hasn’t been willing to publish her books in ebook form, publisher Y has. Furthermore, it seems that her contracts apparently delegate all decisions about how her books will be published, and whether a large Major Big City Law Firm with Fangs (aka MBCLFF) will go after copyright infringers to her publishers and her agent (who is a lawyer at said MBCLFF, and who could presumably inflict major Hurt on copyright infringers that curry the lawyer’s disfavor). I don’t know if this is true, or just her way of managing her relationship with her fans by disclaiming all responsibility about publication forms and enforcement decisions to others — but some authors do make such choices, if they are much more interested in the writing and storytelling end of things than the business side of things. Which brings up an interesting question with respect to copyright enforcement. It’s pretty obvious that many people will give different answers to the question relating to how much deference should be given to copyrights depending on whether they are owned by The Struggling Author versus whether they are owned by The Big Media Corporate Monolith, with many more allowances given if the question is framed as being primarily about the former rather than the latter. Another way in which how you frame the question radically changes the outcome depends on whether the focus is on making sure the author (and/or his surviving widow/widower/children) get paid or whether the focus is on control of one’s works. If you believe the primary justification is an economic one, then that leads to a series of ethical conclusions — the most obvious of which is that if it doesn’t result in a direct (or perhaps indirect) monetary loss to the author, there should not be a moral or ethical problem. There might be some question as to whether devaluing the secondary market might discourage the sale of new books, and hence indirectly harm the author sufficiently that this should be a concern, but those issues can be worked out. If however, you believe the primary issue at hand is one of control, a very different set of issues have to get factored into the conversation. For example, what if the author was ashamed of a book or series, and wants it to go quietly out of print, and hopefully disappear. How should that be weighed against fans who disagree with the author and who love the series? What is the right balance? For those who argue that the author’s wishes should be sacrosanct — should we move things more in that direction? What if all texts lived in DRM’ed, encrypted containers, and electronic readers had to ask permission of a central authorization server for the text could be displayed. This would allow the author to, after the fact, disable anyone from reading his or her works, if for some reason the author so desired it. Would that be a good thing? If not — and I hope most authors would agree this would be horrific power to give copyright holders — then it’s clear that author’s moral rights as creators should not be entirely sacrosanct, and that the society also has some claims on preserving its culture, and that once a book has been published and becomes part of the culture, society should have some claim on that book as part of culture. Whether that means that copyright terms should be 14 years or 20 years as opposed to whenever the Disney corporation feels like paying off more legislators to extend copyright terms is one way that question could be asked. Another is whether society should have the right to say that if after some number of years where a work has been abandoned for commercial exploitation, whether it should automatically enter the public domain. There are no obvious answers here. The final point that I want to make, which may be fairly controversial amongst the Open Source programmers in the room, is that if you believe that copyright should be fundamentally be about economic arguments of “no harm, no foul”, that this is in direct contradiction with the belief that lawsuits should be used in order to enforce the GPL. After all, the conditions imposed by the GPL are fundamentally about control, not about economic issues. Consider — if someone uses the Busybox project in an embedded device — especially if no changes has been made to the code — who has been harmed, economically? No harm, no foul, right? Or if someone uses GPLv3 code in a firmware which is protected by a digital signature — sure, it means that end users who want to modify the firmware and then use it to enhace/extend the device won’t be able to do so. But how does that economically harm the author of the GPLv3 code? Fundamentally, Copyleft schemes are all about extending control over how the code can be used. Hence, if you are an Free Software programmer who cheers on the activities of the SFLC, or who firmly believes that no one should be allowed to mix firmware which is not shipped with source with your GPL’ed software, it is completely and profoundly hypocritical to say, “F*ck the author’s wishes; if it’s not available in the from I want, I should be able to make a derived work to transfer the work into a form that I want.” What if the author is a luddite who hates eBooks and firmly believes and wants to enforce that their works should never be made available in eBook form. How is that fundamentally different from a Free Software Acolyte saying that because they abhor non-free firmware, and don’t want allow their code to be shipped alongside binary-only firmware?

28 November 2008

Andrew Pollock: [tech] Wising up about SMART

I've always installed the smartmontools package on my servers because I figured it'd maybe give me some early warning about an impending disk failure. Getting proper SMART access was one of the motivating factors in moving my home-brew SAN from IDE-to-USB disks to native SATA. Since then, I've had two drives fail on me. One of the original four that I bought, and the replacement one that Seagate shipped to me. (Incidentally, I love how your only recourse to a replacement drive failing with Seagate is they'll ship you another (reconditioned) replacement drive. I can see the shipping expenses racking up very quickly). I decided to do the expedited return when the second drive failed, just because it meant I didn't have to be without a disk in my RAID-10 for a week while I waited for them to receive my drive and turn around and ship me a replacement drive, and it also meant I didn't have to mess around with packaging it myself. (Incidentally, I wonder what happens in Seagate's reconditioning process? Will someone else get my failed drive (i.e. the same serial number) after they replace the platters or whatever it was that failed? Would it be interesting to set up a website where people could register the serial numbers of drives they returned to Seagate, and how they died, and at how many power-on hours? How many times does a drive get "reborn"?) Whilst I was waiting for the replacement drive to arrive, I messed around with the failed one (I removed it from the RAID array), fiddling with the SMART self-tests that smartctl can initiate for you. The faulty drive failed the long self-test at the same LBA every time I ran it. It was around this time that I realised that the default configuration that comes with the Debian smartmontools package isn't all that useful with SATA disks. It ships with
DEVICESCAN -m root -M exec /usr/share/smartmontools/smartd-runner
which, as it turns out, doesn't detect SATA drives properly. I got
Nov 24 22:00:13 minotaur smartd[2990]: Device /dev/sda: ATA disk detected behind SAT layer 
Nov 24 22:00:13 minotaur smartd[2990]:   Try adding '-d sat' to the device line in the smartd.conf file. 
Nov 24 22:00:13 minotaur smartd[2990]:   For example: '/dev/sda -a -d sat' 
logged. It seems to me that if the software can detect this situation, it should be able to just try the "-d sat" behaviour automatically. So it seems that this whole time, I haven't been getting any SMART monitoring of my SATA drives. hddtemp has been happily logging the temperatures for me though. So I took the advice in the comments of /etc/smartd.conf and removed the DEVICESCAN entry in favour of explicitly naming the disks I wanted to monitor. I also discovered that I can have smartd kick off scheduled short and long self-tests on whatever schedule floats my boat. So now I've got something like this:
/dev/sda -d sat \
         -M exec /usr/share/smartmontools/smartd-runner \
         -s (L/../.././01 S/../.././(00 12))
This runs a long self-test at 1am every day, and a short one at midnight and midday. Hopefully this will help predict the next drive a bit earlier. I'm now debating whether to set up an active Nagios monitor for SMART, or to see if I can write a passive one that runs as part of the smartd-runner infrastructure that the smartmontools package provides (and is pretty neat). I guess it's already setup to email me, so it doesn't really matter whether it's Nagios emailing me, or smartd itself.

Theodore Ts'o: An ethical question involving ebooks

I recently purchased a short story from Fictionwise, which was not DRM’ed, so I could easily get it into a form where I could read it on my Sony eReader. Thanks to that short story, I was introduced to an author, and a character, which I found very engaging. When I decided to find out more about the character, I found that the author had written two additional short stories, and three additional novels many years ago, but has since stopped writing any more books involving that character. Furthermore, the novels have gone out of print, and are only available from amazon.com as used books. Unfortunately, I travel a lot. So much so, that one of the few times that I have time to read is when I’m traveling. And I really dislike having to haul dead-tree versions of my favorite novels around; they take up far too much weight and space in my carry-on luggage. Unfortunately, these out-of-print novels were published by a Neanderthal Publishing company who hasn’t made any of the books available in ebook format, DRM’ed or no. Grumpy, I searched on Internet, and found all three novels were easily available for free download — in a pirated form, of course. Should I download them and convert them into a form which would allow me to read them on my Sony eReader? Well, according to Russell Davis, former chair (and now president of the Science Fiction Writer’s Association) of the SFWA’s Copyright Committee, “electronic infringement is theft”. From a legal perspective, I suppose that is true. And given that as an Open Source programmer, I depend on Copyright Law to assure that my wishes as an author are upheld, it would be hypocritical for me assume that I should be able to ignore Copyright Law just because it is inconvenient. And yet… from a moral perspective, who has really lost anything? The argument made by Russell Davis is that infringement is bad because it is “harming authors and author estates”. Jerry Pournelle has indignantly proclaimed that e-piracy goes against a “specific (and very stern) Biblical injunction against stealing from widows and orphans”. Of course, in this case, the author is still alive (and is female, although I suppose stealing from widowers would be just as bad). Also, given that the author has publically stated she doesn’t plan to write any more books involving this character (since some of her more psychotic readers sent her death threats as a result of reading said books), the publisher is highly unlikely to re-release said novels — and if I buy used dead-tree versions of said novels, the author doesn’t receive any additional royalties. So, then, where is the moral bright line? Somewhere along this continuum, we’ve crossed over from the light-side to the dark-side. Setting aside the observation that the Neanderthal attitudes and business practices of the publisher involved has made it impossible for me to legitimiately follow the law, enjoy the novels, and direct money to the author via royalty payments — what do you think is the morally correct course of action? And why? And if you don’t mind saying so publically, roughly what generation are you from (i.e., Baby Boomer, Gen X, Gen Y, etc.)? I’m curious how attitudes are changing based on age, and whether folks who are currently in college might differ from those who can remember a time when the Internet didn’t exist… Update: I’ve posted a follow-up to this post here.

Russell Coker: Leaving Optus

Today I phoned Optus to disconnect my Internet service. Some time ago I got an Internode [1] SOHO connection. This gave me a much faster upload speed (typically 100KB/s) compared with Optus having a maximum of 25KB/s. Also Internode has better value for large data transfer (where “large” in Australia means 25GB per month) and I get a static IP address. I also get unfiltered Internet access, Optus blocks outbound connections to port 25 which forced me to ssh to another server to test my clients’ mail servers. But the real reason for leaving Optus is based on events two years ago. When I first signed up with Optus four years ago my contract said “unlimited uploads“. What they really meant was “upload as much as you want but if you transfer more than 8KB/s for any period of time you get disconnected“. They claimed that running a default configuration of BitTorrent was a DOS (Denial of Service) attack (the only part of their terms of service that even remotely permitted them to disconnect me). So I was quite unhappy when they cut me off for this. What really offended me was the second time they cut my connection. I had been running BitTorrent on Friday and Saturday, and they cut my connection off on Wednesday. Once it was determined that the issue was uploads we had a bit of a debate about when my BitTorrent session was terminated, it was my clear memory of using killall to end BitTorrent during a commercial break of a TV show on the Saturday night vs the Optus idiot claiming they had a record of me doing big uploads on the Sunday. But I let the help desk person think that they had won that debate in order to focus on the big issue, why large uploads on a Saturday (or a Sunday) should result in a loss of service on Wednesday (three or four days later). They said “it was to teach you a lesson“! The lesson I learned is that it is best to avoid doing business with Optus. I didn’t immediately cancel my contract, if you have both phone and Internet service through Optus they do offer a reasonable deal (there are a variety of discounts that are offered if you have multiple services through them). When discussing this matter in the past it had been suggested to me that I try appealing to the Telecommunications Industry Ombudsman etc. However I didn’t do this because I was in fact breaking the Optus acceptable usage policy for most of the time that I was a customer. When I signed up their AUP prohibited me from running a server and from memory I think it had a specific example of a shell server as something that should not be done, it now prohibits running any automated application that uses the Internet when a human is not present (which presumably includes servers). I’m pretty sure that my SE Linux Play Machine [2] met the criteria. While I’m reviewing Optus service I need to mention their mail server, here is the summary of the Optus anti-spam measures in protecting my email address etbe@optushome.com.au in September (other months were much the same):
131 emails have been sent to your Inbox.
52 of these emails were identified as spam and moved to the Spam Folder.
39% of your email has been identified as spam. The email address in question only received legitimate mail from Optus. This meant that I received between two and four valid messages a month, the rest were all spam. So of the 79 messages delivered to me, at least 75 were spam, and Optus blocked less than half the spam. But to be fair, given that the Optus mail servers are listed on some of the DNSBLs it seems reasonable for them to be lax in anti-spam measures. I wonder whether it would be reasonable for an ISP of Optus scale to run the SpamAssassin milter on mail received by their outbound relays to reject the most gross spam from customer machines. But Optus are good at some things. The download speed was always very good (I could receive data at 1MB/s if the remote server could send that fast). Also their procedures for account cancellation are quite good. The guy who took my call offered to transfer me to the complaints department when I mentioned how I was “taught a lesson”, he also offered me a significant discount if I was to continue using the service. In retrospect I should have had that conversation six months ago and had some cheap service from Optus before getting rid of them. Getting the account terminated happened in a couple of hours. It was so quick that I hadn’t got around to transferring my Play Machine to my Internode account before it happened, so I had a few hours of down-time.

Martin F. Krafft: Up the Khyber!

What started with a little host naming theme riddle, and spread as a meme across various planets, has come full circle today, as I installed a new machine, khyber.madduck.net in the racks hosted at the LayerOne colocation site in Z rich. Init Seven, my favourite Swiss ISP, are sponsoring the rack space and connectivity: a routed /28 IPv4 subnet and a /64 IPv6 subnet. The machine is a Transtec Calleo 331 1U server with two quad-core AMD Opteron 2354 processors, 16Gb of RAM, and 4Tb of disk space, configured into a 2Tb RAID1 with LVM on top. It will be used to host a couple of KVM instances for a number of projects I currently operate off my main, personal server, pulse.madduck.net. Unfortunately, Transtec (as well as most other vendors I checked out) uses nVidia s MCP55Pro chipset, which had me sceptical long before I sent the order. nVidia is known to suck at thinking open-source, and the Linux kernel driver for their network chips, forcedeth, had to be reverse-engineered, because nVidia failed to cooperate. Apart from that, nVidia s chips are also often simply crap. Many of their motherboards come with broken APICs and the network chips often wreak havoc on subnets. I find it curious that a search for MCP55 or MCP55Pro on the nVidia website yields no results. Given these expectations, I insisted on a try-and-buy contract, which are not default in Switzerland (as opposed to the EU). My fears proved right, it wasn t long until I encountered the first problems with nVidia s crap: the network chip is unable to deal with segmentation offloading for larger packets, e.g. those with IPv6 payload in a bridging context, and generic segmentation offloading has to be turned off on the interface:
ethtool -K eth0 gso off

This fixes the issue, and so I stuffed it into /etc/network/interfaces and decided to keep the machine, especially after having invested the time into the server to figure out how to work the watchdog and the IPMI card. The folks behind Transtec s support hotline are helpful, but it took me a bit of time to get the information I wanted out of them. At least they deemed it perfectly natural that I wanted to run Debian, and never questioned that. Let s document some of the more internal specs here for posterity: The BIOS gives the impression of two separate watchdogs, one on the IPMI card (a SIMSO+) and one on the mainboard itself (a SuperMicro H8DMU+). Transtec told me that SuperMicro disabled the IPMI watchdog (called BMC watchdog in the BIOS) with firmware 1.29, leaving only the one on the motherboard. It took a bit of time to find out that this was a W83627THF and supported by the w83627hf_wdt driver, which I configured with module options timeout=120 nowayout=1. I left the BIOS setting at disabled since that would otherwise interfere with booting e.g. the awesome grml live system by rebooting the machine after the set amount of time. It also took a bit of time to get SOL working with the IPMI card. In the end, I found it to work best by configuring the console redirection in the BIOS to use COM2 with 38400/n/8, using hardware flow control, redirection-after-POST always, and vt100 emulation ANSI and vt-utf8 emulation were horrific. I instructed the bootloader to pass console=tty0 console=ttyS1,38400n8 to the kernel (order matters), and configured agetty in /etc/inittab like this:
T0:2345:respawn:/sbin/getty -8hL ttyS1 38400n8 vt100

To guard against the worst, I also left a grml CD in the drive, to be able to boot a rescue system via SOL in case everything else was broken. The following kernel boot parameters enable me to use the rescue system via IPMI:
vga=normal noeject noprompt console=tty0 console=ttyS1,38400n8 forensic

Michael Prokop of the grml project tried to create a customised ISO image with these options for me, but I kept getting medium errors trying to read it, independent of the burner, CD-writing-software, operating system used to burn, medium, and drive used to read, so it s possible that the ISO image is faulty. Michael used the following command line to create it (supporting files are here):
grml-live -t ~/templates-madduck -c GRMLBASE,GRML_MEDIUM,AMD64 -o \
  /grml-live/grml64-medium_2008.11-madduck -a amd64 -s sid -v \
  2008.11-madduck -g grml64-medium -r Schluchtenscheisser -V -b

Until we figure out the problem with this, the grml64 0.2 CD in the drive will do. The machine is now operational, but the IPv6 prefix I have still arrives at vera.madduck.net, a Xen-Instance hosted by Init Seven, which I will no longer need, once I find the time to migrate all the services it hosts. NP: This Will Destroy You: Young Mountain

27 November 2008

Russell Coker: Links November 2008

Netatia has an interesting series of articles about running a computer for two people [1]. It is a bit of a kludge, they have a single X server that covers both displays and then use Xephyr to divide it into two virtual screens. The positive aspecct of this is that it shuld allow a single wide monitor to be used by two sessions as displays are getting wider regardless of the wishes of manufacturers and consumers [2] this should be useful. It’s a pity that no-one has solved the problem of having multiple video cards, sound cards, and input devices to allow a single desktop system to be used for 6 or more people. It seems that the problems that need to be solved are only the support for multiple video cards, mouse-wheel support, and sound support. Paul Ewald gave an interesting TED talk about changing the conditions for diseases so that they evolve to be benign [3]. The first example is Cholera which if spread by water will benefit from being as toxic as possible (to cause the greatest amount of diorrhea - killing the host not being a problem), but if spread by human contact benefits from leaving it’s host well enough to walk around and meet people. This and the other examples he cites seem like strong reasons for universal health-care provided by the government. If clean water is provided to all the poor people then cholera will evolve to be less harmful, and if a rich person (such as myself) is unlucky enough to catch it then the results won’t be so bad. He also notes that less harmful bacteria will often result in the victim not seeking anti-biotics and therefore less pressure for the disease to evolve resistance to anti-biotics. Therefore the people who really need them (the elderly, the very young, and people who are already sick) will find them to be more effective. Paul Stamets gave a great TED talk about fungus [4]. One of his discoveries was that fungi can be used for breaking down petro-chemicals (they can eat oil). It would be interesting to see this tested on a large scale with one of the oil spils or with the polluted land around an ooil refinery. Also he has patented a method for using fungus to kill wood-eating ants (such as the ones that briefly infested his home). Robert Full gave an interesting TED talk on robot feet [5]. I found the bit about leg spikes particularly interesting (I had always wondered why insects have spikey legs). Alan Kay gave a very interesting presentation on using computers to teach young children about science [6]. An OLPC is referenced. It makes me want to buy an OLPC for everyone I know who has young children. The start of the talk is a little slow. Dan Barber gave a very interesting TED talk about organic and humane production of foie gras in Extramuda [7]. Apparently it tastes a lot better too. Incidentally I don’t list all the TED talks I watch, only the better ones. Less than half the TED talks that I see announced seem interesting enough to download, and of those less than half are good enough that I will recommend them. The ones that I don’t recommend don’t suck in any way, it’s just that I can’t write a paragraph about every talk. Of recent times my video watching has been divided about equally between “The Bill” and TED talks. Here’s an interesting article about Sarah Palin and “anti-elitism”: The prospects of a Palin administration are far more frightening, in fact, than those of a Palin Institute for Pediatric Neurosurgery. Ask yourself: how has “elitism” become a bad word in American politics? There is simply no other walk of life in which extraordinary talent and rigorous training are denigrated. We want elite pilots to fly our planes, elite troops to undertake our most critical missions, elite athletes to represent us in competition and elite scientists to devote the most productive years of their lives to curing our diseases. And yet, when it comes time to vest people with even greater responsibilities, we consider it a virtue to shun any and all standards of excellence. When it comes to choosing the people whose thoughts and actions will decide the fates of millions, then we suddenly want someone just like us, someone fit to have a beer with, someone down-to-earth in fact, almost anyone, provided that he or she doesn’t seem too intelligent or well educated.[8] Sarah will be representing the Republican party in 2012, the desire for leaders of average intelligence (or less) will still be around then. It will be interesting to see how many votes she gets and amusing to see her interviewed. The proceedings of the “Old Bailey” - London’s Central Criminal Court have been published [9]. It’s interesting to read some of the historical information about the legal system at the time. It made me appreciate how civilised the UK (and other countries that I have visited) are now. Bruce Schneier writes about the feture of ephemeral communication [10]. He concludes with the point “until we have a Presidential election where both candidates have a complete history on social networking sites from before they were teenagers we aren’t fully an information age society“. Of course as he notes the rules are written by the older people, currently I don’t think that any candidate for high office (cabinet minister or above) anywhere in the world can have a good history on the Internet. During the course of a decade or more on the net it’s impossible not to write something that can be used against you and no reasonable person could avoid changing their views on some issues in such a time period. That’s enough to lose an election with the way things currently work.

26 November 2008

Steve Kemp: Have you been following that man?

meta-hacking I've had a lot of fun over the past few years detecting and fixing XSS attacks - a few months ago compromising several thousand user-accounts belonging to a particular niche social networking site and then more recently experimenting with XSS issues upon a popular software developer's advocate blog. One thing I've been wondering about recently is meta-XSS attacks. Consider the LKML (linux kernel mailing list). This list receives lots of long patches, submitted by email, which are copied verbatum to various sites. For example if I mailed an interesting patch to LKML chances are it would get posted to: (Obviously the challenge here is to make a patch sufficiently interesting that it received more than usual coverage.) Do each of those sites HTML-encode patches? In general they do, certainly the ones I looked at had code like this:
#include &lt;linux.h&gt;
...
...
But I'm certain that not all sites do so. I'm also pretty sure there are interesting avenues to explore here, and the general idea of indirectly attacking a specific target is ripe for exploration. Anyway I'm probably not the person to go playing in the field these days; I don't have the time. But it is certainly interesting to think about. ObFilm: Dirty Harry

Russell Coker: Bill Joy

Some time ago Bill Joy (who is famous among other things for being a co-founder of Sun) [1] wrote an article for Wired magazine titled “Why the future doesn’t need us” [2]. He wrote many sensible things but unfortunately focussed on the negative issues and didn’t receive a good response. On reading it today I thought more highly of the article than I did in 2000 when it was printed, largely due to having done some background research on the topic. I’ve recently been reading Accelerating Future [3] which has a more positive approach. Now a talk by Bill Joy from 2006 has been published on the TED.com web site [4]. He starts by talking about “super empowered individuals” re-creating the 1918 flu. He also claims that “more technology super-empowers people more“. Such claims seem to be excessively hyped, I would be interested to see comments from someone who has a good knowledge of current bio-technology as to the merits of those claims. He talks briefly about politics and has some good points such as “the bargain that gives us civilisation is the bargain to not use power” and “we can’t give up the rule of law to fight an asymmetric threat - which is what we seem to be doing“. He mentions Moore’s law and suggests that a computer costing $1000 then (2006) might cost $10 in 2020. He seems to be forgetting the cost of the keyboard and other mechanical parts. I can imagine a high-end CPU which cost about $800 a couple of years ago being replaced by a $2 CPU in 2020, but I don’t expect a decent keyboard to be that cheap any time before we get fully automated nano-factories (which is an entirely separate issue). Even the PSU (which has a significant amount of government regulations for safety reasons) will have a floor cost that is a good portion of $10. Incidentally the keyboard on my EeePC 701 sucks badly, I guess I’m spoiled by the series of Thinkpad keyboards that I keep getting under warranty (which would cost me a moderate amount of money if I had to pay every time I wore one out). I will make a specific prediction, that by 2015 one of the better keyboards will comprise a significant portion of the entire cost of a computer system (more than a low end computer unit) - such that in some reasonable configurations the keyboard will be the most expensive part. It would be good if PCs could be designed to use external PSUs (such as the Compaq Evo models that took laptop PSUs). Then the PSU, keyboard, and monitor would be optional extras thus giving a small base price. Given that well built PSUs and keyboards tend not to wear out as fast as people want to replace computers, it seems that financial savings could be provided to most customers by allowing them to purchase the computer unit without the extra parts. People like me who type enough to regularly wear out keyboards and who keep using computers for more than 5 years because they still work are in a small minority and would of course be able to buy the same bundle of computer, PSU, and keyboard that new users would get. In 2020 a device the size of an iPaQ H39xx with USB (for keyboard and mouse) and the new DisplayPort [5] digital display interface (that is used in recent Lenovo laptops [6]) would make a great PDA/desktop. You could dock a PDA the way some people dock laptops now and carry all your data around with you. Bill cites an example of running the Mac interface on an Apple ][ (does anyone know of a reference for this) as an example of older hardware being more effective with newer software. It's a pity that often new software needs such powerful hardware. EG it's only recently that hardware developments have overtaken the developments of OpenOffice to make it deliver decent performance. He has an interesting idea of using insurance companies to replace government regulation of food and drugs. The general concept is that if you can convince an insurance company that your new drug is not a great risk to them so that they charge a premium you can afford then you could sell it without any further testing. Normally I'm in favor of government regulation of such things, but given the abject failures of the US government this idea has some merit. Of course there's nothing stopping insurance companies from just taking a chance and running up debts that they could never hope to repay (in a similar manner to so many banks). Finally I think it's interesting to note the camera work that the TED people used. My experience of being in the audience for many lectures (including one of Bill Joy's lectures in the late 90's) is that a speaker who consults their notes as often as Bill does gives a negative impression to the audience. Note that I'm not criticising Bill in this regard, often a great talk requires some significant notes - very few people can deliver a talk in a convincing manner entirely from memory. It seems to me that the choices of camera angle are designed to give a better impression than someone who was seated in the audience might receive - there's no reason why a video of a talk should be spoiled by seeing the top of the speaker's head while they consult their notes!

David Pashley: Vim Syntax Highlighting for Puppet

I've just set up syntax highlighting for Puppet manifest files, and thought I'd share the simple steps. The first thing to do is download the syntax file from http://www.reductivelabs.com/downloads/puppet/puppet.vim and save this to ~/.vim/syntax/puppet.vim. Now when the filetype is set to "puppet", vim will use this syntax file. That's useful, it it would be even nicer if we could make vim know that files ending in .pp were puppet files. Turns out this is very easy to do. You need to create a file to detect the correct filetype when you open a file. You need to put the following lines in ~/.vim/ftdetect/puppet.vim:
au BufRead,BufNewFile *.pp   setfiletype puppet
Now when you load a file ending in .pp, you should get nice syntax highlighting. You can also make vim use special settings for the puppet filetype by creating a vim script file in one of ~/.vim/ftplugin/puppet.vim, ~/.vim/ftplugin/puppet_*.vim and/or ~/.vim/ftplugin/puppet/*.vim. Vim has a lot of flexible hooks to enable file type specific configuration; hopefully it should be fairly easy to modify these examples for other file formats.
Read Comments (0)

25 November 2008

Ian Wienand: Position Independent Code and x86-64 libraries

If you've ever tried to link non-position independent code into a shared library on x86-64, you should have seen a fairly cryptic error about invalid relocations and missing symbols. Hopefully this will clear it up a little! Let's start with a small program to illustrate.
$ cat function.c
int global = 100;
int function(int i)  
	return i + global;
 
$ gcc -c function.c
Firstly, inspect the disassembley of this function:
0000000000000000 <function>:
   0:	55                   	push   %rbp
   1:	48 89 e5             	mov    %rsp,%rbp
   4:	89 7d fc             	mov    %edi,-0x4(%rbp)
   7:	8b 05 00 00 00 00    	mov    0x0(%rip),%eax        # d <function+0xd>
   d:	03 45 fc             	add    -0x4(%rbp),%eax
  10:	c9                   	leaveq
  11:	c3                   	retq
Lets just go through that for clarity: The IP relative move is really the trick here. We know from the code that it has to move the value of the global variable here. The zero value is simply a place holder - the compiler currently does not determine the address (i.e. how far away from the instruction pointer the memory holding the global variable is. It leaves behind a relocation -- a note that says to the linker "you should determine the correct address of foo, and then patch this address of the code to point to that addresss (i.e. foo)." Relocations with addend The image above gives some idea of how it works. We can examine relocations with the readelf tool.
$ readelf --relocs ./function.o
Relocation section '.rela.text' at offset 0x518 contains 1 entries:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
000000000009  000800000002 R_X86_64_PC32     0000000000000000 global + fffffffffffffffc
If you try and build a shared object (dynamic library) with this function, you should get something like
$ gcc -shared function.c
/usr/bin/ld: /tmp/ccQ2ttcT.o: relocation R_X86_64_32 against  a local symbol' can not be used when making a shared object; recompile with -fPIC
/tmp/ccQ2ttcT.o: could not read symbols: Bad value
collect2: ld returned 1 exit status
Position Independent Code (PIC, enabled with -fPIC) just means that the output binary does not expect to be loaded at a particular base address, but is happy being put anywhere in memory (compare the output of readelf --segments on a binary such as /bin/ls to that of any shared library). This is obviously critical for implementing shared-libraries, where you may have many, many libraries loaded in essentially any order, and trying to pre-allocate where in memory they would all live just does not work. However, PIC has slightly wider implications than simply movable base addresses. So, back to relocations. The exact rules for different relocation types are described in the ABI for the architecture. The R_X86_64_PC32 relocation is defined as "the base of the section the symbol is within, plus the symbol value, plus the addend". The addend makes it look more tricky than it is; remember that when an instruction is executing the instruction pointer points to the next instruction to be executed. Therefore, to correctly find the data relative to the instruction pointer, we need to subtract the extra. This can be seen more clearly when layed out in a linear fashion (as in the bottom of the above diagram). What's the problem with this in a shared library? In a shared library situation, we can not depend on the local value of global actually being the one we want. Consider the following example, where we override the value of global with a LD_PRELOAD library.
$ cat function.c
int global = 100;
int function(int i)  
	return i + global;
 
$ gcc -fPIC -shared -o libfunction.so function.c
$ cat preload.c
int global = 200;
$ gcc -shared preload.c -o libpreload.so
$ cat program.c
#include <stdio.h>
int function(int i);
int main(void)  
   printf("%d\n", function(10));
 
$ gcc -L. -lfunction program.c -o program
$ LD_LIBRARY_PATH=. ./program
110
$ LD_PRELOAD=libpreload.so LD_LIBRARY_PATH=. ./program
210
If the code in libfunction.so has a fixed offset into its own data section, it will not be able to see the overridden value provided by libpreload.so. This is not the case when building a stand-alone executable, where references are satisfied internally. Of course, any problem in computer science can be solved with a layer of abstraction, and that is what is done when compiling with -fPIC. To examine this case, let's see what happens with PIC turned on.
$ gcc -fPIC -shared -c  function.c
$ objdump --disassemble ./function.o
./function.o:     file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <function>:
   0:	55                   	push   %rbp
   1:	48 89 e5             	mov    %rsp,%rbp
   4:	89 7d fc             	mov    %edi,-0x4(%rbp)
   7:	48 8b 05 00 00 00 00 	mov    0x0(%rip),%rax        # e <function+0xe>
   e:	8b 00                	mov    (%rax),%eax
  10:	03 45 fc             	add    -0x4(%rbp),%eax
  13:	c9                   	leaveq
  14:	c3                   	retq
It's almost the same! We setup the frame pointer with the first two instructions as before. We push the first argument into memory in the pre-allocated "red-zone" as before. Then, however, we do an IP relative load of an address into rax. Next we de-reference this into eax (e.g. eax = *rax in C) before adding the incoming argument to it and returning.
$ readelf --relocs ./function.o
Relocation section '.rela.text' at offset 0x550 contains 1 entries:
  Offset          Info           Type           Sym. Value    Sym. Name + Addend
00000000000a  000800000009 R_X86_64_GOTPCREL 0000000000000000 global + fffffffffffffffc
The magic here is again in the relocations. Notice this time we have a P_X86_64_GOTPCREL relocation. This says "replace the data at offset 0xa with the global offset table (GOT) entry of global. Global Offset Table operation with data variables As shown above, the GOT ensures the abstraction required so symbols can be diverted as expected. Each entry is essentially a pointer to the real data (hence the extra dereference in the code above). Since the GOT is at a fixed offset from the program code, it can use an IP relative address to gain access to the table entries. This extra reference is obviously slower; however for the most part I imagine the overhead would be essentially immeasurable and is required for "generic" operation. If you have figured the cost of indirection through the GOT is the major bottleneck of your program, I imagine you wouldn't be reading this and would already be considering strategies to remove it! The next question is why this works on plain old x86-32. Inspecting the code reveals why:
$ objdump --disassemble ./function.o
00000000 <function>:
   0:	55                   	push   %ebp
   1:	89 e5                	mov    %esp,%ebp
   3:	a1 00 00 00 00       	mov    0x0,%eax
   8:	03 45 08             	add    0x8(%ebp),%eax
   b:	5d                   	pop    %ebp
   c:	c3                   	ret
$ readelf --relocs ./function.o
Relocation section '.rel.text' at offset 0x2ec contains 1 entries:
 Offset     Info    Type            Sym.Value  Sym. Name
00000004  00000701 R_386_32          00000000   global
We start out the same, with the first two instructions setting up the frame pointer. However, next we load a memory value into eax -- as we can see from the relocation information, the address of global. Next we add the incoming argument from the stack (0x8(%ebp)) to the value in this memory location; implicitly dereferencing it. This provides the abstraction we need -- if the relocation makes the patched address at 0x4 the address of the GOT entry, it will be correctly dereferenced. It is the inability of the x86-32 architecture to try and optimise by doing instruction-pointer relative offseting which means it always needs to do slower memory references, which turns out to be just what you want when you're making a shared library! So, the executive summary: the ability of x86-64 to use instruction-pointer relative offsetting to data addresses is a nice optimisation, but in a shared-library situation assumptions about the relative location of data are invalid and can not be used. In this case, access to global data (i.e. anything that might be changed around on you) must go through a layer of abstraction, namely the global offset table.

Neil Williams: Unexpected functionality

Following from unexpected results, I can't make up my mind why Gtk+ supports rotated labels.
Try it, load Glade3, create any normal Gtk window and add or select a standard GtkLabel, add some text. In the properties of the label, there is a spin button for Angle:. Why is that? Which applications have need for this? I can't think of any examples that I've seen in Debian. Does anybody use rotated labels?
I could possibly understand rotations in increments of 90 degrees but this supports rotation at an precision of two decimal places! I mean, why support a rotation of 89.27 degrees?
Even if this was a version of a progress bar, why is it supported for every GtkLabel anywhere?
Weird.
P.S. Off to Extremadura tomorrow, hopefully I'll have a chance to get a better hackergochi too.

Russell Coker: SE Linux and Decrypted Data

There is currently a discussion on the Debian-security mailing list about how to protect data which came from an encrypted file. I was going to skip that one until someone summoned me by mentioning SE Linux. The issue which was raised is that data from an encrypted file can be read from /dev/mem (for all memory of the machine) or /proc/<pid>/mem (for the memory of the process). It was suggested that SE Linux can prevent such attacks, however it’s not that simple. In most SE Linux configurations there will be a domain with ultimate privileges, examples are unconfined_t for a default configuration (also known as targeted) and sysadm_t for a “strict” configuration. SE Linux differs from many security models (such as the Unix permissions model that we are familiar with) in that there is no inherent requirement for a domain with ultimate privileges. I have in the past written policy for machines in which no domain could read /dev/mem or modify the running policy. This meant that booting from installation media might be required to modify the configuration of the system - some people desire systems like this and have good reasons for doing so! As the vast majority of SE Linux users will have a “targeted” configuration, and the majority of the rest will have a “strict” configuration with minimal changes (IE sysadm_t will work as expected) there will always be a domain that can access /dev/mem (I’m not certain that sysadm_t can directly access /dev/mem on all variants of the policy - but given that it can put SE Linux in permissive mode it has ultimate access to work around that). This however doesn’t mean that SE Linux provides no benefit. A typical Linux system will have many daemons running as root, while a typical SE Linux system will have few processes running as root while also having a SE Linux context that grants ultimate privileges. The root owned processes that SE Linux constrains are generally the network facing daemons and other processes which provide a risk, while the root owned processes that are not constrained by SE Linux policy are generally processes related to early stages of the system boot and programs run as part of the system administrator’s login session - processes that are inherently trusted. Now regarding the memory of the process (and the ptrace API), in most cases a process that is likely to be accessing such a file will run in a domain that permits such access to itself. If the process in question is run from a login session (ssh login etc) then other processes in the same session will have access to the data. It is quite possible to write policy to create a new domain for the program which accesses the decrypted data and to deny the domain the ability to ptrace itself, but it will require at least 10 minutes of work (it’s not a default configuration). So while SE Linux will generally help you to improve your security no matter what your exact requirements may be, it’s not something that can be used to make such corner cases entirely disappear. In a more general sense the idea that only a single program can access certain data is almost unattainable in a typical system. Among other things to consider is the fact that the Linux kernel is one of the larger programs on a typical Linux system…

24 November 2008

Michael Schutte: Recently loved

Simon McVittie: Why you shouldn't block on D-Bus calls

I've found myself writing this several times recently in the context of Telepathy, so I thought I'd make a blog post that I can refer people to. D-Bus is defined (by the wire protocol spec) to be an asynchronous message-passing system, and libdbus behaves accordingly; there are no blocking calls at the wire protocol level. However, libdbus provides a "blocking" API (dbus_do_something_and_block), via a mechanism I'll refer to as "pseudo-blocking" for the purposes of this post. Most D-Bus bindings (at least dbus-glib, dbus-python and QtDBus) expose this pseudo-blocking behaviour to library users. These pseudo-blocking calls work like this: The messages received between M and R are delivered when the main loop is next entered. This can cause a number of problems: As a result, telepathy-glib's code generation mechanism does not generate any pseudo-blocking code. There are several alternative modes of operation that we do support: We make a couple of narrowly targeted exceptions to the "no pseudo-blocking" policy in internal code, by allowing telepathy-glib internals to make a small number of pseudo-blocking method calls to the dbus-daemon (which is the one component we can definitely trust to return results promptly). Here are some examples of the same strategies in other libraries:

Josselin Mouette: The great return of the broomsticks

While a few developers have the chance to be paid for their job on Debian, most of us are doing it on our spare time, for fun. Yes, we are making the best operating system out there, for fun. Yet a large number of developers are taking this project way too seriously. To say it in other words, they have a carrot up the ass. I happen to prefer the French expression though, since it conveys better the rigidity of their attitude: they have a broomstick up the ass. Recently, when I launched the idea of the Bug Sprint, someone wrote to me to propose, instead of rewarding people with cookies, to send them money. This is the best example of broomstick behavior: taking the fun out of people by bringing back rampantly the very idea that almost split the project in two the last time it was introduced. The very same person, when faced with a sarcastic email sent to an announcement mailing list, immediately rushed in to send a ban request to list masters (a totally useless one, since I don t have the habit to make the same joke twice). That person happens to be the project leader. So it seems the only thing the DPL has to do, at a time when we d rather need people to fix RC bugs, is to protect the project from seditious members who don t share their love for broomsticks. When someone makes a bad-taste joke, you are not forced to laugh. But you are not forced to impose your rigid and moralist views either. And on top of that, throwing random accusations of sexism without any kind of justification does not improve the mood. This is even very close to defamation, but since I don t have a broomstick in the ass myself, I prefer to just laugh at them with the help of some fellow developers. I will go on shocking these people. And they won t like it more than in the past. Every time one of them climbs on her high horse to take a pathetic and patronizing stance while totally missing the point, it will bring a bit of fun. Bonus #1: as for the promised statistics, we are, at the time of writing, at 493 599 unique IPs who clicked on the trap. Quite a good investment for someone who d want to make money from smelly geeks. Bonus #2: here is a sexist picture.

23 November 2008

Wouter Verhelst: Music is Math

Gintautas Miliauskas blogs about a computer program that can generate something which reportedly really sounds like composer-written music; apparently it has passed a 'turing test' where people listened to music generated by this thing, and music written by a human composer. I'm afraid, however, I'll have to disappoint him a bit, really. If we ignore the effect that music can have on the emotional state of a living being for a moment, then it's a plain and simple fact that music is pure math: There are many other things in music that can be expressed as mathematical rules; learning to how to compose music involves learning those rules, which is a long and tedious process. Now I'm not saying that following those rules will necessarily lead you to an interesting piece of music; the fact that it's possible to create something ugly while still using chords etc. But since so much of it already is math, I can imagine it not being extremely hard to figure out what the other rules are (the ones a composer figures out by imself as opposed to being taught them), transferring them into a computer program, and using that to generate music. That's not to say that such a thing is easy to do, and I'm sure it's still an impressive feat to create a computer program which can create "nice" sounding music; but I don't think this would qualify as 'artificial intelligence'. At least not any more than Deep Blue

Next.

Previous.