elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Entrar al Canal Oficial Telegram de elhacker.net


  Mostrar Temas
Páginas: [1] 2
1  Informática / Hardware / Intel va a sacar al mercado Haswell con el bug del USB 3.0 en: 15 Marzo 2013, 15:57 pm
Acabo de leer la noticia, aquí:
Intel no retrasará Haswell por el bug del USB 3.0, pero sí limitará su disponibilidad.


Para los que no conozcan ese fallo:

Las primeras plataformas Intel Haswell tendrán problemas con USB 3.0 y el modo S3.

Me parece increíble, que saquen un producto con ese fallo. Es decir, van a sacar unos pocos procesadores malos que los van a comprar los que no entiendan. Y luego sacarán los procesadores buenos y los que lo vayan a comprar se tragarán los defectuosos que quedaran en stock...

Lo peor va a ser el tema de los portátiles, porque el fallo del USB 3.0 sucede cuando el equipo entra en modo ahorro de energía. Y por no dar mala imagen, Intel va a sacar los procesadores en la fecha prevista... lamentable.
2  Programación / Programación General / Problema con linker script en: 4 Septiembre 2012, 13:39 pm
Hola, estoy desarrollando un Kernel y tengo un problema con los strings. El Kernel bootea desde la disquetera, carga el Stage2 y entra en modo largo, luego se inicia el Kernel en C++.

Hasta ahora, lo estaba desarrollando en Windows, usando Nasm y MinGW, pero me encontré con el problema de las cadenas y lo porté a GNU/Linux.

En Windows, mi linker script es este:

Código
  1. OUTPUT_FORMAT("pe-x86-64")
  2. ENTRY("loader")
  3. SECTIONS
  4. {
  5.    . = 0x100000;
  6.    .text :
  7.    {
  8.        code = .;
  9.        *(.text)
  10.        text_end = .;
  11.    }
  12.    .rodata :
  13.    {
  14.        rodata = text_end;
  15.        *(.rodata)
  16. *(.rdata)
  17.        rodata_end  = .;      
  18.    }    
  19.    .data :
  20.    {
  21.        data = rodata_end;
  22.        *(.data)
  23.        data_end = .;
  24.    }
  25.    .bss :  
  26.    {
  27.        bss = data_end;
  28.        *(.bss)
  29.        bss__end = .;
  30.    }
  31.    end = .;
  32. }
  33.  

Y compilo todo, con el siguiente bat:

Código:
@echo off
set nasm="tools\nasm.exe"
set bochs="C:\Program Files (x86)\Bochs-2.5.1\bochs.exe"
set fat12maker="tools\fat12maker.exe"
set ld="..\MinGW64\bin\x86_64-w64-mingw32-ld.exe"
set cpp="..\MinGW64\bin\x86_64-w64-mingw32-g++.exe"
set objcopy="..\MinGW64\bin\x86_64-w64-mingw32-objcopy.exe"
set cpp_params=-I.\Kernel\ -nostdlib -nostartfiles -nodefaultlibs -masm=intel -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin

mkdir bin\

%nasm% -fbin bootloader\Stage_1.asm -o Stage_1.bin
if NOT %ERRORLEVEL%==0 goto error

%nasm% -fbin bootloader\Stage_2.asm -o Stage_2.bin
if NOT %ERRORLEVEL%==0 goto error

%cpp% %cpp_params% -c Kernel\kernel.cpp -o bin\kernel.o
%cpp% %cpp_params% -c Kernel\Drivers\screen.cpp -o bin\screen.o
%cpp% %cpp_params% -c Kernel\string.cpp -o bin\string.o
%cpp% %cpp_params% -c Kernel\io.cpp -o bin\io.o
%cpp% %cpp_params% -c Kernel\idt.cpp -o bin\idt.o
%nasm% -f win64 Kernel\Stage_3.asm -o bin\Stage_3.o
if NOT %ERRORLEVEL%==0 goto error

%ld% -nostdlib -nodefaultlibs -T linker.ld bin\Stage_3.o bin\kernel.o bin\idt.o bin\screen.o bin\string.o bin\io.o -o Kernel.out
%objcopy% -x -g -X -S -O binary Kernel.out kernel.bin

copy /b Stage_2.bin+kernel.bin Stage_2.bin
if NOT %ERRORLEVEL%==0 goto error

%fat12maker% -b Stage_1.bin -i Stage_2.bin -o Kernel.img
%bochs% -f bochsconf

goto fin

:error
echo Se produjo un error de compilacion
exit

:fin
echo Compilacion satisfactoria
rmdir /S /Q bin\

Se ejecuta bien, pero no se muestran las cadenas que son constantes globales. No puedo hacer algo como esto:

Código
  1. const char * interrupts_exceptions[] = {
  2. "0 - Division by zero exception",
  3. "1 - Debug exception",
  4. "2 - Non maskable interrupt",
  5. "3 - Breakpoint exception",
  6. "4 - 'Into detected overflow",
  7. "5 - Out of bounds exception",
  8. "6 - Invalid opcode exception",
  9. "7 - No coprocessor exception",
  10. "8 - Double fault",
  11. "9 - Coprocessor segment overrun",
  12. "10 - Bad TSS",
  13. "11 - Segment not present",
  14. "12 - Stack fault",
  15. "13 - General protection fault",
  16. "14 - Page fault",
  17. "15 - Unknown interrupt exception",
  18. "16 - Coprocessor fault",
  19. "17 - Alignment check exception",
  20. "18 - Machine check exception",
  21. "19 - Reserved exception",
  22. "20 - Reserved exception",
  23. "21 - Reserved exception",
  24. "22 - Reserved exception",
  25. "23 - Reserved exception",
  26. "24 - Reserved exception",
  27. "25 - Reserved exception",
  28. "26 - Reserved exception",
  29. "27 - Reserved exception",
  30. "28 - Reserved exception",
  31. "29 - Reserved exception",
  32. "30 - Reserved exception"
  33. "31 - Reserved exception"};
  34.  
  35. void idt::init_idt()
  36. {
  37. idt_ptr = (idt_ptr_t*)IDT_ADDRESS;
  38. *idt_entries = (idt_entry_t*)IDT_ADDRESS;
  39.  
  40. clean_gates();
  41. screen::kprintf("Exceptions pointer: 0x%p\n", ::interrupts_exceptions);
  42. screen::kprintf("String: %s\n", ::interrupts_exceptions[0]); //<--------------------------
  43.  
  44. idt_set_gate(0, (QWORD)isr0, 0x08, 0x8E);
  45. }
  46.  

Esto es lo que muestra: http://forum.osdev.org/download/file.php?id=2342&mode=view

Estuve buscando información en http://wiki.osdev.org/Main_Page pero no consigo arreglar el problema.

El linker script de linux es este:

Código
  1. OUTPUT_FORMAT(binary)
  2. ENTRY(loader)
  3. SECTIONS
  4. {
  5.    . = 0x100000;
  6.    .text :
  7.    {
  8.        code = .;
  9.        *(.text)
  10.        text_end = .;
  11.    }
  12.    .rodata :
  13.    {
  14.        rodata = text_end;
  15.        *(.rodata)
  16.        rodata_end  = .;      
  17.    }    
  18.    .data :
  19.    {
  20.        data = rodata_end;
  21.        *(.data)
  22.        data_end = .;
  23.    }
  24.    .bss :  
  25.    {
  26.        bss = data_end;
  27.        *(.bss)
  28.        bss__end = .;
  29.    }
  30.    end = .;
  31. }
  32.  

Y el Makefile:

Código
  1. CPP = g++
  2. CPP_PARAMS = -I./Kernel/ -nostdlib -nostartfiles -nodefaultlibs -masm=intel -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin
  3. OBJECTS = Stage_3.o kernel.o screen.o string.o io.o idt.o
  4. FAT12MAKER = ./tools/fat12maker/fat12maker
  5.  
  6.  
  7. all:
  8. nasm -fbin bootloader/Stage_1.asm -o Stage_1.bin
  9. nasm -fbin bootloader/Stage_2.asm -o Stage_2.o
  10.  
  11. nasm -felf64 Kernel/Stage_3.asm -o Stage_3.o
  12. $(CPP) $(CPP_PARAMS) -c Kernel/kernel.cpp -o kernel.o
  13. $(CPP) $(CPP_PARAMS) -c Kernel/Drivers/screen.cpp -o screen.o
  14. $(CPP) $(CPP_PARAMS) -c Kernel/string.cpp -o string.o
  15. $(CPP) $(CPP_PARAMS) -c Kernel/io.cpp -o io.o
  16. $(CPP) $(CPP_PARAMS) -c Kernel/idt.cpp -o idt.o
  17.  
  18. ld -nostdlib -nodefaultlibs -T linker-linux.ld $(OBJECTS) -o Kernel.o
  19. cat Stage_2.o Kernel.o > Stage_2.bin
  20. $(FAT12MAKER) -b Stage_1.bin -i Stage_2.bin -o Kernel.img
  21. bochs -f bochsconf-linux
  22.  
  23. clean:
  24. rm *.o
  25. rm *.bin
  26.  

Pero en Linux, funciona peor. Sólo funcionan las cadenas que se declaran como variables locales:

Código
  1. extern "C" void kmain(WORD Foo, WORD Foo2)
  2. {
  3. char saludo[] = "Hello!\n";
  4. screen::clear_screen();
  5. screen::hide_cursor();
  6.  
  7. screen::kprintf("Adios\n"); //No funciona
  8. screen::kprintf(saludo); //Funciona
  9.  

Estoy muy perdido, espero que alguien pueda echarme una mano...

Saludos.
3  Programación / ASM / int 13h problema en: 21 Julio 2012, 15:40 pm
Hola, estoy escribiendo mi propio bootloader, que se carga desde una imagen FAT12 de disquete. Utilizo bochs para la virtualización.

El problema que tengo, es que no se como trabajar con el buffer que devuelve la función int 13h cuando lees unos sectores del disquete.

Código
  1. [bits 16]
  2. [ORG 0]
  3.  
  4. jmp short start
  5. nop   ; No Operation (1 byte)
  6.  
  7. OEMLabel:                     db "KERNEL  "      ; 8 characters padded with spaces
  8. BytesPerSector:                 dw 512            ; Bytes per sector
  9. SectorsPerCluster:                db 1            ; Sectors per cluster
  10. ReservedSectors:                dw 1            ; Reserved Sectors (for sector 0)
  11. NumberOfFATs:                   db 2            ; Number of FAT´s
  12. MaxRootEntries:                dw 224            ; Number of Root Entries
  13.  
  14. NumberOfSectors:                dw 2880            ; Number of sectors
  15. DeviceDescriptor:                db 0xF0            ; Device Descriptor 0xF0 => 1.44 MB floppy image
  16. SectorsPerFAT:                   dw 9            ; Sectors Per FAT
  17. SectorsPerTrack:                dw 18            ; Sectors Per Track
  18. Sides:                         dw 2            ; Sides of disk
  19. HiddenSectors:                   dd 0            ; Number of Hidden Sectors
  20. LengthOfSectors:               dd 0            ; Length of sectors
  21. DriveNo:                      db 0            ; Drive Number (0 or 1)
  22. Flags:                         db 0            ; Additional flags
  23. Signature:                      db 0x14            ; Signature, some number of 1 byte
  24. VolumeID:                     dd 0xAABBCCDD      ; Volume ID
  25. VolumeLabel:                   db "DISCO TANIS "   ; 11 characters padded with spaces
  26. FileSystem:                   db "FAT12   "      ; 8 characters padded with spaces
  27.  
  28. ;**********************************************************;
  29. ; Entry Point
  30. ; Reset the floppy disk.
  31. ; Calculate the root directory CHS address and jump to
  32. ; read_root_directory.
  33. ;**********************************************************;
  34. start:
  35.   jmp 07C0h:stage_1
  36.  
  37. stage_1:
  38.   mov ax, cs
  39.   mov ds, ax
  40.   mov es, ax
  41.  
  42.   mov si, StringMsg
  43.   call print_string
  44.  
  45.   xor ah, ah ; Ah = 0, reset function
  46.   mov dl, BYTE [DriveNo]
  47.   int 13h ; Reset Floppy Disk
  48.  
  49.   xor ax, ax
  50.  
  51.   add ax, WORD [SectorsPerFAT]
  52.   mul BYTE [NumberOfFATs]
  53.   add ax, WORD [ReservedSectors]
  54.   ; AX = (SectorsPerFAT * NumberOfFATs) + ReservedSectors
  55.  
  56.   call lba2chs
  57.  
  58.   jmp short read_root_directory
  59.  
  60. read_root_directory:
  61.   ; We have already calculated the CH = Cilynder, CL = sector and
  62.   ; DH = Head.
  63.   mov ax, 1000h
  64.   mov es, ax
  65.   mov bx, 0
  66.  
  67.   mov ah, 02h   ; Read mode
  68.   mov al, 0Fh ; Sectors to read (512 bytes each sector)
  69.   mov dl, BYTE [DriveNo]
  70.  
  71.   int 13h ;Call the interruption!
  72.   jc .root_dir_read_error
  73.  
  74.   mov si, [1000h]
  75.   mov dx, 512
  76.   call print_n
  77.  
  78.        ...
  79.  

Y la función print_n

Código
  1. ;**********************************************************;
  2. ; Print a string in screen
  3. ; SI => String pointer
  4. ; DX => Number of characters to print
  5. ;**********************************************************;
  6. print_n:
  7.   push ax
  8.   push bx
  9.   push cx
  10.  
  11.   mov ah, 0Eh
  12.  
  13.   xor cx, cx
  14.  
  15.   .loop:
  16.   mov al, [si]
  17.   int 10h
  18.   inc cx
  19.   cmp cx, dx
  20.   je short .end_loop
  21.  
  22.   inc si
  23.   jmp short .loop
  24.  
  25.   .end_loop:
  26.   pop ax
  27.   pop bx
  28.   pop cx
  29.   ret
  30.  

El problema que tengo, está aquí:

Código
  1. mov si, [1000h]
  2. mov dx, 512
  3. call print_n
  4.  

Me debería escribir en pantalla en caracteres ASCII el contenido del Root Directory, pero en vez de eso, comienza a escribirme desde el sector 0, es decir, va escribiendo la propia memoria del programa...
La función lba2chs, convierte direccionamiento LBA (Logical Block Address) a CHS (Cylinder Head Sector), y funciona bien.

Espero que me podáis ayudar.

Saludos.
4  Programación / Programación General / fat12maker en: 4 Julio 2012, 16:53 pm
Hola, cree una herramienta que permite crear imágenes de disquete con el sistema de archivos FAT12.

Muchos considerarán inútil, pero le puede ser útil a aquella gente que quiera conocer como trabaja el sistema de archivos FAT12. Esta herramienta, la programé para el Kernel que estoy desarrollando. Puedes hacer un bootloader (de 512 bytes) y esta herramienta se encarga de meterla en el sector 0 de la imagen. También permite crear imágenes de disquete sin bootloader, soporta los siguientes tipos: 2880KB, 1440 KB, 1200 KB, 720 KB, 360 KB, 320 KB, 180 KB, 160 KB.

Las imágenes generadas siguen el estándar de Microsoft y pueden ser abiertas por el Nero o el UltraISO.

El código es bastante interesante, está escrito en C, creo que está bastante bien.

Código
  1. /*
  2.  * addFileFAT12()
  3.  * Add file to our FAT12_t structure
  4. */
  5. int addFileFAT12(char * fileName, FAT12_t * fat12)
  6. {
  7. int result = 0;
  8. linked_list_t * l = NULL;
  9. directory_entry_t directoryEntry;
  10.  
  11. if (fat12 == NULL)
  12. return FAT12_INVALID_FAT12_POINTER;
  13.  
  14. if (fat12->active != 0)
  15. return FAT12_INACTIVE;
  16.  
  17. result = getDirectoryEntry(fileName, fat12, &directoryEntry);
  18. if (result == DE_OK)
  19. {
  20. fat12->list.list = fat12->list.last;
  21.  
  22. l = (linked_list_t*)malloc(sizeof(linked_list_t));
  23. if (l == NULL)
  24. return FAT12_LINKED_LIST_MALLOC_ERR;
  25.  
  26. if (fat12->list.list == NULL)
  27. fat12->list.list = l;
  28. else
  29. {
  30. fat12->list.list->next = l;
  31. fat12->list.list = fat12->list.list->next;
  32. }
  33.  
  34. fat12->list.list->directoryEntry = directoryEntry;
  35.  
  36. fat12->list.list->fileName = (char *)malloc(strlen(fileName) + 1);
  37. if (fat12->list.list->fileName == NULL)
  38. return FAT12_LINKED_LIST_FILENAME_MALLOC_ERR;
  39.  
  40. strncpy(fat12->list.list->fileName, fileName, strlen(fileName) + 1);
  41. //fat12->list.list->fileName = strdup(fileName);
  42.  
  43. fat12->list.list->next = NULL;
  44.  
  45. if (fat12->list.first == NULL)
  46. fat12->list.first = fat12->list.list;
  47.  
  48. fat12->list.last = fat12->list.list;
  49. fat12->NumberOfFiles++;
  50.  
  51. return FAT12_OK;
  52. }
  53. else
  54. return result;
  55. }
  56.  
  57. ...
  58. while (fat12->list.list != NULL)
  59. {
  60. sectorsCount = (unsigned short)(fat12->list.list->directoryEntry.FileSize / fat12->boot_sector.BytesPerSector) + 1;
  61. fat12->list.list->directoryEntry.StartingCluster = LBAAddress;
  62.  
  63. printf("\nFile: %s, Size: %d bytes, Sectors count: %d, LBA Address: 0x%.4x", fat12->list.list->fileName,
  64. fat12->list.list->directoryEntry.FileSize, sectorsCount, LBAAddress);
  65.  
  66. LBAAddress += sectorsCount;
  67.  
  68. if (sectorsCountOfNextFile != -1) //Quiere decir que ya usamos un cluster
  69. sectorsCount--;
  70. sectorsCountOfNextFile = -1;
  71.  
  72. fat12->list.list = fat12->list.list->next; //Preparamos el siguiente archivo
  73. while (sectorsCount > 0)
  74. {
  75. switch (sectorsCount)
  76. {
  77. case 1:
  78. sectorsCount = 0;
  79. fat_entry = 0x000FFF00;
  80.  
  81. if (fat12->list.list != NULL)
  82. {
  83. sectorsCountOfNextFile = (unsigned short)(fat12->list.list->directoryEntry.FileSize / fat12->boot_sector.BytesPerSector) + 1;
  84. if (sectorsCountOfNextFile == 1)
  85. fat_entry = 0xFFFFFF00;
  86. else
  87. fat_entry += (nextCluster + 1) << 20;
  88. }
  89. break;
  90. case 2:
  91. fat_entry = 0xFFF00000 + (nextCluster << 8);
  92. sectorsCount = 0;
  93. break;
  94. default:
  95. fat_entry = (unsigned long)((nextCluster + 1) << 20) + (nextCluster << 8);
  96.  
  97. sectorsCount -= 2;
  98. break;
  99. }
  100. nextCluster+=2;
  101.  
  102. *fatTable++ = (unsigned char)((fat_entry & 0x0000FF00) >> 8);
  103. *fatTable++ = (unsigned char)((fat_entry & 0x00FF0000) >> 16);
  104. *fatTable++ = (unsigned char)((fat_entry & 0xFF000000) >> 24);
  105. }
  106. }
  107.  
  108.  

Estoy haciendo más portable el código para que se pueda compilar en sistemas *nix, además, estoy escribiendo una buena documentación en español sobre el sistema de archivos FAT12.

https://sourceforge.net/projects/fat12maker/

Espero que os sea de utilidad  ;D

Saludos.
5  Sistemas Operativos / GNU/Linux / Kernel Panic en Arch en: 5 Diciembre 2011, 02:00 am
Hola, llevo 2 meses con Arch Linux en mi netbook y me va de maravilla. El problema comenzó el otro día cuando le instalé el kernel 3.1.4-1, a veces al encender el ordenador me daba un kernel panic y ahí se quedaba... Pensé que era problema del kernel, que igual tendría algún que otro fallo así que inicié en modo de recuperación y lo sustituí por uno viejo que funcionaba perfectamente, concretamente el 3.1.1-1.

Pero con el kernel 3.1.1-1 sigue haciendo lo mismo: unas veces se produce un kernel panic al bootear y otras veces arranca perfectamente...

La verdad no se que hacer y me da pereza formatear porque tenía todo el sistema configurado a mi gusto... y no es fácil configurar un Arch...

Descartados problemas de hardware, hice test de memoria y de disco. Además tengo dual boot con Windows 7 y este funciona perfecto.

Saludos.
6  Programación / Programación C/C++ / Threads Affinity! en: 29 Agosto 2011, 02:32 am
El otro día estaba investigando la posibilidad de ejecutar un Thread en un núcleo específico del procesador y me encontré con esta función de la API de Windows: SetThreadAffinityMask().

Se define así:

DWORD_PTR WINAPI SetThreadAffinityMask(__in HANDLE hThread, __in DWORD_PTR dwThreadAffinityMask);

Usando el siguiente programa y el taskmanager de Windows hice las siguientes pruebas:

Código
  1. #include <iostream>
  2. #include <Windows.h>
  3.  
  4. using namespace std;
  5.  
  6. void threadFunc()
  7. {
  8. double a = 0;
  9.  
  10. for (unsigned long long i = 0;;i++)
  11. {
  12. a = (i * 17) - 32;
  13. if (a > 0)
  14. a = (sqrt(a) * 43) - 72;
  15. }
  16. }
  17.  
  18. int main(int argc, char * argv[])
  19. {
  20. SYSTEM_INFO sysInfo;
  21. DWORD dwThreadId;
  22.  
  23. GetSystemInfo(&sysInfo);
  24. cout << "Numero de nucleos: " << sysInfo.dwNumberOfProcessors << endl << endl;
  25.  
  26. BYTE coreToUse = 0; //Empieza en el 0
  27. HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadFunc, NULL, 0, &dwThreadId);
  28.  
  29. if (SetThreadAffinityMask(hThread, 1 << (coreToUse % 8)) != 0)
  30. cout << "ThreadAffinity se establecio con exito en el nucleo " << (int)coreToUse << endl;
  31. else
  32. cout << "ThreadAffinity error! El sistema repartira la carga del Thread!" << endl;
  33.  
  34. cin.get();
  35.  
  36. return 0;
  37. }
  38.  

En la variable coreToUse especificas que núcleo que vas a usar para ejecutar el thread con la función threadFunc(). En mi caso tengo como procesador un AMD Athlon X 2 6400 - 3.2 GHz, por lo tanto sólo tiene 2 núcleos.



Como podéis ver en la imagen, el primer núcleo se pone al 100%.. Ahora voy a hacer lo mismo, pero poniendole el valor 1 a la variable coreToUse.



¿Qué pasaría si le pongo un valor mayor que 1? Pues en mi caso, como solo tiene 2 núcleos mi procesador, fallaría la función SetThreadAffinityMask() y por lo tanto el sistema repartiría la carga de la función threadFunc().



No trabajan los dos núcleos lo mismo, siempre va a trabajar más uno que otro, pero eso depende de los algoritmos de planificación del scheduler del kernel de Windows...

Y ahora viene la gran pregunta, ¿Vale la pena utilizar esta API? La verdad, yo no le encontré gran utilidad. Quizás con 2 núcleos no te sirva de mucho, pero con 8 o 12 núcleos se podrían hacer bastantes cosas a la vez. Supongo que para los videojuegos o programas que necesiten gran capacidad de cálculo les será útil. Aunque siempre dependes de la cantidad de núcleos que tenga el equipo que ejecute tu programa.

Saludos.
7  Programación / Programación C/C++ / Problema de dependencias en: 4 Junio 2011, 11:49 am
Hola, estoy haciendo un proyecto en C# y C++ con el Visual Studio. La interfaz está hecha en C# y el "corazón" del programa está en una librería hecha en C++.

Código
  1. #include <Windows.h>
  2. //#include "core.h"
  3. #include <curl/curl.h>
  4.  
  5. extern "C" __declspec(dllexport) int StartXModule();
  6.  
  7. BOOL APIENTRY DllMain( HANDLE hModule,
  8.                        DWORD  ul_reason_for_call,
  9.                        LPVOID lpReserved )
  10. {
  11.    return TRUE;
  12. }
  13.  
  14.  
  15. int StartXModule()
  16. {
  17. curl_global_init(CURL_GLOBAL_DEFAULT);
  18. return 0;
  19. }
  20.  

La llamada de la función desde C# se hace aquí:

Código
  1. [DllImport("x-module.dll")]
  2.        private static extern int StartXModule();
  3.  
  4.        private void FMain_Load(object sender, EventArgs e)
  5.        {
  6.            PMain.BackColor = System.Drawing.ColorTranslator.FromWin32(0x00373737);
  7.            //for (int i = 0; i < 30; i++)
  8.            //    listBoxX1.Items.Add("qdwqdqw");
  9.            StartXModule();
  10.        }
  11.  

Depurando desde el Visual C# la aplicación se ejecuta correctamente, pero generando la aplicación y ejecutando directamente me da este error:

No se puede cargar el archivo DLL "x-module.dll". No se puede encontrar el módulo especificado. (Excepción de HRESULT: 0x8007007E).

Mi aplicación la forman 2 librerías (libcurl.dll y x-module.dll) y la aplicación hecha en C#. El problema creo que está en que no tiene acceso a la función curl_globla_init() llamando a StartXModule() desde C#, porque si comento esa línea, la función se carga correctamente.

Espero que me podáis ayudar.. Saludos.
8  Foros Generales / Foro Libre / Proyecto de fin de ciclo en: 28 Marzo 2011, 21:02 pm
Hola, hace un mes un compañero y yo teníamos que crear una web como proyecto para la asignatura de Implementación de Aplicaciones Informáticas de Gestión. Mi clase y yo, nos pasábamos todo el día metidos en páginas tipo desmotivaciones y de memes. Así que pensamos en crear una web de ese estilo.

Nos llevó cerca de un mes, la desarrollamos en MySQL y PHP con xampp. Hace una semana decidimos colgarla en Internet y compramos un hosting LAMP. Todavía tiene algún que otro fallo y está un poco verde.



Espero que os guste, se aceptan críticas y sugerencias.

http://aburrimientomaximo.com/

Saludos.
9  Programación / Programación General / [Delphi] PEFileSize function en: 25 Enero 2011, 17:52 pm
Código
  1. (*
  2.  * PEFileSize function, inspired by The Swash
  3.  * by Khronos
  4. *)
  5.  
  6. function PEFileSize(FileName: string): Cardinal;
  7. var
  8. i: integer;
  9. FileStream: TFileStream;
  10. IDH: IMAGE_DOS_HEADER;
  11. INH: IMAGE_NT_HEADERS;
  12. ISH: IMAGE_SECTION_HEADER;
  13. begin
  14. result:= 0;
  15.  try
  16.    FileStream:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
  17.    FileStream.Read(IDH, SizeOf(IDH));
  18.    if IDH.e_magic = IMAGE_DOS_SIGNATURE then
  19.      begin
  20.        FileStream.Seek(IDH._lfanew, 0);
  21.        FileStream.Read(INH, SizeOf(INH));
  22.        if INH.Signature = IMAGE_NT_SIGNATURE then
  23.          begin
  24.            for I := 0 to INH.FileHeader.NumberOfSections - 1 do
  25.              begin
  26.                FileStream.Seek(IDH._lfanew + SizeOf(INH) + SizeOf(ISH) * i, 0);
  27.                FileStream.Read(ISH, SizeOf(ISH));
  28.                result:= result + ISH.SizeOfRawData;
  29.              end;
  30.            result:= result + INH.OptionalHeader.SizeOfHeaders;
  31.          end;
  32.      end;
  33.  finally
  34.    FileStream.Free;
  35.  end;
  36. end;
  37.  

Saludos.
10  Programación / Programación General / DownloadFile [Delphi] en: 24 Enero 2011, 00:01 am
Hace algún tiempo cree una función para descargar un archivo de una página web en Delphi. Hoy decidí mejorarla un poco y tiene algunas novedades:

- La función se ejecuta dentro de un Thread, por lo que no afecta al rendimiento de la aplicación ni hace que se congele.
- Para descargar el archivo me conecto al servidor trabajando directamente con sockets y consultas HTTP.
- Incluye 3 eventos: OnStartDownload, OnProgress y OnFinishDownload.

Código
  1. procedure DownloadFile(URL: AnsiString; FileName: String; StartDownload: TOnStartDownload;  
  2.          Progress: TOnProgress; FinishDownload: TOnFinishDownload);

URL: Es la dirección del archivo web a descargar.
FileName: Es la ruta donde vas a guardar el archivo descargado.
StartDownload: Es un puntero a una función, este se ejecutará al comenzar la descarga. Devuelve como parámetro el tamaño del archivo, si se conoce.
Progress: Es un puntero a una función, este se ejecuta a medida que se va descargando el archivo. Este evento, puede ser útil si quieres mostrar el progreso de la descarga en un TProgressBar, por ejemplo.
FinishDownload: Es un puntero a una función, este se ejecuta si se produce algún error en la descarga o al terminar la descarga. Tiene como parámetro ErrorCode, de tipo byte, si ErrorCode es 0 significa que la descarga se completó con éxito.

A continuación el código de la unidad:

Código
  1. unit URLDown;
  2.  
  3. (*
  4.  * *****************************************************************************
  5.  * ***************************   Unidad URLDown  *******************************
  6.  *    Esta unidad contiene la función DownloadFile, una función que
  7.  * descarga un archivo desde una dirección URL. Esta función se ejecuta en
  8.  * otro thread, por lo que no "congela" la aplicación ni causa inastabilidad.
  9.  * Además, cuenta con 3 eventos: OnStartDownload, OnProgress y OnFinishDownload.
  10.  *
  11.  * Autor: Khronos
  12.  * Email: khronos14@hotmail.com
  13.  * Blog: khronos14.blogspot.com
  14.  *******************************************************************************
  15. *)
  16.  
  17. interface
  18.  
  19. uses SysUtils, Classes, Windows, WinSock;
  20.  
  21. {$DEFINE OBJECT_FUNCTIONS}
  22. (*
  23.   Si borras la definición OBJECT_FUNCTIONS, los eventos
  24.   de la función DownloadFile no serán de tipo objeto.
  25.   Para emplear esta función en modo consola o sin clases,
  26.   comenta esta definición.
  27. *)
  28.  
  29. const
  30.  SZBUFFER_SIZE   = 2048; //Este es el tamaño del buffer de descarga
  31.  
  32.  URLDOWN_OK                    = 0;
  33.  URLDOWN_INVALID_HOST          = 1;
  34.  URLDOWN_CONNECT_ERROR         = 2;
  35.  URLDOWN_DOWNLOAD_ERROR        = 3;
  36.  URLDOWN_UNKNOWN_ERROR         = $FD;
  37.  
  38. type
  39.  TOnStartDownload = procedure(FileSize: int64) {$IFDEF OBJECT_FUNCTIONS}of object{$ENDIF};
  40.  TOnProgress = procedure(Progress: int64) {$IFDEF OBJECT_FUNCTIONS}of object{$ENDIF};
  41.  TOnFinishDownload = procedure(ErrorCode: byte) {$IFDEF OBJECT_FUNCTIONS}of object{$ENDIF};
  42.  
  43.  TDownloadVars = record
  44.    URL: AnsiString;
  45.    FileName: String;
  46.    OnStartDownload: TOnStartDownload;
  47.    OnProgress: TOnProgress;
  48.    OnFinishDownload: TOnFinishDownload;
  49.  end;
  50.  PDownloadVars = ^TDownloadVars;
  51.  
  52. procedure DownloadFile(URL: AnsiString; FileName: String; StartDownload: TOnStartDownload;
  53.          Progress: TOnProgress; FinishDownload: TOnFinishDownload); stdcall;
  54.  
  55. implementation
  56.  
  57.  
  58. function GetDomainName(const URL: AnsiString): AnsiString;
  59. var
  60. P1: integer;
  61. begin
  62.  P1:= Pos('http://', URL);
  63.  if P1 > 0 then
  64.   begin
  65.     result:= Copy(URL, P1 + 7, Length(URL) - P1 - 6);
  66.     P1:= Pos('/', result);
  67.     if P1 > 0 then
  68.       result:= Copy(result, 0, P1 - 1);
  69.   end else
  70.     begin
  71.       P1:= Pos('/', URL);
  72.       if P1 > 0 then
  73.         result:= Copy(URL, 0, P1 - 1)
  74.       else result:= URL;
  75.     end;
  76. end;
  77.  
  78. function GetFileWeb(const URL: AnsiString): AnsiString;
  79. var
  80. P1: integer;
  81. begin
  82.  P1:= Pos('http://', URL);
  83.  if P1 > 0 then
  84.   begin
  85.     result:= Copy(URL, P1 + 7, Length(URL) - P1 - 6);
  86.     P1:= Pos('/', result);
  87.     if P1 > 0 then
  88.       result:= Copy(result, P1, Length(result) - P1 + 1);
  89.   end else
  90.     begin
  91.       P1:= Pos('/', URL);
  92.       if P1 > 0 then
  93.         result:= Copy(URL, P1, Length(URL) - P1 + 1)
  94.       else result:= URL;
  95.     end;
  96.  if result = GetDomainName(URL) then
  97.    result:= '/';
  98. end;
  99.  
  100. procedure CleanHttp(var Mem: TMemoryStream);
  101. var
  102. i: integer;
  103. Separator: array [0..3] of AnsiChar;
  104. Mem2: TMemoryStream;
  105. begin
  106. if Assigned(Mem) then
  107.   begin
  108.     for i := 0 to Mem.Size - 1 do
  109.       begin
  110.         Mem.Seek(i, 0);
  111.         Mem.Read(Separator, 4);
  112.         if (Separator[0] = #13) and (Separator[1] = #10) and (Separator[2] = #13)
  113.             and (Separator[3] = #10) then
  114.               begin
  115.                 Mem2:= TMemoryStream.Create;
  116.                 Mem.Seek(i + 4, 0);
  117.                 Mem2.CopyFrom(Mem, Mem.Size - I - 4);
  118.                 Mem:= Mem2;
  119.                 break;
  120.               end;
  121.       end;
  122.   end;
  123. end;
  124.  
  125. function SendQuery(Socket: TSocket; RHost: sockaddr_in; Query: AnsiString): boolean;
  126. begin
  127. if Connect(Socket, PSockAddrIn(@RHost)^, Sizeof(RHost)) = 0 then
  128.  begin
  129.    send(Socket, Pointer(Query)^, Length(Query), 0);
  130.    result:= true;
  131.  end else
  132.    result:= false;
  133. end;
  134.  
  135. function CreateQuery(URL: AnsiString): AnsiString;
  136. begin
  137.  result:= 'GET ' + GetFileWeb(URL) + ' HTTP/1.0' + #13#10 +
  138.    'Host: ' + GetDomainName(URL) +  #13#10 +
  139.    'User-Agent: Khronos' + #13#10#13#10;
  140. end;
  141.  
  142. function GetContentLength(szBuff: AnsiString; Size: Cardinal): int64;
  143. var
  144. dwStart, dwEnd: integer;
  145. ContentLength: AnsiString;
  146. begin
  147. Result:= 0;
  148.  dwStart:= Pos('Content-Length: ', szBuff);
  149.  if dwStart <> 0 then
  150.    begin
  151.      dwStart:= dwStart + StrLen('Content-Length: ');
  152.      dwEnd:= dwStart;
  153.      repeat
  154.        Inc(dwEnd);
  155.      until (szBuff[dwEnd] = #0) or (szBuff[dwEnd] = #13) or (dwEnd = Size);
  156.      ContentLength:= Copy(szBuff, dwStart, dwEnd - dwStart);
  157.      if TryStrToInt64(ContentLength, Result) = false then
  158.        result:= -1;
  159.    end;
  160.  dwStart:= Pos(#13#10#13#10, szBuff);
  161. end;
  162.  
  163. function InitializeWinSock(Host: AnsiString; var Socket: TSocket; var RHost: sockaddr_in): boolean;
  164. var
  165. WSA: TWSAData;
  166. Addr: u_long;
  167. Hostent: PHostent;
  168. Ip: ^Integer;
  169. begin
  170. If WSAStartup(MakeWord(2,2), WSA) = 0 then
  171.  begin
  172.     Socket:= WinSock.SOCKET(AF_INET, SOCK_STREAM, 0);
  173.     if Socket <> INVALID_SOCKET then
  174.        begin
  175.          Hostent:= GetHostByName(PAnsiChar(GetDomainName(Host)));
  176.          if Hostent <> nil then
  177.            begin
  178.              Ip:= @Hostent.h_addr_list^[0];
  179.              RHost.sin_family:= AF_INET;
  180.              RHost.sin_port:= htons(80);
  181.              RHost.sin_addr.S_addr:= ip^;
  182.              result:= true;
  183.           end;
  184.        end;
  185.  end else
  186.    result:= false;
  187. end;
  188.  
  189. function ProcessDownload(Socket: TSocket; FileName: WideString; StartDownload: TOnStartDownload;
  190.          Progress: TOnProgress; FinishDownload: TOnFinishDownload): boolean;
  191. var
  192. szBuffer: array [0..SZBUFFER_SIZE] of AnsiChar;
  193. Stream: TMemoryStream;
  194. ContentLength, ReturnCode: integer;
  195. begin
  196. result:= false;
  197.    try
  198.      Stream:= TMemoryStream.Create;
  199.      ContentLength:= 0;
  200.      repeat
  201.        FillChar(szBuffer, SZBUFFER_SIZE, 0);
  202.        ReturnCode:= recv(Socket, szBuffer, SZBUFFER_SIZE, 0);
  203.        if (ContentLength = 0) and (ReturnCode > 0) then
  204.          begin
  205.            ContentLength:= GetContentLength(szBuffer, ReturnCode);
  206.            if Assigned(StartDownload) then
  207.              StartDownload(ContentLength);
  208.          end;
  209.        if ReturnCode > 0 then
  210.          begin
  211.            Stream.Write(szBuffer, ReturnCode);
  212.            if Assigned(Progress) then
  213.                Progress(Stream.Position);
  214.          end;
  215.      until ReturnCode <= 0;
  216.      if Stream.Size > 0 then
  217.        begin
  218.          CleanHttp(Stream);
  219.          Stream.SaveToFile(FileName);
  220.          if Assigned(FinishDownload) then
  221.            FinishDownload(URLDOWN_OK);
  222.          result:= true;
  223.        end;
  224.    finally
  225.      Stream.Free;
  226.    end;
  227. end;
  228.  
  229. procedure Download(P: Pointer);
  230. var
  231. Query: AnsiString;
  232. Socket: TSocket;
  233. RHost: sockaddr_in;
  234. begin
  235.  try
  236.    if InitializeWinSock(TDownloadVars(P^).URL, Socket, RHost) then
  237.      begin
  238.        Query:= CreateQuery(TDownloadVars(P^).URL);
  239.        if SendQuery(Socket, RHost, Query) then
  240.          begin
  241.            If ProcessDownload(Socket, TDownloadVars(P^).FileName, TDownloadVars(P^).OnStartDownload,
  242.                TDownloadVars(P^).OnProgress, TDownloadVars(P^).OnFinishDownload) = false then
  243.                if Assigned(TDownloadVars(P^).OnFinishDownload) then
  244.                  TDownloadVars(P^).OnFinishDownload(URLDOWN_DOWNLOAD_ERROR);
  245.            ShutDown(Socket, SD_BOTH);
  246.            CloseSocket(Socket);
  247.          end else
  248.            if Assigned(TDownloadVars(P^).OnFinishDownload) then
  249.              TDownloadVars(P^).OnFinishDownload(URLDOWN_CONNECT_ERROR);
  250.      end else
  251.        if Assigned(TDownloadVars(P^).OnFinishDownload) then
  252.          TDownloadVars(P^).OnFinishDownload(URLDOWN_INVALID_HOST);
  253.  
  254.    WSACleanUp();
  255.    Dispose(PDownloadVars(P));
  256.  Except on Exception do
  257.    begin
  258.      if Assigned(TDownloadVars(P^).OnFinishDownload) then
  259.          TDownloadVars(P^).OnFinishDownload(URLDOWN_UNKNOWN_ERROR);
  260.    end;
  261.  end;
  262. end;
  263.  
  264. procedure DownloadFile(URL: AnsiString; FileName: String; StartDownload: TOnStartDownload;
  265.          Progress: TOnProgress; FinishDownload: TOnFinishDownload);
  266. var
  267. DownloadVars: ^TDownloadVars;
  268. begin
  269.  New(DownloadVars);
  270.  DownloadVars^.URL:= URL;
  271.  DownloadVars^.FileName:= FileName;
  272.  DownloadVars^.OnStartDownload:= StartDownload;
  273.  DownloadVars^.OnProgress:= Progress;
  274.  DownloadVars^.OnFinishDownload:= FinishDownload;
  275.  
  276.  BeginThread(nil, 0, @Download, DownloadVars, 0, PDWORD(0)^);
  277. end;
  278.  
  279.  
  280. end.
  281.  

Subí a MegaUpload un programa de prueba que usa la función, además incluye todo el código fuente.

http://www.megaupload.com/?d=GU5P5QDW

Saludos.

Páginas: [1] 2
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines