2012-04-18 60 views
0

我正在嘗試獲取與文件內特定字節關聯的(物理)位置。我會怎麼做呢?如何在Linux中獲取文件中某個位置的物理地址

我不能在C中這樣做,因爲我必須將文件讀入緩衝區,如果我嘗試在RAM中獲取物理(非虛擬)地址,我會得到緩衝區的地址而不是特定的字節那是在文件中。

幫助將不勝感激。

感謝

+1

文件中的字節沒有地址,因爲您在考慮它們。它們存儲在磁盤上,而不是存儲在RAM中,並且您要求在RAM中存儲地址。 – 2012-04-18 19:41:41

+0

我將文件「臨時」存儲在/ shmem中,它基本上映射到了RAM中。 – Falcata 2012-04-18 19:43:20

+0

文件中的某個字節沒有內存地址,除非您將該文件的內容讀取到緩衝區或使用mmap進行映射。 – smichak 2012-04-18 19:46:20

回答

0

爲了做到這一點,你應該通過設備直接檢查文件系統。這意味着你應該能夠定位位圖表,i節點表,目錄條目和類似的東西。對於現代和即將到來的文件系統(例如Btrfs)來說,這並不是微不足道的。

除此之外,你應該不得不處理塊和扇區偏移或地址(也許LBA或可能是基於圓柱體)。

所以,在我看來,答案是或者至少它的解決方案會非常複雜。

1

通過mmap將共享內存映射到進程中,訪問包含壞數據的頁面,然後閱讀/proc/self/pagemap以查找有關虛擬內存頁如何映射到物理內存的信息。

* /proc/pid/pagemap. This file lets a userspace process find out which 
    physical frame each virtual page is mapped to. It contains one 64-bit 
    value for each virtual page, containing the following data (from 
    fs/proc/task_mmu.c, above pagemap_read): 

    * Bits 0-54 page frame number (PFN) if present 
    * Bits 0-4 swap type if swapped 
    * Bits 5-54 swap offset if swapped 
    * Bits 55-60 page shift (page size = 1<<page shift) 
    * Bit 61 reserved for future use 
    * Bit 62 page swapped 
    * Bit 63 page present 

    If the page is not present but in swap, then the PFN contains an 
    encoding of the swap file number and the page's offset into the 
    swap. Unmapped pages return a null PFN. This allows determining 
    precisely which pages are mapped (or in swap) and comparing mapped 
    pages between processes. 

    Efficient users of this interface will use /proc/pid/maps to 
    determine which areas of memory are actually mapped and llseek to 
    skip over unmapped regions. 

注意:這似乎只在較新的內核上。另外,這裏是how to translate the PFN into a physical address

相關問題