Feeds:
Posts
Comments

Posts Tagged ‘linux’

Esses dias assinei um plano 3G da Vivo. Chegando em casa, comecei a usar a conexão 3G ao invés do ADSL que tenho aqui para testar o serviço. Foi meio broxante quando depois de um tempo de uso (1 hora talvez? não sei) a conexão ficou extremamente lenta, com pings de 30 segundos ou mais (o recorde foi 200 segundos!). Lá vou eu, ligar pro suporte da Vivo no mesmo dia em que assinei o serviço. A 1ª impressão foi pro ralo.

Interessante que o menu do telefone já classifica o usuário por sistema operacional:

Se você usa um computador com Windows, tecle 1.
Se você usa um computador com Mac OS, tecle 2.
Se você usa um computador com Linux, tecle 3.

Legal, eles reconhecem que existem clientes que usam Linux! Teclei 3. A experiência não foi lá tão boa, mas isso não surpreendeu. Obviamente o suporte da Vivo coloca sempre a culpa no seu equipamento e o problema nunca é na rede deles, então pedem pra fazer trocentos procedimentos de configuração e teste antes de cogitarem que eles têm que fazer algo do lado deles.

Mas isso é outra história. O interessante foi o procedimento que ele pediu pra eu fazer. Em primeiro lugar, pediu para abrir um terminal e digitar:

$ sudo echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6

Imagine o tempo que levou pra soletrar tudo isso. :-)

A 1ª coisa que salta aos olhos é que o comando tem um erro típico de quem não manja muito de Linux (quem eles contrataram pra elaborar os procedimentos de Linux deles?!?): o comando “echo 1″ rodará como usuário root, mas a parte do “> blah” é feita pelo shell do usuário, portanto vai dar erro de permissão na hora de escrever no disable_ipv6.

Mais impressionante que isso, o atendente pediu pra eu digitar a parte do “$␣”, ou seja ele soletrou “Cifrão, espaço, s, u, d, o, …”.

FacePalm

Quando terminei de digitar o comando (fazendo as alterações necessárias) e apertei enter, ele perguntou se apareceu “Operação bem sucedida”.

NOT-SURE-IF-A-TROLL-OR-JUST-STUPID

Eu expliquei pra ele que quando não aparece nada é porque o comando deu certo então seguimos adiante. A próxima coisa que eu tinha que fazer era reiniciar o computador. Wait wat? Todo esse trabalho soletrando um comando gigante pra editar uma variável no /proc e ele quer que eu reinicie?

mr-bean-irritado

Pra quem não usa ou não manja de Linux (o que não tem problema nenhum, e é até saudável, a menos que você trabalhe com suporte técnico): as alterações no /proc são “efêmeras” e na próxima vez em que o computador é ligado volta tudo como estava antes.

O lado bom da história é que a Vivo suporta Linux. Os atendentes também são surpreendentemente prestativos. Quando o procedimento acima não funcionou (quem diria?), eu fiquei discutindo com o cara outras possibilidades, ele deu algumas sugestões genéricas, inclusive uma que ajudou bastante: o problema talvez fosse que o modem muda de 3G (HSUPA) para 2G (EDGE), e aí fica lento. Passei a reparar nisso e realmente é o que acontece.

Já estou fugindo do assunto mas resumidamente, em outra ligação a atendente mencionou que é possível forçar o modem a ficar só no 3G, e isso poderia resolver o problema. O procedimento que ela tinha era só pro Windows infelizmente mas tá valendo, entrei no Windows. Só que meu modem é da Claro e o “discador” que veio nele também, e ele é ligeiramente diferente do da Vivo. Apesar disso ela ficou um tempão tentando me ajudar, tentando mapear o procedimento que ela tinha pra interface do meu discador. No fim achei a opção e realmente resolveu o problema!

Agora, por que o modem muda pra EDGE? Isso ninguém soube explicar, e ainda não consegui convencer a Vivo a fazer uma revisão na rede dela aqui no meu bairro…

Read Full Post »

I have been meaning to write this post for a long time.

One thing which I often found myself doing was typing echo $? after running a command to find out if there was any error, or appending || echo failed to the end of the command line.

Commands generally warn if there was an error, but you have to stop for a second and carefully read the output to see whether anything went wrong. I’m lazy and that additional second and the extra cognitive effort always bothered me.

I eventually had the idea of making the shell prompt show the exit status of the last command if it was non-zero. I use zsh, so it’s got to be possible. :-)

It turns out it is, this is my PS1 variable now:

CYAN="%{"$'33[00;36m'"%}"
RED="%{"$'33[01;31m'"%}"
NORM="%{"$'33[00m'"%}"

export PS1="${CYAN}%m${NORM}%# %(?..${RED}(%?%)${NORM} )"

The magical part is %(?..${RED}(%?%)${NORM} ). Here’s the result:

zsh prompt

As a side note, one other thing that the screenshot shows is the right-hand prompt. This is a great feature of zsh, and I use it to show the current working directory. That way, no matter where I am in the filesystem, the cursor prompt always starts at the same column. Here’s my RPS1 variable:

MAGENTA="%{"$'33[00;35m'"%}"

export RPS1="${MAGENTA}%~${NORM}"

Read Full Post »

Converting from Ogg Vorbis to MP3 in Amarok

Since version 2.6, you can tell Amarok to convert (transcode) every music track to MP3 when copying it to a given device.

There’s a bug, however which causes MP3 files converted from Ogg Vorbis to lose all metadata (artist, album, title etc). This is a showstopper for me.

This happens because Amarok needs to pass an option to ffmpeg to tell it to get the metadata from the first stream found in the Ogg file as opposed to the default of getting it from global metadata. Unfortunately as far as I can tell there’s no way to configure the ffmpeg command line used by Amarok. The solution then is to replace the ffmpeg binary in the path with a script that will do that, like this one:

#!/usr/bin/python
import os
import sys

AVCONV_FFMPEG = '/usr/bin/ffmpeg.distrib'
os.execv(AVCONV_FFMPEG, sys.argv + ['-map_metadata', '0:0,s0'])

In Debian or Ubuntu, you can divert the real ffmpeg binary and install the script above as /usr/bin/ffmpeg:

$ sudo dpkg-divert --add /usr/bin/ffmpeg
$ sudo cp /tmp/fake-ffmpeg.py /usr/bin/ffmpeg
$ sudo chmod +x /usr/bin/ffmpeg

There’s another bug where Amarok needlessly converts even MP3 files when copying them to the device.

Read Full Post »

Ok, so this time I won’t talk about Python scripting support in GDB. I’m getting tired of it myself. :-) I’ll just comment that it’s amazing the number of problems people in IRC report with GDB that can be solved with the Python support that we’re adding to it. Sometimes they need stuff which is only on the branch, but sometimes even the few bits already in CVS HEAD are enough!

Er, I actually do have one more thing to say about the subject: GDB had one project accepted in the Google Summer of Code 2009. Oguz Kayral is the student working on it, and I am his mentor. He will add support for subscribing to inferior events (e.g., signals, process and thread stops, thread creation) from Python. One use case for which this is useful was given by an IRC user at the #gdb channel:

<LimCore> how to run gdb from command line, so that it will run ./foo.bin with arguments: foo bar baz and it will run it instantly without waiting for ‘r’; And if program segfaults then it will do ‘bt’ without waiting for the command. (and if program terminates normally then it will also just quit)

LimCore will be able to write a simple and short Python script using the events API to solve his problem.

Now, moving on to other items: my team has been asked to improve GDB support for the hardware debug facilities in embedded PowerPC processors (for more info about these facilities, see Chapter 10 of Book III-E of the Power ISA v2.06). I announced this work to the GDB mailing list back in early March, and got useful insight from Joel Brobecker.

Today I posted an update on where we are with this work. We have the following ready for both native GDB and gdbserver on Linux:

  • one additional hardware watchpoint (two in total),
  • four hardware breakpoints,
  • one ranged hardware watchpoint.

And we still have the following features ahead of us:

  • support for the two DVC (Data Value Compare) registers, which enable hardware-accelerated conditions for hardware watchpoints,
  • two ranged hardware breakpoints.

Last and least, I was thinking of posting monthly GDB updates on what happened in GDB in the previous month as I did back in February, but I got busy and didn’t get around to it. I still entertain the idea though, so if you think it’s worth it, I’d be glad to know.

Read Full Post »

It’s been a while since I last talked about Python scripting support in GDB. Mostly because I’ve been focusing on getting stuff from the branch merged into CVS HEAD, so that GDB 7.0 can have some useful Python bindings.

The latest two patches committed upstream are for creating convenience functions in Python, and fo manipulating a program’s stack frames as Python objects. So, what can you do with those? I’ll borrow an example from Tom Tromey here: suppose you want to set a breakpoint which triggers only when the code is called by one specific function. You can create a convenience function like this:

import gdb
import re

class CallerIs (gdb.Function):
    """Return True if the calling function's name is equal to a string.
This function takes one or two arguments.
The first argument is the name of a function; if the calling function's
name is equal to this argument, this function returns True.
The optional second argument tells this function how many stack frames
to traverse to find the calling function.  The default is 1."""

    def __init__ (self):
        super (CallerIs, self).__init__ ("caller_is")

    def invoke (self, name, nframes = 1):
        frame = gdb.selected_frame ()
        while nframes > 0:
            frame = frame.older ()
            nframes = nframes - 1
        return frame.name () == name.string ()

CallerIs ()

And then create a conditional breakpoint using it, as in:

(gdb) break foo.c:42 if $caller_is ("some_function")

Or, to check the name of the grand-grand-caller of the code:

(gdb) break foo.c:42 if $caller_is ("some_function", 3)

Cool, huh? Now, why bother writing that big doc comment? GDB will use it as online help for the function you wrote:

(gdb) help function caller_is
Return True if the calling function's name is equal to a string.
This function takes one or two arguments.
The first argument is the name of a function; if the calling function's
name is equal to this argument, this function returns True.
The optional second argument tells this function how many stack frames
to traverse to find the calling function.  The default is 1.

One other patch which was merged in HEAD enables creating new GDB commands in Python, so you can write new commands to do some frame tricks too!

If you’d like to know more about the Python scripting work in GDB, I suggest you read the series of blog posts from Tom Tromey on this subject. It’ll give you a pretty good idea of what we have in the Python branch, and the direction we’re heading. Just keep in mind that some method names and syntax changed since he wrote that. Refer to the GDB manual in the Python branch (“make gdb.pdf” in gdb/doc/) or the example scripts (also in the Python branch, in gdb/python/lib/gdb/) for up-to-date details.

Read Full Post »

resolvendo nomes na rede de casa

Desde que eu tenho dois notebooks em casa eu senti a necessidade de ter resolução de nomes funcionando decentemente para eles, ao invés de ter que ficar vendo qual IP o roteador designou para cada notebook cada vez que preciso acessar um ou outro computador. Primeiro pensei em fixar um IP baseado no endereço MAC, mas meu roteador não tem essa funcionalidade. Depois fiquei imaginando se não existia algum servidor DNS pra uso doméstico que pode ter suas entradas atualizadas dinamica e automaticamente.

Qual não foi minha surpresa quando descobri que a solução pro meu problema não só já existe, como não exige configuração nenhuma e além disso já estava instalada e funcionando nos dois computadores! Chama-se Multicast DNS (mDNS), e faz parte de um conjunto de tecnologias de “zero configuration networking”, da qual o Apple Bonjour faz parte. No Linux, o serviço que implementa isso é o Avahi.

Para usá-lo no caso que eu tinha em mente (basicamente, ssh e scp) basta usar o hostname do computador a ser acessado e acrescentar a extensão .local. Exemplo:

hotblack% ssh hactar.local
hactar% ping hotblack.local
PING hotblack.local (192.168.1.2) 56(84) bytes of data.
64 bytes from hotblack.local (192.168.1.2): icmp_seq=1 ttl=64 time=0.328 ms

Ótimo!

Eu já tinha ouvido falar de Zeroconf e do Avahi, claro. Mas eu achava que era só para descoberta de serviços na rede (coisa que nunca precisei, pelo menos por enquanto (mas acho a idéia bem legal)), não sabia que integrava com DNS!

Read Full Post »

news from GDB-land

Nick Clifton publishes in his blog monthly news from the toolchain world, which is very interesting and very nice of him. Unfortunately he has not been able to provide news from GDB-land. I compiled a list of interesting events which happened in the GDB community this February to post as a comment in his blog, and figured it could be useful to post it here as well:

This is an incomplete list (doesn’t mention bugfixes, for instance) hacked up in the wee hours of the night, while waiting for sleep to come. If you are a GDB hacker who committed something interesting this month, I apologize in advance for not listing it here.

Read Full Post »

One annoying aspect of scripting GDB (using it’s own scripting language), is that if you test or set a variable which is not in scope, the script will generate an error and GDB will give up evaluating it. It would be useful to have a way to programatically check if the variable is in scope before trying to use it. There was even at least one try (from the brave Rob Quill) at implementing such a thing posted to the gdb-patches mailing list, but unfortunately as of now it still has some issues and haven’t been committed (I believe this patch is the latest version).

Anyway, this is the kind of thing we want to make easy to do in Python, so I decided to try to implement a solution using what we have in the Python branch. Tom Tromey already created the notion of convenience functions, which are functions that are implemented by GDB  that you can call in places where it accepts expressions, and he made it possible to implement such functions in Python. It follows that one can write a in_scope convenience function in Python which checks if a given variable name is valid in the current scope of the debugged program.

There were some missing pieces which I had to implement to get the in_scope function working (most notably, a method to get a string from a variable in the debugged program), and in the past few days I committed to the branch the patches which add those pieces. So now you can have the following script:

class InScope (gdb.Function):
    """Check if all the given variables or macros are in scope.
       Receives as argument a list of names separated by
       whitespace."""

    def __init__ (self):
        super (InScope, self).__init__ ("in_scope")

    def invoke (self, var):
        vars = set (var.string().split())
        found = set ()
        pc = gdb.get_selected_frame ().get_pc ()
        block = gdb.get_block_for_pc (pc)
        while block:
            for sym in block:
                if (sym.is_argument ()
                      or sym.is_constant ()
                      or sym.is_function ()
                      or sym.is_variable ()):
                    sym_name = sym.get_print_name ()
                    if sym_name in vars:
                        found.add (sym_name)
            block = block.get_superblock ()

        return vars == found

InScope ()

And use it like this:

Breakpoint 1, main (argc=1, argv=0x7fffffffe208) at /tmp/funcs.c:16
16        int i = 41;
(gdb) if $in_scope("i")
 >print "yay"
 >else
 >print "nay"
 >end
$1 = "yay"
(gdb)

If you save the script to ~/.gdb-in-scope.py, you can put the following in your ~/.gdbinit to load it automatically:

source ~/.gdb-in-scope.py

Now my goal is to cut out and submit upstream a set of patches to make the above work on regular GDB. The only problem is that I have the boring task of writing testcases and documentation for the code before I can submit it… :-)

For now, If you want to use this script you can build a GDB from the branch, but be aware that the Python API as provided in the branch is subject to change.

Read Full Post »

It’s been a great while since I last posted about Python scripting in GDB, mostly because I’ve been busy coding the feature and getting it ready for upstream.

First of all, I’d like to take the opportunity to encourage people interested in using this feature to experiment with what we have implemented so far. The reason is that if you still can’t do what you want with the current code in the Python branch, we’d love to hear what you miss and implement it. We are working on what is useful for ourselves, and trying to decide what other people would find useful. But it’s not possible to imagine everything that people want to use this for, or even most things. Please refer to this wiki page to learn what currently works, what we plan to implement, and how to grab the code from the Python branch.

Feel free to write to the GDB mailing list or show up in the #gdb IRC channel at Freenode to discuss this work and/or bring your use case to our attention, so that we can support it. I hope that with enough input from prospective users we can ship something that’s immediately useful for most people, and avoid having to jump through hoops later and have to shoehorn something that we forgot to cater for initially, risking breaking scripts out there or ending up with an inconsistent API.

Anyway, back to business: I have just committed the second patch in the Python series! It exports GDB’s value subsystem to Python scripts. Basically, GDB values are objects which represent data in the inferior (GDB jargon for the program being debugged), holding its address in the inferior’s addressspace, its type and so on. See the “Python API” section in the GDB manual if you want to learn more about it (yes, we are even writing documentation for the feature!).

I committed the first patch back in August, but I didn’t mention it here because it didn’t do anything the user would find useful, really. It was just groundwork for the rest (autoconf and Makefile.in changes, a ‘python’ command in GDB which basically does nothing useful, initial documentation…). Still, it was about 1500 lines long (not counting the patch’s context)! This shows how much work it is to integrate Python support in GDB. I almost regret having joined this effort. :-)

The second patch also doesn’t allow the user to do anything useful yet, unfortunately. But it is noteworthy because it is a base upon which a lot of other Python support code depend upon. Also, it’s the first committed patch which actually exposes something from GDB to Python. It took a while to get this code ready for two reasons: one was that there was a long discussion regarding how the syntax of acessing struct/union/class elements. The other was that implementing the Value class involved playing with little-documented aspects of Python’s C interface, and it took me time to discover how to do what I needed.

Now my next step is to choose the next patch from the Python series to submit upstream, and get it ready for posting (i.e., fix FIXMEs, add testcases and documentation). This brings me to another thing I’d like to mention. Back in April when I first prepared the Python patch series, I naively thought that after cutting them out, it was just a matter of posting them, iterate through a few review/rework steps and they’d be committed. Simple enough. But here we are in mid-October and just two from nine patches went in (now it’s more like 15 patches in total)! What happened?

The problem is that we’ve been working in the branch in an experimental and exploratory way, just hacking together enough to get something useful done. This was necessary because we didn’t know exactly what we would want to expose from GDB to Python, and how we wanted to do that. As we progressed and discussed the results, things started to become clear. The problem is that now we have a lot to clean up, voids to fill, and above all documentation and testcases to write. This takes time.

At least, that was the problem with the first two patches. I noticed Tom Tromey started to write more documentation and tie more loose ends than in the beginning (me? I’ve just been working on the first two patches until they were ready. Didn’t write sexy new stuff since then…), so there’s hope that the next patches will be easier to work with. We still lack a lot of tests for the testsuite, though…

Read Full Post »

que iPhone/iPod o que…

… eu quero é um Neo FreeRunner!

Pra que me prender a um celular/PDA no qual eu não posso instalar os programas que eu quiser, e que eu não posso fuçar pra tentar fazer funcionar do jeito que é mais útil pra mim (olá, supporte a ogg :-) )?

O N810 também é uma boa opção (eu tentei comprar um já, mas não achei pra vender na época), se você ignorar o fato de que ele não é um telefone. Pra mim não é uma limitação séria, já tenho um de 200 reaus (isso na época, hoje não vale nem dez…) que faz e recebe chamadas.

Read Full Post »

Older Posts »

Follow

Get every new post delivered to your Inbox.

Join 349 other followers