Path: blob/main/contrib/elftoolchain/libpe/pe_rich.c
39482 views
/*-1* Copyright (c) 2016 Kai Wang2* All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12*13* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND14* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE15* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE16* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE17* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL18* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS19* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)20* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT21* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY22* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF23* SUCH DAMAGE.24*/2526#include <assert.h>27#include <errno.h>2829#include "_libpe.h"3031ELFTC_VCSID("$Id: pe_rich.c 3312 2016-01-10 09:23:51Z kaiwang27 $");3233PE_RichHdr *34pe_rich_header(PE *pe)35{3637if (pe == NULL) {38errno = EINVAL;39return (NULL);40}4142if (pe->pe_rh == NULL && pe->pe_stub_ex > 0 &&43(pe->pe_flags & LIBPE_F_LOAD_DOS_STUB) == 0) {44assert((pe->pe_flags & LIBPE_F_SPECIAL_FILE) == 0);45(void) libpe_read_msdos_stub(pe);46}4748if (pe->pe_rh == NULL) {49errno = ENOENT;50return (NULL);51}5253return (pe->pe_rh);54}5556static uint32_t57rol32(uint32_t n, int c)58{5960c &= 0x1f;6162return ((n << c) | (n >> (0x20 - c)));63}6465int66pe_rich_header_validate(PE *pe)67{68PE_RichHdr *rh;69uint32_t cksum;70char *p;71int i, off;7273if (pe_rich_header(pe) == NULL)74return (-1);7576assert(pe->pe_rh_start != NULL);7778/*79* Initial value of the checksum is the offset to the begin of80* the Rich header.81*/82cksum = pe->pe_rh_start - pe->pe_stub;8384/*85* Add the bytes before the Rich header to the checksum, rotated86* left by the offset.87*/88for (p = pe->pe_stub; p < pe->pe_rh_start; p++) {89/* Skip dh_lfanew. */90off = p - pe->pe_stub;91if (off >= 0x3c && off < 0x40)92continue;93cksum += rol32((unsigned char) *p, off);94}9596/* Add each compid rotated left by its count to the checksum. */97rh = pe->pe_rh;98for (i = 0; (uint32_t) i < rh->rh_total; i++)99cksum += rol32(rh->rh_compid[i], rh->rh_cnt[i]);100101/* Validate the checksum with the XOR mask stored after "Rich". */102if (cksum == rh->rh_xor)103return (1);104105return (0);106}107108109