/* * ACPI implementation * * Copyright (c) 2006 Fabrice Bellard * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "vl.h" //#define DEBUG /* i82731AB (PIIX4) compatible power management function */ #define PM_FREQ 3579545 /* XXX: make them variable */ #define PM_IO_BASE 0xb000 #define SMI_CMD_IO_ADDR 0xb040 #define ACPI_DBG_IO_ADDR 0xb044 typedef struct PIIX4PMState { PCIDevice dev; uint16_t pmsts; uint16_t pmen; uint16_t pmcntrl; QEMUTimer *tmr_timer; int64_t tmr_overflow_time; } PIIX4PMState; #define RTC_EN (1 << 10) #define PWRBTN_EN (1 << 8) #define GBL_EN (1 << 5) #define TMROF_EN (1 << 0) #define SCI_EN (1 << 0) #define SUS_EN (1 << 13) /* Note: only used for ACPI bios init. Could be deleted when ACPI init is integrated in Bochs BIOS */ static PIIX4PMState *piix4_pm_state; static uint32_t get_pmtmr(PIIX4PMState *s) { uint32_t d; d = muldiv64(qemu_get_clock(vm_clock), PM_FREQ, ticks_per_sec); return d & 0xffffff; } static int get_pmsts(PIIX4PMState *s) { int64_t d; int pmsts; pmsts = s->pmsts; d = muldiv64(qemu_get_clock(vm_clock), PM_FREQ, ticks_per_sec); if (d >= s->tmr_overflow_time) s->pmsts |= TMROF_EN; return pmsts; } static void pm_update_sci(PIIX4PMState *s) { int sci_level, pmsts; int64_t expire_time; pmsts = get_pmsts(s); sci_level = (((pmsts & s->pmen) & (RTC_EN | PWRBTN_EN | GBL_EN | TMROF_EN)) != 0); pci_set_irq(&s->dev, 0, sci_level); /* schedule a timer interruption if needed */ if ((s->pmen & TMROF_EN) && !(pmsts & TMROF_EN)) { expire_time = muldiv64(s->tmr_overflow_time, ticks_per_sec, PM_FREQ); qemu_mod_timer(s->tmr_timer, expire_time); } else { qemu_del_timer(s->tmr_timer); } } static void pm_tmr_timer(void *opaque) { PIIX4PMState *s = opaque; pm_update_sci(s); } static void pm_ioport_writew(void *opaque, uint32_t addr, uint32_t val) { PIIX4PMState *s = opaque; addr &= 0x3f; switch(addr) { case 0x00: { int64_t d; int pmsts; pmsts = get_pmsts(s); if (pmsts & val & TMROF_EN) { /* if TMRSTS is reset, then compute the new overflow time */ d = muldiv64(qemu_get_clock(vm_clock), PM_FREQ, ticks_per_sec); s->tmr_overflow_time = (d + 0x800000LL) & ~0x7fffffLL; } s->pmsts &= ~val; pm_update_sci(s); } break; case 0x02: s->pmen = val; pm_update_sci(s); break; case 0x04: { int sus_typ; s->pmcntrl = val & ~(SUS_EN); if (val & SUS_EN) { /* change suspend type */ sus_typ = (val >> 10) & 3; switch(sus_typ) { case 0: /* soft power off */ qemu_system_shutdown_request(); break; default: break; } } } break; default: break; } #ifdef DEBUG printf("PM writew port=0x%04x val=0x%04x\n", addr, val); #endif } static uint32_t pm_ioport_readw(void *opaque, uint32_t addr) { PIIX4PMState *s = opaque; uint32_t val; addr &= 0x3f; switch(addr) { case 0x00: val = get_pmsts(s); break; case 0x02: val = s->pmen; break; case 0x04: val = s->pmcntrl; break; default: val = 0; break; } #ifdef DEBUG printf("PM readw port=0x%04x val=0x%04x\n", addr, val); #endif return val; } static void pm_ioport_writel(void *opaque, uint32_t addr, uint32_t val) { // PIIX4PMState *s = opaque; addr &= 0x3f; #ifdef DEBUG printf("PM writel port=0x%04x val=0x%08x\n", addr, val); #endif } static uint32_t pm_ioport_readl(void *opaque, uint32_t addr) { PIIX4PMState *s = opaque; uint32_t val; addr &= 0x3f; switch(addr) { case 0x08: val = get_pmtmr(s); break; default: val = 0; break; } #ifdef DEBUG printf("PM readl port=0x%04x val=0x%08x\n", addr, val); #endif return val; } static void smi_cmd_writeb(void *opaque, uint32_t addr, uint32_t val) { PIIX4PMState *s = opaque; #ifdef DEBUG printf("SMI cmd val=0x%02x\n", val); #endif switch(val) { case 0xf0: /* ACPI disable */ s->pmcntrl &= ~SCI_EN; break; case 0xf1: /* ACPI enable */ s->pmcntrl |= SCI_EN; break; } } static void acpi_dbg_writel(void *opaque, uint32_t addr, uint32_t val) { #if defined(DEBUG) printf("ACPI: DBG: 0x%08x\n", val); #endif } /* XXX: we still add it to the PIIX3 and we count on the fact that OSes are smart enough to accept this strange configuration */ void piix4_pm_init(PCIBus *bus, int devfn) { PIIX4PMState *s; uint8_t *pci_conf; uint32_t pm_io_base; s = (PIIX4PMState *)pci_register_device(bus, "PM", sizeof(PIIX4PMState), devfn, NULL, NULL); pci_conf = s->dev.config; pci_conf[0x00] = 0x86; pci_conf[0x01] = 0x80; pci_conf[0x02] = 0x13; pci_conf[0x03] = 0x71; pci_conf[0x08] = 0x00; // revision number pci_conf[0x09] = 0x00; pci_conf[0x0a] = 0x80; // other bridge device pci_conf[0x0b] = 0x06; // bridge device pci_conf[0x0e] = 0x00; // header_type pci_conf[0x3d] = 0x01; // interrupt pin 1 pm_io_base = PM_IO_BASE; pci_conf[0x40] = pm_io_base | 1; pci_conf[0x41] = pm_io_base >> 8; register_ioport_write(pm_io_base, 64, 2, pm_ioport_writew, s); register_ioport_read(pm_io_base, 64, 2, pm_ioport_readw, s); register_ioport_write(pm_io_base, 64, 4, pm_ioport_writel, s); register_ioport_read(pm_io_base, 64, 4, pm_ioport_readl, s); register_ioport_write(SMI_CMD_IO_ADDR, 1, 1, smi_cmd_writeb, s); register_ioport_write(ACPI_DBG_IO_ADDR, 4, 4, acpi_dbg_writel, s); /* XXX: which specification is used ? The i82731AB has different mappings */ pci_conf[0x5f] = (parallel_hds[0] != NULL ? 0x80 : 0) | 0x10; pci_conf[0x63] = 0x60; pci_conf[0x67] = (serial_hds[0] != NULL ? 0x08 : 0) | (serial_hds[1] != NULL ? 0x90 : 0); s->tmr_timer = qemu_new_timer(vm_clock, pm_tmr_timer, s); piix4_pm_state = s; } /* ACPI tables */ /* XXX: move them in the Bochs BIOS ? */ /*************************************************/ /* Table structure from Linux kernel (the ACPI tables are under the BSD license) */ #define ACPI_TABLE_HEADER_DEF /* ACPI common table header */ \ uint8_t signature [4]; /* ACPI signature (4 ASCII characters) */\ uint32_t length; /* Length of table, in bytes, including header */\ uint8_t revision; /* ACPI Specification minor version # */\ uint8_t checksum; /* To make sum of entire table == 0 */\ uint8_t oem_id [6]; /* OEM identification */\ uint8_t oem_table_id [8]; /* OEM table identification */\ uint32_t oem_revision; /* OEM revision number */\ uint8_t asl_compiler_id [4]; /* ASL compiler vendor ID */\ uint32_t asl_compiler_revision; /* ASL compiler revision number */ struct acpi_table_header /* ACPI common table header */ { ACPI_TABLE_HEADER_DEF }; struct rsdp_descriptor /* Root System Descriptor Pointer */ { uint8_t signature [8]; /* ACPI signature, contains "RSD PTR " */ uint8_t checksum; /* To make sum of struct == 0 */ uint8_t oem_id [6]; /* OEM identification */ uint8_t revision; /* Must be 0 for 1.0, 2 for 2.0 */ uint32_t rsdt_physical_address; /* 32-bit physical address of RSDT */ uint32_t length; /* XSDT Length in bytes including hdr */ uint64_t xsdt_physical_address; /* 64-bit physical address of XSDT */ uint8_t extended_checksum; /* Checksum of entire table */ uint8_t reserved [3]; /* Reserved field must be 0 */ }; /* * ACPI 1.0 Root System Description Table (RSDT) */ struct rsdt_descriptor_rev1 { ACPI_TABLE_HEADER_DEF /* ACPI common table header */ uint32_t table_offset_entry [2]; /* Array of pointers to other */ /* ACPI tables */ }; /* * ACPI 1.0 Firmware ACPI Control Structure (FACS) */ struct facs_descriptor_rev1 { uint8_t signature[4]; /* ACPI Signature */ uint32_t length; /* Length of structure, in bytes */ uint32_t hardware_signature; /* Hardware configuration signature */ uint32_t firmware_waking_vector; /* ACPI OS waking vector */ uint32_t global_lock; /* Global Lock */ uint32_t S4bios_f : 1; /* Indicates if S4BIOS support is present */ uint32_t reserved1 : 31; /* Must be 0 */ uint8_t resverved3 [40]; /* Reserved - must be zero */ }; /* * ACPI 1.0 Fixed ACPI Description Table (FADT) */ struct fadt_descriptor_rev1 { ACPI_TABLE_HEADER_DEF /* ACPI common table header */ uint32_t firmware_ctrl; /* Physical address of FACS */ uint32_t dsdt; /* Physical address of DSDT */ uint8_t model; /* System Interrupt Model */ uint8_t reserved1; /* Reserved */ uint16_t sci_int; /* System vector of SCI interrupt */ uint32_t smi_cmd; /* Port address of SMI command port */ uint8_t acpi_enable; /* Value to write to smi_cmd to enable ACPI */ uint8_t acpi_disable; /* Value to write to smi_cmd to disable ACPI */ uint8_t S4bios_req; /* Value to write to SMI CMD to enter S4BIOS state */ uint8_t reserved2; /* Reserved - must be zero */ uint32_t pm1a_evt_blk; /* Port address of Power Mgt 1a acpi_event Reg Blk */ uint32_t pm1b_evt_blk; /* Port address of Power Mgt 1b acpi_event Reg Blk */ uint32_t pm1a_cnt_blk; /* Port address of Power Mgt 1a Control Reg Blk */ uint32_t pm1b_cnt_blk; /* Port address of Power Mgt 1b Control Reg Blk */ uint32_t pm2_cnt_blk; /* Port address of Power Mgt 2 Control Reg Blk */ uint32_t pm_tmr_blk; /* Port address of Power Mgt Timer Ctrl Reg Blk */ uint32_t gpe0_blk; /* Port addr of General Purpose acpi_event 0 Reg Blk */ uint32_t gpe1_blk; /* Port addr of General Purpose acpi_event 1 Reg Blk */ uint8_t pm1_evt_len; /* Byte length of ports at pm1_x_evt_blk */ uint8_t pm1_cnt_len; /* Byte length of ports at pm1_x_cnt_blk */ uint8_t pm2_cnt_len; /* Byte Length of ports at pm2_cnt_blk */ uint8_t pm_tmr_len; /* Byte Length of ports at pm_tm_blk */ uint8_t gpe0_blk_len; /* Byte Length of ports at gpe0_blk */ uint8_t gpe1_blk_len; /* Byte Length of ports at gpe1_blk */ uint8_t gpe1_base; /* Offset in gpe model where gpe1 events start */ uint8_t reserved3; /* Reserved */ uint16_t plvl2_lat; /* Worst case HW latency to enter/exit C2 state */ uint16_t plvl3_lat; /* Worst case HW latency to enter/exit C3 state */ uint16_t flush_size; /* Size of area read to flush caches */ uint16_t flush_stride; /* Stride used in flushing caches */ uint8_t duty_offset; /* Bit location of duty cycle field in p_cnt reg */ uint8_t duty_width; /* Bit width of duty cycle field in p_cnt reg */ uint8_t day_alrm; /* Index to day-of-month alarm in RTC CMOS RAM */ uint8_t mon_alrm; /* Index to month-of-year alarm in RTC CMOS RAM */ uint8_t century; /* Index to century in RTC CMOS RAM */ uint8_t reserved4; /* Reserved */ uint8_t reserved4a; /* Reserved */ uint8_t reserved4b; /* Reserved */ #if 0 uint32_t wb_invd : 1; /* The wbinvd instruction works properly */ uint32_t wb_invd_flush : 1; /* The wbinvd flushes but does not invalidate */ uint32_t proc_c1 : 1; /* All processors support C1 state */ uint32_t plvl2_up : 1; /* C2 state works on MP system */ uint32_t pwr_button : 1; /* Power button is handled as a generic feature */ uint32_t sleep_button : 1; /* Sleep button is handled as a generic feature, or not present */ uint32_t fixed_rTC : 1; /* RTC wakeup stat not in fixed register space */ uint32_t rtcs4 : 1; /* RTC wakeup stat not possible from S4 */ uint32_t tmr_val_ext : 1; /* The tmr_val width is 32 bits (0 = 24 bits) */ uint32_t reserved5 : 23; /* Reserved - must be zero */ #else uint32_t flags; #endif }; /* * MADT values and structures */ /* Values for MADT PCATCompat */ #define DUAL_PIC 0 #define MULTIPLE_APIC 1 /* Master MADT */ struct multiple_apic_table { ACPI_TABLE_HEADER_DEF /* ACPI common table header */ uint32_t local_apic_address; /* Physical address of local APIC */ #if 0 uint32_t PCATcompat : 1; /* A one indicates system also has dual 8259s */ uint32_t reserved1 : 31; #else uint32_t flags; #endif }; /* Values for Type in APIC_HEADER_DEF */ #define APIC_PROCESSOR 0 #define APIC_IO 1 #define APIC_XRUPT_OVERRIDE 2 #define APIC_NMI 3 #define APIC_LOCAL_NMI 4 #define APIC_ADDRESS_OVERRIDE 5 #define APIC_IO_SAPIC 6 #define APIC_LOCAL_SAPIC 7 #define APIC_XRUPT_SOURCE 8 #define APIC_RESERVED 9 /* 9 and greater are reserved */ /* * MADT sub-structures (Follow MULTIPLE_APIC_DESCRIPTION_TABLE) */ #define APIC_HEADER_DEF /* Common APIC sub-structure header */\ uint8_t type; \ uint8_t length; /* Sub-structures for MADT */ struct madt_processor_apic { APIC_HEADER_DEF uint8_t processor_id; /* ACPI processor id */ uint8_t local_apic_id; /* Processor's local APIC id */ #if 0 uint32_t processor_enabled: 1; /* Processor is usable if set */ uint32_t reserved2 : 31; /* Reserved, must be zero */ #else uint32_t flags; #endif }; struct madt_io_apic { APIC_HEADER_DEF uint8_t io_apic_id; /* I/O APIC ID */ uint8_t reserved; /* Reserved - must be zero */ uint32_t address; /* APIC physical address */ uint32_t interrupt; /* Global system interrupt where INTI * lines start */ }; #include "acpi-dsdt.hex" static int acpi_checksum(const uint8_t *data, int len) { int sum, i; sum = 0; for(i = 0; i < len; i++) sum += data[i]; return (-sum) & 0xff; } static void acpi_build_table_header(struct acpi_table_header *h, char *sig, int len) { memcpy(h->signature, sig, 4); h->length = cpu_to_le32(len); h->revision = 0; memcpy(h->oem_id, "QEMU ", 6); memcpy(h->oem_table_id, "QEMU", 4); memcpy(h->oem_table_id + 4, sig, 4); h->oem_revision = cpu_to_le32(1); memcpy(h->asl_compiler_id, "QEMU", 4); h->asl_compiler_revision = cpu_to_le32(1); h->checksum = acpi_checksum((void *)h, len); } #define ACPI_TABLES_BASE 0x000e8000 /* base_addr must be a multiple of 4KB */ void acpi_bios_init(void) { struct rsdp_descriptor *rsdp; struct rsdt_descriptor_rev1 *rsdt; struct fadt_descriptor_rev1 *fadt; struct facs_descriptor_rev1 *facs; struct multiple_apic_table *madt; uint8_t *dsdt; uint32_t base_addr, rsdt_addr, fadt_addr, addr, facs_addr, dsdt_addr; uint32_t pm_io_base, acpi_tables_size, madt_addr, madt_size; int i; /* compute PCI I/O addresses */ pm_io_base = (piix4_pm_state->dev.config[0x40] | (piix4_pm_state->dev.config[0x41] << 8)) & ~0x3f; base_addr = ACPI_TABLES_BASE; /* reserve memory space for tables */ addr = base_addr; rsdp = (void *)(phys_ram_base + addr); addr += sizeof(*rsdp); rsdt_addr = addr; rsdt = (void *)(phys_ram_base + addr); addr += sizeof(*rsdt); fadt_addr = addr; fadt = (void *)(phys_ram_base + addr); addr += sizeof(*fadt); /* XXX: FACS should be in RAM */ addr = (addr + 63) & ~63; /* 64 byte alignment for FACS */ facs_addr = addr; facs = (void *)(phys_ram_base + addr); addr += sizeof(*facs); dsdt_addr = addr; dsdt = (void *)(phys_ram_base + addr); addr += sizeof(AmlCode); addr = (addr + 7) & ~7; madt_addr = addr; madt_size = sizeof(*madt) + sizeof(struct madt_processor_apic) * smp_cpus + sizeof(struct madt_io_apic); madt = (void *)(phys_ram_base + addr); addr += madt_size; acpi_tables_size = addr - base_addr; cpu_register_physical_memory(base_addr, acpi_tables_size, base_addr | IO_MEM_ROM); /* RSDP */ memset(rsdp, 0, sizeof(*rsdp)); memcpy(rsdp->signature, "RSD PTR ", 8); memcpy(rsdp->oem_id, "QEMU ", 6); rsdp->rsdt_physical_address = cpu_to_le32(rsdt_addr); rsdp->checksum = acpi_checksum((void *)rsdp, 20); /* RSDT */ rsdt->table_offset_entry[0] = cpu_to_le32(fadt_addr); rsdt->table_offset_entry[1] = cpu_to_le32(madt_addr); acpi_build_table_header((struct acpi_table_header *)rsdt, "RSDT", sizeof(*rsdt)); /* FADT */ memset(fadt, 0, sizeof(*fadt)); fadt->firmware_ctrl = cpu_to_le32(facs_addr); fadt->dsdt = cpu_to_le32(dsdt_addr); fadt->model = 1; fadt->reserved1 = 0; fadt->sci_int = cpu_to_le16(piix4_pm_state->dev.config[0x3c]); fadt->smi_cmd = cpu_to_le32(SMI_CMD_IO_ADDR); fadt->acpi_enable = 0xf1; fadt->acpi_disable = 0xf0; fadt->pm1a_evt_blk = cpu_to_le32(pm_io_base); fadt->pm1a_cnt_blk = cpu_to_le32(pm_io_base + 0x04); fadt->pm_tmr_blk = cpu_to_le32(pm_io_base + 0x08); fadt->pm1_evt_len = 4; fadt->pm1_cnt_len = 2; fadt->pm_tmr_len = 4; fadt->plvl2_lat = cpu_to_le16(50); fadt->plvl3_lat = cpu_to_le16(50); fadt->plvl3_lat = cpu_to_le16(50); /* WBINVD + PROC_C1 + PWR_BUTTON + SLP_BUTTON + FIX_RTC */ fadt->flags = cpu_to_le32((1 << 0) | (1 << 2) | (1 << 4) | (1 << 5) | (1 << 6)); acpi_build_table_header((struct acpi_table_header *)fadt, "FACP", sizeof(*fadt)); /* FACS */ memset(facs, 0, sizeof(*facs)); memcpy(facs->signature, "FACS", 4); facs->length = cpu_to_le32(sizeof(*facs)); /* DSDT */ memcpy(dsdt, AmlCode, sizeof(AmlCode)); /* MADT */ { struct madt_processor_apic *apic; struct madt_io_apic *io_apic; memset(madt, 0, madt_size); madt->local_apic_address = cpu_to_le32(0xfee00000); madt->flags = cpu_to_le32(1); apic = (void *)(madt + 1); for(i=0;itype = APIC_PROCESSOR; apic->length = sizeof(*apic); apic->processor_id = i; apic->local_apic_id = i; apic->flags = cpu_to_le32(1); apic++; } io_apic = (void *)apic; io_apic->type = APIC_IO; io_apic->length = sizeof(*io_apic); io_apic->io_apic_id = smp_cpus; io_apic->address = cpu_to_le32(0xfec00000); io_apic->interrupt = cpu_to_le32(0); acpi_build_table_header((struct acpi_table_header *)madt, "APIC", madt_size); } } 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
Please send your questions to the
[googlemock](http://groups.google.com/group/googlemock) discussion
group. If you need help with compiler errors, make sure you have
tried [Google Mock Doctor](#How_am_I_supposed_to_make_sense_of_these_horrible_template_error.md) first.

## When I call a method on my mock object, the method for the real object is invoked instead.  What's the problem? ##

In order for a method to be mocked, it must be _virtual_, unless you use the [high-perf dependency injection technique](CookBook.md#mocking-nonvirtual-methods).

## I wrote some matchers.  After I upgraded to a new version of Google Mock, they no longer compile.  What's going on? ##

After version 1.4.0 of Google Mock was released, we had an idea on how
to make it easier to write matchers that can generate informative
messages efficiently.  We experimented with this idea and liked what
we saw.  Therefore we decided to implement it.

Unfortunately, this means that if you have defined your own matchers
by implementing `MatcherInterface` or using `MakePolymorphicMatcher()`,
your definitions will no longer compile.  Matchers defined using the
`MATCHER*` family of macros are not affected.

Sorry for the hassle if your matchers are affected.  We believe it's
in everyone's long-term interest to make this change sooner than
later.  Fortunately, it's usually not hard to migrate an existing
matcher to the new API.  Here's what you need to do:

If you wrote your matcher like this:
```
// Old matcher definition that doesn't work with the latest
// Google Mock.
using ::testing::MatcherInterface;
...
class MyWonderfulMatcher : public MatcherInterface<MyType> {
 public:
  ...
  virtual bool Matches(MyType value) const {
    // Returns true if value matches.
    return value.GetFoo() > 5;
  }
  ...
};
```

you'll need to change it to:
```
// New matcher definition that works with the latest Google Mock.
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;
...
class MyWonderfulMatcher : public MatcherInterface<MyType> {
 public:
  ...
  virtual bool MatchAndExplain(MyType value,
                               MatchResultListener* listener) const {
    // Returns true if value matches.
    return value.GetFoo() > 5;
  }
  ...
};
```
(i.e. rename `Matches()` to `MatchAndExplain()` and give it a second
argument of type `MatchResultListener*`.)

If you were also using `ExplainMatchResultTo()` to improve the matcher
message:
```
// Old matcher definition that doesn't work with the lastest
// Google Mock.
using ::testing::MatcherInterface;
...
class MyWonderfulMatcher : public MatcherInterface<MyType> {
 public:
  ...
  virtual bool Matches(MyType value) const {
    // Returns true if value matches.
    return value.GetFoo() > 5;
  }

  virtual void ExplainMatchResultTo(MyType value,
                                    ::std::ostream* os) const {
    // Prints some helpful information to os to help
    // a user understand why value matches (or doesn't match).
    *os << "the Foo property is " << value.GetFoo();
  }
  ...
};
```

you should move the logic of `ExplainMatchResultTo()` into
`MatchAndExplain()`, using the `MatchResultListener` argument where
the `::std::ostream` was used:
```
// New matcher definition that works with the latest Google Mock.
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;
...
class MyWonderfulMatcher : public MatcherInterface<MyType> {
 public:
  ...
  virtual bool MatchAndExplain(MyType value,
                               MatchResultListener* listener) const {
    // Returns true if value matches.
    *listener << "the Foo property is " << value.GetFoo();
    return value.GetFoo() > 5;
  }
  ...
};
```

If your matcher is defined using `MakePolymorphicMatcher()`:
```
// Old matcher definition that doesn't work with the latest
// Google Mock.
using ::testing::MakePolymorphicMatcher;
...
class MyGreatMatcher {
 public:
  ...
  bool Matches(MyType value) const {
    // Returns true if value matches.
    return value.GetBar() < 42;
  }
  ...
};
... MakePolymorphicMatcher(MyGreatMatcher()) ...
```

you should rename the `Matches()` method to `MatchAndExplain()` and
add a `MatchResultListener*` argument (the same as what you need to do
for matchers defined by implementing `MatcherInterface`):
```
// New matcher definition that works with the latest Google Mock.
using ::testing::MakePolymorphicMatcher;
using ::testing::MatchResultListener;
...
class MyGreatMatcher {
 public:
  ...
  bool MatchAndExplain(MyType value,
                       MatchResultListener* listener) const {
    // Returns true if value matches.
    return value.GetBar() < 42;
  }
  ...
};
... MakePolymorphicMatcher(MyGreatMatcher()) ...
```

If your polymorphic matcher uses `ExplainMatchResultTo()` for better
failure messages:
```
// Old matcher definition that doesn't work with the latest
// Google Mock.
using ::testing::MakePolymorphicMatcher;
...
class MyGreatMatcher {
 public:
  ...
  bool Matches(MyType value) const {
    // Returns true if value matches.
    return value.GetBar() < 42;
  }
  ...
};
void ExplainMatchResultTo(const MyGreatMatcher& matcher,
                          MyType value,
                          ::std::ostream* os) {
  // Prints some helpful information to os to help
  // a user understand why value matches (or doesn't match).
  *os << "the Bar property is " << value.GetBar();
}
... MakePolymorphicMatcher(MyGreatMatcher()) ...
```

you'll need to move the logic inside `ExplainMatchResultTo()` to
`MatchAndExplain()`:
```
// New matcher definition that works with the latest Google Mock.
using ::testing::MakePolymorphicMatcher;
using ::testing::MatchResultListener;
...
class MyGreatMatcher {
 public:
  ...
  bool MatchAndExplain(MyType value,
                       MatchResultListener* listener) const {
    // Returns true if value matches.
    *listener << "the Bar property is " << value.GetBar();
    return value.GetBar() < 42;
  }
  ...
};
... MakePolymorphicMatcher(MyGreatMatcher()) ...
```

For more information, you can read these
[two](CookBook.md#writing-new-monomorphic-matchers)
[recipes](CookBook.md#writing-new-polymorphic-matchers)
from the cookbook.  As always, you
are welcome to post questions on `googlemock@googlegroups.com` if you
need any help.

## When using Google Mock, do I have to use Google Test as the testing framework?  I have my favorite testing framework and don't want to switch. ##

Google Mock works out of the box with Google Test.  However, it's easy
to configure it to work with any testing framework of your choice.
[Here](ForDummies.md#using-google-mock-with-any-testing-framework) is how.

## How am I supposed to make sense of these horrible template errors? ##

If you are confused by the compiler errors gcc threw at you,
try consulting the _Google Mock Doctor_ tool first.  What it does is to
scan stdin for gcc error messages, and spit out diagnoses on the
problems (we call them diseases) your code has.

To "install", run command:
```
alias gmd='<path to googlemock>/scripts/gmock_doctor.py'
```

To use it, do:
```
<your-favorite-build-command> <your-test> 2>&1 | gmd
```

For example:
```
make my_test 2>&1 | gmd
```

Or you can run `gmd` and copy-n-paste gcc's error messages to it.

## Can I mock a variadic function? ##

You cannot mock a variadic function (i.e. a function taking ellipsis
(`...`) arguments) directly in Google Mock.

The problem is that in general, there is _no way_ for a mock object to
know how many arguments are passed to the variadic method, and what
the arguments' types are.  Only the _author of the base class_ knows
the protocol, and we cannot look into his head.

Therefore, to mock such a function, the _user_ must teach the mock
object how to figure out the number of arguments and their types.  One
way to do it is to provide overloaded versions of the function.

Ellipsis arguments are inherited from C and not really a C++ feature.
They are unsafe to use and don't work with arguments that have
constructors or destructors.  Therefore we recommend to avoid them in
C++ as much as possible.

## MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter.  Why? ##

If you compile this using Microsoft Visual C++ 2005 SP1:
```
class Foo {
  ...
  virtual void Bar(const int i) = 0;
};

class MockFoo : public Foo {
  ...
  MOCK_METHOD1(Bar, void(const int i));
};
```
You may get the following warning:
```
warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
```

This is a MSVC bug.  The same code compiles fine with gcc ,for
example.  If you use Visual C++ 2008 SP1, you would get the warning:
```
warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
```

In C++, if you _declare_ a function with a `const` parameter, the
`const` modifier is _ignored_.  Therefore, the `Foo` base class above
is equivalent to:
```
class Foo {
  ...
  virtual void Bar(int i) = 0;  // int or const int?  Makes no difference.
};
```

In fact, you can _declare_ Bar() with an `int` parameter, and _define_
it with a `const int` parameter.  The compiler will still match them
up.

Since making a parameter `const` is meaningless in the method
_declaration_, we recommend to remove it in both `Foo` and `MockFoo`.
That should workaround the VC bug.

Note that we are talking about the _top-level_ `const` modifier here.
If the function parameter is passed by pointer or reference, declaring
the _pointee_ or _referee_ as `const` is still meaningful.  For
example, the following two declarations are _not_ equivalent:
```
void Bar(int* p);        // Neither p nor *p is const.
void Bar(const int* p);  // p is not const, but *p is.
```

## I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it.  What can I do? ##

We've noticed that when the `/clr` compiler flag is used, Visual C++
uses 5~6 times as much memory when compiling a mock class.  We suggest
to avoid `/clr` when compiling native C++ mocks.

## I can't figure out why Google Mock thinks my expectations are not satisfied.  What should I do? ##

You might want to run your test with
`--gmock_verbose=info`.  This flag lets Google Mock print a trace
of every mock function call it receives.  By studying the trace,
you'll gain insights on why the expectations you set are not met.

## How can I assert that a function is NEVER called? ##

```
EXPECT_CALL(foo, Bar(_))
    .Times(0);
```

## I have a failed test where Google Mock tells me TWICE that a particular expectation is not satisfied.  Isn't this redundant? ##

When Google Mock detects a failure, it prints relevant information
(the mock function arguments, the state of relevant expectations, and
etc) to help the user debug.  If another failure is detected, Google
Mock will do the same, including printing the state of relevant
expectations.

Sometimes an expectation's state didn't change between two failures,
and you'll see the same description of the state twice.  They are
however _not_ redundant, as they refer to _different points in time_.
The fact they are the same _is_ interesting information.

## I get a heap check failure when using a mock object, but using a real object is fine.  What can be wrong? ##

Does the class (hopefully a pure interface) you are mocking have a
virtual destructor?

Whenever you derive from a base class, make sure its destructor is
virtual.  Otherwise Bad Things will happen.  Consider the following
code:

```
class Base {
 public:
  // Not virtual, but should be.
  ~Base() { ... }
  ...
};

class Derived : public Base {
 public:
  ...
 private:
  std::string value_;
};

...
  Base* p = new Derived;
  ...
  delete p;  // Surprise! ~Base() will be called, but ~Derived() will not
             // - value_ is leaked.
```

By changing `~Base()` to virtual, `~Derived()` will be correctly
called when `delete p` is executed, and the heap checker
will be happy.

## The "newer expectations override older ones" rule makes writing expectations awkward.  Why does Google Mock do that? ##

When people complain about this, often they are referring to code like:

```
// foo.Bar() should be called twice, return 1 the first time, and return
// 2 the second time.  However, I have to write the expectations in the
// reverse order.  This sucks big time!!!
EXPECT_CALL(foo, Bar())
    .WillOnce(Return(2))
    .RetiresOnSaturation();
EXPECT_CALL(foo, Bar())
    .WillOnce(Return(1))
    .RetiresOnSaturation();
```

The problem is that they didn't pick the **best** way to express the test's
intent.

By default, expectations don't have to be matched in _any_ particular
order.  If you want them to match in a certain order, you need to be
explicit.  This is Google Mock's (and jMock's) fundamental philosophy: it's
easy to accidentally over-specify your tests, and we want to make it
harder to do so.

There are two better ways to write the test spec.  You could either
put the expectations in sequence:

```
// foo.Bar() should be called twice, return 1 the first time, and return
// 2 the second time.  Using a sequence, we can write the expectations
// in their natural order.
{
  InSequence s;
  EXPECT_CALL(foo, Bar())
      .WillOnce(Return(1))
      .RetiresOnSaturation();
  EXPECT_CALL(foo, Bar())
      .WillOnce(Return(2))
      .RetiresOnSaturation();
}
```

or you can put the sequence of actions in the same expectation:

```
// foo.Bar() should be called twice, return 1 the first time, and return
// 2 the second time.
EXPECT_CALL(foo, Bar())
    .WillOnce(Return(1))
    .WillOnce(Return(2))
    .RetiresOnSaturation();
```

Back to the original questions: why does Google Mock search the
expectations (and `ON_CALL`s) from back to front?  Because this
allows a user to set up a mock's behavior for the common case early
(e.g. in the mock's constructor or the test fixture's set-up phase)
and customize it with more specific rules later.  If Google Mock
searches from front to back, this very useful pattern won't be
possible.

## Google Mock prints a warning when a function without EXPECT\_CALL is called, even if I have set its behavior using ON\_CALL.  Would it be reasonable not to show the warning in this case? ##

When choosing between being neat and being safe, we lean toward the
latter.  So the answer is that we think it's better to show the
warning.

Often people write `ON_CALL`s in the mock object's
constructor or `SetUp()`, as the default behavior rarely changes from
test to test.  Then in the test body they set the expectations, which
are often different for each test.  Having an `ON_CALL` in the set-up
part of a test doesn't mean that the calls are expected.  If there's
no `EXPECT_CALL` and the method is called, it's possibly an error.  If
we quietly let the call go through without notifying the user, bugs
may creep in unnoticed.

If, however, you are sure that the calls are OK, you can write

```
EXPECT_CALL(foo, Bar(_))
    .WillRepeatedly(...);
```

instead of

```
ON_CALL(foo, Bar(_))
    .WillByDefault(...);
```

This tells Google Mock that you do expect the calls and no warning should be
printed.

Also, you can control the verbosity using the `--gmock_verbose` flag.
If you find the output too noisy when debugging, just choose a less
verbose level.

## How can I delete the mock function's argument in an action? ##

If you find yourself needing to perform some action that's not
supported by Google Mock directly, remember that you can define your own
actions using
[MakeAction()](CookBook.md#writing-new-actions) or
[MakePolymorphicAction()](CookBook.md#writing_new_polymorphic_actions),
or you can write a stub function and invoke it using
[Invoke()](CookBook.md#using-functions_methods_functors).

## MOCK\_METHODn()'s second argument looks funny.  Why don't you use the MOCK\_METHODn(Method, return\_type, arg\_1, ..., arg\_n) syntax? ##

What?!  I think it's beautiful. :-)

While which syntax looks more natural is a subjective matter to some
extent, Google Mock's syntax was chosen for several practical advantages it
has.

Try to mock a function that takes a map as an argument:
```
virtual int GetSize(const map<int, std::string>& m);
```

Using the proposed syntax, it would be:
```
MOCK_METHOD1(GetSize, int, const map<int, std::string>& m);
```

Guess what?  You'll get a compiler error as the compiler thinks that
`const map<int, std::string>& m` are **two**, not one, arguments. To work
around this you can use `typedef` to give the map type a name, but
that gets in the way of your work.  Google Mock's syntax avoids this
problem as the function's argument types are protected inside a pair
of parentheses:
```
// This compiles fine.
MOCK_METHOD1(GetSize, int(const map<int, std::string>& m));
```

You still need a `typedef` if the return type contains an unprotected
comma, but that's much rarer.

Other advantages include:
  1. `MOCK_METHOD1(Foo, int, bool)` can leave a reader wonder whether the method returns `int` or `bool`, while there won't be such confusion using Google Mock's syntax.
  1. The way Google Mock describes a function type is nothing new, although many people may not be familiar with it.  The same syntax was used in C, and the `function` library in `tr1` uses this syntax extensively.  Since `tr1` will become a part of the new version of STL, we feel very comfortable to be consistent with it.
  1. The function type syntax is also used in other parts of Google Mock's API (e.g. the action interface) in order to make the implementation tractable. A user needs to learn it anyway in order to utilize Google Mock's more advanced features.  We'd as well stick to the same syntax in `MOCK_METHOD*`!

## My code calls a static/global function.  Can I mock it? ##

You can, but you need to make some changes.

In general, if you find yourself needing to mock a static function,
it's a sign that your modules are too tightly coupled (and less
flexible, less reusable, less testable, etc).  You are probably better
off defining a small interface and call the function through that
interface, which then can be easily mocked.  It's a bit of work
initially, but usually pays for itself quickly.

This Google Testing Blog
[post](http://googletesting.blogspot.com/2008/06/defeat-static-cling.html)
says it excellently.  Check it out.

## My mock object needs to do complex stuff.  It's a lot of pain to specify the actions.  Google Mock sucks! ##

I know it's not a question, but you get an answer for free any way. :-)

With Google Mock, you can create mocks in C++ easily.  And people might be
tempted to use them everywhere. Sometimes they work great, and
sometimes you may find them, well, a pain to use. So, what's wrong in
the latter case?

When you write a test without using mocks, you exercise the code and
assert that it returns the correct value or that the system is in an
expected state.  This is sometimes called "state-based testing".

Mocks are great for what some call "interaction-based" testing:
instead of checking the system state at the very end, mock objects
verify that they are invoked the right way and report an error as soon
as it arises, giving you a handle on the precise context in which the
error was triggered.  This is often more effective and economical to
do than state-based testing.

If you are doing state-based testing and using a test double just to
simulate the real object, you are probably better off using a fake.
Using a mock in this case causes pain, as it's not a strong point for
mocks to perform complex actions.  If you experience this and think
that mocks suck, you are just not using the right tool for your
problem. Or, you might be trying to solve the wrong problem. :-)

## I got a warning "Uninteresting function call encountered - default action taken.."  Should I panic? ##

By all means, NO!  It's just an FYI.

What it means is that you have a mock function, you haven't set any
expectations on it (by Google Mock's rule this means that you are not
interested in calls to this function and therefore it can be called
any number of times), and it is called.  That's OK - you didn't say
it's not OK to call the function!

What if you actually meant to disallow this function to be called, but
forgot to write `EXPECT_CALL(foo, Bar()).Times(0)`?  While
one can argue that it's the user's fault, Google Mock tries to be nice and
prints you a note.

So, when you see the message and believe that there shouldn't be any
uninteresting calls, you should investigate what's going on.  To make
your life easier, Google Mock prints the function name and arguments
when an uninteresting call is encountered.

## I want to define a custom action.  Should I use Invoke() or implement the action interface? ##

Either way is fine - you want to choose the one that's more convenient
for your circumstance.

Usually, if your action is for a particular function type, defining it
using `Invoke()` should be easier; if your action can be used in
functions of different types (e.g. if you are defining
`Return(value)`), `MakePolymorphicAction()` is
easiest.  Sometimes you want precise control on what types of
functions the action can be used in, and implementing
`ActionInterface` is the way to go here. See the implementation of
`Return()` in `include/gmock/gmock-actions.h` for an example.

## I'm using the set-argument-pointee action, and the compiler complains about "conflicting return type specified".  What does it mean? ##

You got this error as Google Mock has no idea what value it should return
when the mock method is called.  `SetArgPointee()` says what the
side effect is, but doesn't say what the return value should be.  You
need `DoAll()` to chain a `SetArgPointee()` with a `Return()`.

See this [recipe](CookBook.md#mocking_side_effects) for more details and an example.


## My question is not in your FAQ! ##

If you cannot find the answer to your question in this FAQ, there are
some other resources you can use:

  1. read other [documentation](Documentation.md),
  1. search the mailing list [archive](http://groups.google.com/group/googlemock/topics),
  1. ask it on [googlemock@googlegroups.com](mailto:googlemock@googlegroups.com) and someone will answer it (to prevent spam, we require you to join the [discussion group](http://groups.google.com/group/googlemock) before you can post.).

Please note that creating an issue in the
[issue tracker](https://github.com/google/googletest/issues) is _not_
a good way to get your answer, as it is monitored infrequently by a
very small number of people.

When asking a question, it's helpful to provide as much of the
following information as possible (people cannot help you if there's
not enough information in your question):

  * the version (or the revision number if you check out from SVN directly) of Google Mock you use (Google Mock is under active development, so it's possible that your problem has been solved in a later version),
  * your operating system,
  * the name and version of your compiler,
  * the complete command line flags you give to your compiler,
  * the complete compiler error messages (if the question is about compilation),
  * the _actual_ code (ideally, a minimal but complete program) that has the problem you encounter.