Blog

  • How to open java coredump in gdb

    2023-12-28 15:47:57.094437

    After dozen of experiments I finally come to next action sequence with gdb as the most universal/reliable one.

    Good case we have access to client libraries

    1. Check gdb version. it should be 6.x the later the better.
    2. Create directory D inside you working one
    3. Create D/gdbrc file with *full* path to your directory
      set solib-absolute-prefix /home/dms/Sept12/12_09_2008_20_00_node4/D 
      

      Notice: set substitute-path doesn't work because gdb apply it to source files only

    4. symlink apropriate D/java
    5. run
         gdb -x D/gdbrc D/java core
      
    6. type
          info shared
      

    You will see something like:

    (gdb) info shared
    From        To          Syms Read   Shared Object Library
                            No          /lib/tls/libpthread.so.0
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    0x00a05bb0  0x00a068c4  Yes /home/dms/Sept12/D/lib/libdl.so.2
    ...
    0x008c9c00  0x009b9800  Yes /home/dms/Sept12/D/lib/tls/libc.so.6
                            No          /lib/libnsl.so.1
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
    1. leave gdb and copy or link missed library under D.

    In my case:

    D/lib/tls/lib/tls/libpthread.so.0
    D/lib/libnsl.so.1
    
    

    To gather all libraries necessary to open a coredump on other machine run:

     gdb -batch --eval "info shared"  D/java core 2> /dev/null |\
     sed -n -e 's/^.*Yes[^\/]*\//\//p' -e 's/^.*No[^\/]*\//\//p'  > filelist
    

    on your own machine and than:

     cat filelist | zip zipme.zip -@
    

    on client one

    Bad case - we don't have access to original libraries. We still can restore JVM part of stack trace manually.

    To do it:

    1. Run some java app (e.g. Java2Demo.jar) with exactly the same version of jdk and JVM part of command line.
    2. Kill it by kill -BUS to get a core.
    3. Open core with gdb and check whether upper part of stack trace match customer's one -
    #0  0xffffe424 in __kernel_vsyscall ()
    #1  0xb76f96e0 in raise () from /lib/libc.so.6
    #2  0xb76faf15 in abort () from /lib/libc.so.6
    #3  0xb70abbaf in os::abort(bool)
    #4  0xb71de555 in VMError::report_and_die()
    #5  0xb70b257c in JVM_handle_linux_signal ()
    #6  0xb70ae7a4 in signalHandler(int, siginfo*, void*) ()
    #7  <signal handler called>
    

    Ever without symbols - you should have exactly 6 entries before <> and os::abort is right the next after libc abort.

    • Type info shared and get addresses where jvm is loaded:
      0xb6bf2bd0  0xb71fe250  Yes (*)  /opt/jdk1.6.0_18/jre/lib/i386/server/libjvm.so
      
    • Calculate offset of os:abort : 0xb70abbaf - 0xb6bf2bd0 = 0x4b8fdf
    • Calculate jvm size: 0xb71fe250 - 0xb6bf2bd0 = 0x60b680
    • Go to cu core and calculate jvm start and end addresses
      <os::abort> - 0x4b8fdf = N, N + 0x60b680
      

    *Calculate offset between your JVM and cu JVM

      <os::abort> - 0xb70abbaf (os:abort from my core, or compare two JVM starts)
    
    • Get stacktrace offset, check whether it within range. apply difference
    • Go to your coredump and type
    info address <recalcualted_address>
    


  • Thinkpad 420 WiFi and Bluetooth issue

    2023-12-28 15:44:32.134245

    If you installed windows 10 on old Thinkpad T420 and you realize that neither bluetooth nor wifi are working properly (windows reports that it is turned off and can't turn it on) >do following:

    • 1. Make sure that small switch located on the right side of laptop right after the CD bay is turned on (green is shown, knob is under computer icon)
    • 2. Make sure that wifi and bluetooth access is enabled in the BIOS, check Security::I/O Ports section.
    • 3. Make sure that Fn and CRL buttons is not swapped in BISO, check Config::Keyboard section
    • 4. Go to the Device Manager and check that Intel Centrino adapter is present, update it's driver  - let autoupdate find appropriate one
    • 5. Install  Thinkpad Hotkey Features Integration software from http://support.lenovo.com including all aditional utilities, like on-screen menu
    • 6. Reboot you PC
    • 7. Press Fn + F5 and enable Bluetooth and WiFi

    You should be able to use WiFi/Bluetooth now.


  • Some thoughts about WFH

    2023-12-28 15:44:20.823026

    1. WFH involves a slightly different relationship with working time - a working day has no beginning and no end, but load is distributed across more freely. That is, if the vast majority of people in the office work from 10 to 19, then on WFH we often can see something like: "I work from 11 to 15 while my wife looks over the child and then from 20 to 24 while the child sleeps". Such distribution of time might be mandatory, especially in the current situation of forced WFH.
     
    2. WFH, especially in combination with quarantine measures such as the closure of fitness, very quickly lead to the lack of communication and feeling of loneliness. In many cases, an employee compensates for this with increased activity in personal chats/groups and increased time spent reading these chats. Moreover, a typical office pattern: "raise the head; make sure that a colleague is on his desk; ask a question; get an answer" is replaced by "writing in a chat; waiting for an answer".
     
    3. WFH leads to fast growing distance from the team. As kitchen communication, joint lunch, etc. are lost, the employee quickly loses the sense of team and project, despite the daily scrum and other ceremonies. The pattern like "pick up the task from the air" or "help a stuck teammate in between of own tasks" is lost.
     
    4. WFH job mainly attract people of a certain nature, often with some hard life circumstances, or contribute to the development of specific character traits, so you have to be very careful getting into the personal space of such people (happy birthday, pulling out on the team events and so on).
     
    A few tips to deal with problems mentioned above:
     
    1. Decrease the number of communication channels for developers. In some cases it is better to kill all chats altogether and move all communication to email.
     
    2. Set some rather narrow intervals within a working day for chatting. At this time and only at this time, you can ask a question and expect an immediate answer. At any other time, the developer should not rush to answer immediately, but wait for a natural pause in the work. This agreement should be explained loudly to all team members, managers and developers.
     
    3. Keep sending across the project digest (once or twice a week - depends on the intensity of the project), with the main non-technical events in the project and high-level plans for the next interval.
     
    4. Ask developers to update their tasks daily and to put the task to correct status as soon as possible. In addition, more efforts should be made to develop DOD and to make tasks more atomic and clear. Checklists are useful here.
     
     


  • How to extract Mac OS xip archive

    2023-12-28 15:44:09.390468

    xip is an old archive format used to distribute XCode.  it's actually an xar format but with ability to be signed. If you installing the same software multiple times and don't want to spend time to verify known to be valid signature, instead of xip -x do the following (you can use xar -x -f instead of bsdtar xvf):

    bsdtar xvf Archive.xip

    ditto -x Content .

     

     


  • Executing jcmd programmatically

    2023-12-28 15:43:56.405177

    It's often convenient to run jcmd command programmatically from within a testcase to get some information or to adjust options.

    See the template below:

    // import javax.management.ObjectName;
    // import javax.management.MBeanServer;
    
     public static void reloadCompilerDirectives(String filename) {
        String result;
        result = doRunDcmd("compilerDirectivesClear", new String[]{""});
        result = doRunDcmd("compilerDirectivesAdd", new String[]{ filename });
      }
    
      private static String doRunDcmd(String operationName, String operationArgs[]) {
          ObjectName objectName = 
              new ObjectName("com.sun.management:type=DiagnosticCommand");
          MBeanServer mbeanServer = 
              ManagementFactory.getPlatformMBeanServer();
          Object[] params = new Object[] { operationArgs };
          String[] signature = new String[]{ String[].class.getName() };
          return(String) mbeanServer.invoke(objectName, operationName, params, signature);
      }
    
    
    
    


  • Print the code emitted by Hotspot assembler

    2023-12-28 15:43:47.352285

    It's not always obvious what assembly will be generated after expanding all the macros of the HotSpot meta-assembly system. The following code shows how to print the actual code generated by HotSpot.

    // #define DMS_DEBUG
    #ifdef DMS_DEBUG
    address barrier_start = masm->code()->insts_end();
    #endif
     __ block_comment("nmethod_barrier begin");
     __ ldr_label(tmp0, guard);
    ...
     __ bind(skip);
     __ block_comment("nmethod_barrier end"); 
    
    #ifdef DMS_DEBUG 
    address barrier_end = masm->code()->insts_end(); 
    tty->print_cr("DMS: barier %p %p bytes: %d", barrier_start, barrier_end, barrier_end - barrier_start); 
    
    //  masm->code()->print(); 
    masm->code()->decode(); 
    #endif
    
    


  • Conditional Syslog from within the HotSpot

    2023-12-28 15:43:35.110007

    The following code shows how to organize debug printing with minimal impact on the loaded system

    #include <syslog.h>
    #include <stdarg.h>
    #include <stdlib.h>
    
    static void print_at(const char *srcfile, int line, const char *format, ...) {
      va_list ap;
      const char *envvar="JAVA_SHOULD_PRINT_AT";
      static int requested_line = -1;
    
      if (requested_line == -1) {
        const char *should_print = getenv(envvar);
        requested_line = (should_print != NULL) ? atoi(should_print) : 0;
        openlog("javadebug", LOG_PID, LOG_UUCP);
      }
    
      if (requested_line == line) {
         va_start(ap, format);
         vsyslog(LOG_DEBUG, format, ap);
         va_end(ap);
      }
    }
    


  • Силовая подготовка каратиста

    2023-12-28 15:40:52.604179

    Железу отвожу четыре дня, которые спариваю (штабс-капитан молчать) по два. На одну тренировку уходит вместе с разминкой и заминкой не больше полутора часов. Вес подбирается так, чтобы последний раз выполнялся через не могу. Заминка состоит из растягивания работавших мышц и расслаблении позвоночника.

    От Лица Павла Клопова.

    См Библиотека Ратника


    В первый пробиваю грудь и трицепс.

    • Жим штанги на горизонтальной доске широким хватом пирамида (взрывом)
    • Ворона 12х4 (ускорением)
    • Жим гантелей на наклонной скамье (35 градусов) 12х4 (взрывом)
    • Разгибание рук на верхнем блоке 12х4 (плавно)
    • Французкий жим лёжа 12х4 (ускорением)
    • Разводка рук в локтях к низу на верхнем блоке 12х4 (медленно)

    На следующий день пробиваю плечи и трапеции

    • Шраги за спиной пирамидой (взрывом)
    • Тяга штанги к подбородку 12х4 (плавно)
    • Жим гантелей сидя 12х4 (взрывом)
    • Подъём гантелей через стороны 12х4 (взрывом)
    • Подъём гантелей вперёд 12х4 (взрывом)
    • Разводка гантелей в наклоне 12х4 (взрывом)

    Два дня отдыха и новая спарка

    В первый день спина, бицепс

    • Крест пирамидой (плавно)
    • Тяга верхнего блока к груди 10х4 (плавно)
    • Тяга гантели одной рукой в наклоне 10х3 (взрывом)
    • Гребля 12х4 (плавно)
    • Подъём гантелей на бицепс с супинацией 12х4 (быстро)
    • Трисет на бицепс со штангой 10-10-10х3 (плавно)
    • Молоток сидя 12х4 (быстро)

    Следующий день уделяю ногам

    • Разгибания ног в станке 12х4 (взрывом)
    • Жим тележки пирамидой (взрывом)
    • Румынская становая тяга 8х3 (плавно)
    • Сгибания ног в станке 12х4 (взрывом)
    • Подъём на мыски сидя в станке 12х4 (взрывом)
    • Подъём мысков со штангой на пальцах 12х4 (плавно)

    Между упражнениями кручу минуту велотренажёр, для не потери скорости и силы удара работаю по мешкам и макиваре, но развожу их по разным дням с железом. Раз в квартал дёргаю резинки и мучаюсь с утяжелителями.

    ... посему назову рабочие.

    • Жимы на грудь в зависимости от упражнения от 120 до 150 кг.
    • Подъёмы гантелей для плеч (через стороны, вперёд и в наклоне) от 20 до 25 кг.
    • Шраги от 120 кг
    • Бицепс гантели 20 - 25 (трисет естейственно меньше).
    • тяга к подбородку 60 - 65 кг.
    • Тяга гантели одной рукой в наклоне (на спину) 55-65
    • Французкий жим лёжа 50-60


  • ffmpeg tips

    2023-12-28 15:37:08.077720

     

    dv => mpeg2 

    dvgrab capture_20060604.dv
    ffmpeg -i capture_20060604.dv  -target pal-dvd capture_20060604.mpeg
    

    more ... http://womble.decadent.org.uk/talks/dvd-ukuug06/dvd-talk-ukuug06-paper.html

    mkv => avi: change container 

    /opt/mplayer/bin/mencoder infile.mkv -oac copy -ovc copy -o outfile.avi
    

    or using mkvtoolnix

    1. MKV is a container, to see what the file contains:
    $ mkvinfo movie.mkv
    
    |+ Segment tracks
    | + Track number: 1
    ^^^^^^^^^^^^^^^
    + Track type: video
    ^^^^^^^^^^^^^^^^
    
    1. select the numbers of the trucks you want to extract and type:
      $ mkvextract tracks "/mnt/common/Film/movie.mkv" 1:/mnt/common/Film/video.h264 2:/mnt/common/Film/audio.aac
      
    1. Let's put all toghether:
    $ mencoder -audiofile video.aac -oac copy -ovc copy audio.h264 [-of mpeg]  -o movie_complete.mpg
    

    or

    $ ffmpeg -i video.h264 -i audio.aac -map 0.0:0 -map 1.0:0 -acodec copy -vcodec copy -r 23.976 -f vob video.mpg


  • Про налоги

    2023-12-28 15:28:45.463688

    Я очень надеюсь, что для тех кто думает, что в России зарплатные налоги составляют 43%, в аду приготовлен отдельный котел.

    Если у вашего работника оклад 100р, то вы, как работодатель, платите 30р во всякие фонды, а работник, в свою очередь, платит 13р НДФЛ. Итого, ваш ФОТ - 130р, сумма на руки - 87р. Общая налоговая нагрузка (Налоги к ФОТ) - 33.1%.

    Также обратите внимание что:
    (a) Есть предельная величина базы, 1 917 000р, после которой взносы уменьшаются до 15.1% и общая налоговая нагрузка до 24.4%.
    (б) Для организаций на ОСН, ФОТ уходит из базы налога на прибыль (20%). Т.е. если бы организация не платила зарплату, она бы со 130р прибыли отдала 26р налога.

    * Цифры даны по состоянию на 2023 год

    Еще одна группа деятелей, которая заслуживает отдельного котла - те, кто приходят с утверждением: "всякий раз, когда вы достаете из кармана кошелек, вы платите НДС".

    И дело тут не в том, что можно придумать десяток схем, при которых НДС не возникает (дедушка собрал грибы в лесу и продал их на рынке). А в том, что нет прямого переноса НДС на стоимость товара. Даже в том случае, когда НДС указан отдельной строкой в чеке, вы не можете количественно оценить влияние НДС (и других косвенных налогов) на общую стоимость покупаемого товара. Цена товара с 10% НДС и товара с 20% НДС не будет отличаться ровно на 10%, т. к. на цену товара в первую очередь влияют другие факторы.

    Поэтому учитывать НДС (и другие косвенные налоги) в общей налоговой нагрузке на физлицо бессмысленно как с экономической так и с практической точки зрения.