Desarrollo del kernel -- ampo con kernel camp codereview Relacionados El problema

Kernel development


4
vote

problema

Español

Estoy tratando de aprender más sobre los núcleos, por lo que, naturalmente, comencé a programar uno. Estoy usando tutoriales de aquí . En este momento he modificado el #! /usr/bin/env perl use feature qw(say); use strict; use warnings; my $old_str = '$1B<$ <hello> $> aba B<$ <kk> $>$1'; my $str = $old_str; my $regex = qr'B<$ <(.*?)> $>'; my $replace = 'I<$1$1$1>'; (my $cnt, $str) = substitute_regex_backref( $str, $regex, $replace ); say "Old string: '$old_str'"; say "Number of replacements: $cnt"; say "New string: '$str'"; exit; # # # ($num_substitutions, $new_str) = # substitute_regex_backref( $str, $regex, $replace ) # # # This sub routine is based on a stackoverflow.com answer # by username Kent Fredric, see http://stackoverflow.com/a/392649/2173773 # # Replace all occurences of $regex in $str with $replace. # Returns number of replacements and the new string. # # The $regex input is assumed to be a regex quoted string. For example: # my $regex = qr/A simple (w+) example/; # # The replacement string $replace is allowed to have backreferences: # Example: $replace = "a $1 b" # "$1" is here treated as a backreference. It corresponds to capture group number 1 # in the $regex string. # # The replacement string $replace can also have backslash escaped dollar signs, # Example: $replace = "$1 a $1 b" # Such escaped dollar signs should be replaced by # a literal '$' (and not treated as a backreference) # Note: This subroutine was written to avoid using the ee modifier technique: # $var =~ s/$find/$replace/ee; # which has sequrity risks if the $replace string comes from user input. # sub substitute_regex_backref { my ( $str, $regex, $replace ) = @_; # First obtain an array @m of matches my @m = $str =~ /$regex/g; if (@m == 0) { return (0, $str); } my $special_character_seq = "x41x42x43x44"; # Remove any dollar signs from $str $str =~ s/$/$special_character_seq/g; # If $regex contain escaped dollar signs (to be treated as # literal dollar signs), we need to replace # them with $special_character_seq since we have removed all # dollar signs in the previous line $regex =~ s/\$/$special_character_seq/g; # Do the replacement, but dollar signs in the $replace variable # are left as literal dollar signs $str =~ s/$regex/$replace/g; # Replace backslash escaped dollar signs with special string $str =~ s/\$/$special_character_seq/g; # use "reverse" function to cope with mixed one- and two-digit back references # For example, $12 should be dealt with before $1, in order to avoid confusion. for( reverse 0 .. $#m ){ my $n = $_ + 1; my $val = $m[$_]; # Replace "$n" with the value of capture group $str =~ s/$$n/$val/g; } # Reinsert all literal dollar signs: $str =~ s/$special_character_seq/$/g ; return (@m + 0, $str); } 4 que se suministró allí. Se utiliza #! /usr/bin/env perl use feature qw(say); use strict; use warnings; my $old_str = '$1B<$ <hello> $> aba B<$ <kk> $>$1'; my $str = $old_str; my $regex = qr'B<$ <(.*?)> $>'; my $replace = 'I<$1$1$1>'; (my $cnt, $str) = substitute_regex_backref( $str, $regex, $replace ); say "Old string: '$old_str'"; say "Number of replacements: $cnt"; say "New string: '$str'"; exit; # # # ($num_substitutions, $new_str) = # substitute_regex_backref( $str, $regex, $replace ) # # # This sub routine is based on a stackoverflow.com answer # by username Kent Fredric, see http://stackoverflow.com/a/392649/2173773 # # Replace all occurences of $regex in $str with $replace. # Returns number of replacements and the new string. # # The $regex input is assumed to be a regex quoted string. For example: # my $regex = qr/A simple (w+) example/; # # The replacement string $replace is allowed to have backreferences: # Example: $replace = "a $1 b" # "$1" is here treated as a backreference. It corresponds to capture group number 1 # in the $regex string. # # The replacement string $replace can also have backslash escaped dollar signs, # Example: $replace = "$1 a $1 b" # Such escaped dollar signs should be replaced by # a literal '$' (and not treated as a backreference) # Note: This subroutine was written to avoid using the ee modifier technique: # $var =~ s/$find/$replace/ee; # which has sequrity risks if the $replace string comes from user input. # sub substitute_regex_backref { my ( $str, $regex, $replace ) = @_; # First obtain an array @m of matches my @m = $str =~ /$regex/g; if (@m == 0) { return (0, $str); } my $special_character_seq = "x41x42x43x44"; # Remove any dollar signs from $str $str =~ s/$/$special_character_seq/g; # If $regex contain escaped dollar signs (to be treated as # literal dollar signs), we need to replace # them with $special_character_seq since we have removed all # dollar signs in the previous line $regex =~ s/\$/$special_character_seq/g; # Do the replacement, but dollar signs in the $replace variable # are left as literal dollar signs $str =~ s/$regex/$replace/g; # Replace backslash escaped dollar signs with special string $str =~ s/\$/$special_character_seq/g; # use "reverse" function to cope with mixed one- and two-digit back references # For example, $12 should be dealt with before $1, in order to avoid confusion. for( reverse 0 .. $#m ){ my $n = $_ + 1; my $val = $m[$_]; # Replace "$n" with the value of capture group $str =~ s/$$n/$val/g; } # Reinsert all literal dollar signs: $str =~ s/$special_character_seq/$/g ; return (@m + 0, $str); } 5 y no me gustó eso.

¿Puede alguien ver algo malo con este código? Funcionó bien cuando lo probé.

  #! /usr/bin/env perl  use feature qw(say); use strict; use warnings;  my $old_str = '$1B<$ <hello> $> aba B<$ <kk> $>$1'; my $str = $old_str; my $regex = qr'B<$ <(.*?)> $>'; my $replace = 'I<$1$1$1>';  (my $cnt, $str) = substitute_regex_backref( $str, $regex, $replace );  say "Old string: '$old_str'"; say "Number of replacements: $cnt"; say "New string: '$str'";  exit;  # # # ($num_substitutions, $new_str) = #     substitute_regex_backref( $str, $regex, $replace ) # # # This sub routine is based on a stackoverflow.com answer # by username Kent Fredric, see http://stackoverflow.com/a/392649/2173773 # # Replace all occurences of $regex in $str with $replace. # Returns number of replacements and the new string. # # The $regex input is assumed to be a regex quoted string. For example: #  my $regex = qr/A simple (w+) example/; # # The replacement string $replace is allowed to have backreferences: #   Example: $replace = "a $1 b" # "$1" is here treated as a backreference. It corresponds to capture group number 1 # in the $regex string. # # The replacement string $replace can also have backslash escaped dollar signs, #  Example:  $replace = "$1 a $1 b"  # Such escaped dollar signs should be replaced by #  a literal '$' (and not treated as a backreference)   # Note: This subroutine was written to avoid using the ee modifier technique: #   $var =~ s/$find/$replace/ee; # which has sequrity risks if the $replace string comes from user input. # sub substitute_regex_backref {     my ( $str, $regex, $replace ) = @_;      # First obtain an array @m of matches     my @m = $str =~ /$regex/g;     if (@m == 0) {         return (0, $str);     }     my $special_character_seq = "x41x42x43x44";      # Remove any dollar signs from $str     $str =~ s/$/$special_character_seq/g;      # If $regex contain escaped dollar signs (to be treated as     # literal dollar signs), we need to replace     # them with $special_character_seq since we have removed all     # dollar signs in the previous line     $regex =~ s/\$/$special_character_seq/g;      # Do the replacement, but dollar signs in the $replace variable     # are left as literal dollar signs      $str =~ s/$regex/$replace/g;      # Replace backslash escaped dollar signs with special string     $str =~ s/\$/$special_character_seq/g;      # use "reverse" function to cope with mixed one- and two-digit back references     # For example, $12 should be dealt with before $1, in order to avoid confusion.     for( reverse 0 .. $#m ){          my $n = $_ + 1;         my $val = $m[$_];          # Replace "$n" with the value of capture group         $str =~ s/$$n/$val/g;         }         # Reinsert all literal dollar signs:         $str =~ s/$special_character_seq/$/g ;     return (@m + 0, $str);  } 6  

y #! /usr/bin/env perl use feature qw(say); use strict; use warnings; my $old_str = '$1B<$ <hello> $> aba B<$ <kk> $>$1'; my $str = $old_str; my $regex = qr'B<$ <(.*?)> $>'; my $replace = 'I<$1$1$1>'; (my $cnt, $str) = substitute_regex_backref( $str, $regex, $replace ); say "Old string: '$old_str'"; say "Number of replacements: $cnt"; say "New string: '$str'"; exit; # # # ($num_substitutions, $new_str) = # substitute_regex_backref( $str, $regex, $replace ) # # # This sub routine is based on a stackoverflow.com answer # by username Kent Fredric, see http://stackoverflow.com/a/392649/2173773 # # Replace all occurences of $regex in $str with $replace. # Returns number of replacements and the new string. # # The $regex input is assumed to be a regex quoted string. For example: # my $regex = qr/A simple (w+) example/; # # The replacement string $replace is allowed to have backreferences: # Example: $replace = "a $1 b" # "$1" is here treated as a backreference. It corresponds to capture group number 1 # in the $regex string. # # The replacement string $replace can also have backslash escaped dollar signs, # Example: $replace = "$1 a $1 b" # Such escaped dollar signs should be replaced by # a literal '$' (and not treated as a backreference) # Note: This subroutine was written to avoid using the ee modifier technique: # $var =~ s/$find/$replace/ee; # which has sequrity risks if the $replace string comes from user input. # sub substitute_regex_backref { my ( $str, $regex, $replace ) = @_; # First obtain an array @m of matches my @m = $str =~ /$regex/g; if (@m == 0) { return (0, $str); } my $special_character_seq = "x41x42x43x44"; # Remove any dollar signs from $str $str =~ s/$/$special_character_seq/g; # If $regex contain escaped dollar signs (to be treated as # literal dollar signs), we need to replace # them with $special_character_seq since we have removed all # dollar signs in the previous line $regex =~ s/\$/$special_character_seq/g; # Do the replacement, but dollar signs in the $replace variable # are left as literal dollar signs $str =~ s/$regex/$replace/g; # Replace backslash escaped dollar signs with special string $str =~ s/\$/$special_character_seq/g; # use "reverse" function to cope with mixed one- and two-digit back references # For example, $12 should be dealt with before $1, in order to avoid confusion. for( reverse 0 .. $#m ){ my $n = $_ + 1; my $val = $m[$_]; # Replace "$n" with the value of capture group $str =~ s/$$n/$val/g; } # Reinsert all literal dollar signs: $str =~ s/$special_character_seq/$/g ; return (@m + 0, $str); } 7 , izquierda completamente no modificada:

  #! /usr/bin/env perl  use feature qw(say); use strict; use warnings;  my $old_str = '$1B<$ <hello> $> aba B<$ <kk> $>$1'; my $str = $old_str; my $regex = qr'B<$ <(.*?)> $>'; my $replace = 'I<$1$1$1>';  (my $cnt, $str) = substitute_regex_backref( $str, $regex, $replace );  say "Old string: '$old_str'"; say "Number of replacements: $cnt"; say "New string: '$str'";  exit;  # # # ($num_substitutions, $new_str) = #     substitute_regex_backref( $str, $regex, $replace ) # # # This sub routine is based on a stackoverflow.com answer # by username Kent Fredric, see http://stackoverflow.com/a/392649/2173773 # # Replace all occurences of $regex in $str with $replace. # Returns number of replacements and the new string. # # The $regex input is assumed to be a regex quoted string. For example: #  my $regex = qr/A simple (w+) example/; # # The replacement string $replace is allowed to have backreferences: #   Example: $replace = "a $1 b" # "$1" is here treated as a backreference. It corresponds to capture group number 1 # in the $regex string. # # The replacement string $replace can also have backslash escaped dollar signs, #  Example:  $replace = "$1 a $1 b"  # Such escaped dollar signs should be replaced by #  a literal '$' (and not treated as a backreference)   # Note: This subroutine was written to avoid using the ee modifier technique: #   $var =~ s/$find/$replace/ee; # which has sequrity risks if the $replace string comes from user input. # sub substitute_regex_backref {     my ( $str, $regex, $replace ) = @_;      # First obtain an array @m of matches     my @m = $str =~ /$regex/g;     if (@m == 0) {         return (0, $str);     }     my $special_character_seq = "x41x42x43x44";      # Remove any dollar signs from $str     $str =~ s/$/$special_character_seq/g;      # If $regex contain escaped dollar signs (to be treated as     # literal dollar signs), we need to replace     # them with $special_character_seq since we have removed all     # dollar signs in the previous line     $regex =~ s/\$/$special_character_seq/g;      # Do the replacement, but dollar signs in the $replace variable     # are left as literal dollar signs      $str =~ s/$regex/$replace/g;      # Replace backslash escaped dollar signs with special string     $str =~ s/\$/$special_character_seq/g;      # use "reverse" function to cope with mixed one- and two-digit back references     # For example, $12 should be dealt with before $1, in order to avoid confusion.     for( reverse 0 .. $#m ){          my $n = $_ + 1;         my $val = $m[$_];          # Replace "$n" with the value of capture group         $str =~ s/$$n/$val/g;         }         # Reinsert all literal dollar signs:         $str =~ s/$special_character_seq/$/g ;     return (@m + 0, $str);  } 8  
Original en ingles

I'm trying to learn more about kernels, so naturally I started to program one. I'm using tutorials from here. Right now I have modified the printf() that was supplied there. It used goto and I didn't like that.

Can anyone see anything wrong with this code? It worked fine when I tested it.

printf("hello %c world %c",'x','y')  int printf(const char* restrict format, ...) {    va_list parameters;    va_start(parameters, format);     int written = 0;    size_t amount;     while(*format != '\0')    {       if (*format != '%')       {     amount = 1;     while(format[amount] && format[amount] != '%') //print every character until, % is encountered.        amount++;     print(format, amount);     format += amount;            written += amount;     continue;       }       switch(*(++format)) //since format points now to %, move on step       {          case 'c':             format++;   //prepare next char         char c = (char)va_arg(parameters, int);         print(&c, sizeof(c));         written++;          break;       }    }     return written; } 

And print(), left completely unmodified:

static void print(const char* data, size_t data_length) {     for ( size_t i = 0; i < data_length; i++ )         putchar((int) ((const unsigned char*) data)[i]); } 
     

Lista de respuestas

5
 
vote
vote
La mejor respuesta
 
  • Es posible que deba documentar que esto actualmente solo funciona para la opción 99887766655443314 . Otros pueden asumir lo contrario que esto puede apoyar a todos o la mayoría de ellos. Por supuesto, no tiene que hacerlo, ya que esto es simplemente una reinvención de la rueda.

  • Asegúrese de mantener su sangría consistente. Parece que estás utilizando principalmente cuatro espacios para ello, por lo que debe hacerse en todas partes. Debe especialmente fijarlo en la declaración grande $q25 .

  • Esto se ve un poco inusual:

      $q26  

    Supongo que está haciendo esto para evitar la duplicación, pero en función de su código actual, parece que aún puede ponerlo en el cuerpo 99887766655443317 sin repetición. Tampoco tener el incremento en la declaración, también puede ayudar con la legibilidad.

  • Nunca verifica los errores, lo cual es la función estándar. Si se produce un error, debe configurar el indicador de error $q28 y luego devolver un valor negativo.

    Asegúrese de que está leyendo la documentación en esta función para ayudar a mejorar su propia.

 
  • You may need to document that this currently only works for the c option. Others may assume otherwise that this can support all or most of them. Of course, you don't have to do that since this is merely a reinvention of the wheel.

  • Make sure to keep your indentation consistent. It seems you're mostly using four spaces for it, so it should be done everywhere. You should especially fix it in the large if statement.

  • This looks a little unusual:

    switch(*(++format)) 

    I assume you're doing this to avoid duplication, but based on your current code, it looks like you can still put it in the switch body without repetition. Not having the increment in the statement itself may help with readability, too.

  • You never check for errors, which is what the standard function does. If an error occurs, you should set the error indicator ferror and then return a negative value.

    Be sure you're reading the documentation on this function to help improve your own.

 
 

Relacionados problema

2  Kernel de CUDA para comparar las entradas de matriz, ponderadas con un patrón  ( Cuda kernel to compare matrix entries weighted with a pattern ) 
Me pregunto si es posible optimizar este código en CUDA. ¿Podría obtener alguna sugerencia cómo? El algoritmo equivalente funciona más rápido en Matlab para m...

3  Char conductor simple de Linux  ( Simple linux char driver ) 
Dado que los recursos que encontré para aprender están generalmente desactualizados, tengo que leer una gran cantidad de documentación, lo que hace que el pro...

7  Home Brew Std :: String para usar con kernel  ( Homebrew stdstring for use with kernel ) 
He presionado algunas instalaciones de la biblioteca estándar, como vector, algoritmo, etc. a mi kernel, así que puedo codificar en C ++ en lugar de C. Este e...

2  Obtención de un elemento de la lista protegida contra RCU en el kernel  ( Getting an element from rcu protected list in kernel ) 
Escribí una función, read_fox_rcu() para obtener un elemento de la lista protegida por RCU en un controlador de dispositivo Linux. Something.Mutable extend...

11  Devolución de llamada en el controlador de kernel de Linux para ocultar el protocolo de bajo nivel del dispositivo  ( Callback in linux kernel driver in order to hide devices low level protocol ) 
Estoy escribiendo un controlador de kernel de Linux para LCDS HD44780 conectado a través del bus I2C. En mi último cambio, intenté desacoplar el código de baj...

4  Representación de fuente VBE BDF  ( Vbe bdf font rendering ) 
Estoy trabajando en un kernel de hobby, con gráficos y fuentes de representación. El formato de fuente es BDF. Algunos de ellos (como para Ubuntu Mono) utilic...

5  Creación de la entrada de PROCFS en Linux en el módulo Kernel  ( Creating procfs entry on linux in kernel module ) 
My Linux Kernel versión es Linux version 5.0.0-29-generic 8 Actualmente estoy aprendiendo cómo escribir módulos de kernel para Linux e implementé este ...

6  X86 Legacy Boot Loader Error Trapping  ( X86 legacy boot loader error trapping ) 
El cargador de arranque que estoy diseñando es simplemente ir a la configuración (A) Pila, (b) Registros de segmentos (C) Cuadrar el resto de la pista para el...

4  ReadwreitSerializer  ( Readwriteserializer ) 
Estoy desarrollando un kernel de C ++, y tengo la necesidad de manipular enormes estructuras de datos antes de que se ejecute el planificador de tareas, lo qu...

14  Libera un árbol binario sin usar recursión o asignación de memoria  ( Free a binary tree without using recursion or allocating memory ) 
Como dice el título, el objetivo es liberar un árbol binario sin usar la pila o la asignación de memoria. Esto fue requerido para un módulo de kernel donde l...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos